#!/bin/bash
#
# Generates an autofs map file based on the list of ISOs supplied on stdin
# Author: Pieter Hollants <pieter@hollants.com>

need_to_flush()
{
	# Do we need to flush out the previous Multi-DVD set first?
	if [ ${#LASTREST} -gt 0 -a "$REST" != "$LASTREST" ]
	then
		echo "$LASTREST \\"
		for (( i=0; i<${#MULTI[@]}; i++ ))
		do
			echo -n "${MULTI[$i]}"
			if [ $i -lt $(( ${#MULTI[@]} - 1 )) ] ; then
				echo -n " \\"
			fi
			echo ""
		done
		LASTREST=""
		MULTI=()
	fi
}

echo "# This file automatically generated by update_autofs_maps.sh"

# Process ISO filenames supplied on stdin
while read ISO; do

	# Find base name of iso without path prefix and .iso suffix
	NAME=${ISO##*/}
	NAME=${NAME%.iso}

	# Set $dvd only if ISO belongs to a multi-DVD set
	DVD=$(echo "$NAME" | sed 's/.*\(DVD[0-9]\?\).*/\1/')
	[ "$DVD" == "DVD" ] && DVD=""

	# Compose $rest as $name without a "-DVD" part
	REST=$(echo "$NAME" | sed 's/-\(DVD[0-9]\?\)//')

	need_to_flush

	# Multi-DVD set?
	if [ -n "$DVD" ]
	then
		if [ "$REST" != "$LASTREST" ] ; then
			LASTREST="$REST";
		fi
		MULTI[${#MULTI[@]}]=" /$DVD -fstype=iso9660,ro,loop :$ISO"
	else
		echo "$REST -fstype=iso9660,ro,loop :$ISO"
	fi
done

REST=""
need_to_flush
