#!/bin/bash

. ${TOOLKIT}-functions.sh

#----------------------------------------------------------------
# /etc/fstab patching (adds extra entries)
#----------------------------------------------------------------


outfile=tmpfstab.tmp	# non uso fstab.tmp, conflict jtconf --list fstab.
orig=/etc/fstab
cp $orig $outfile || exit $?

myself=$(uname -n)
myshort=$(uname -n | sed -e 's/\..*//')

# 2017.08.25 changed comment format
old_comment="# entries added by kusa"
new_comment="#kusa-cli-fs entries"

[ $myself = $myshort ] && myshort=


# elimina le righe precedentemente create (comprese tra
# $comment ... START e $comment END)
#
copy=true
cat $outfile | while read line
do
	case "$line" in
		${old_comment}*START)	copy=false ;;
		${old_comment}*END)	copy=true ; continue ;;
		${new_comment}*START)	copy=false ;;
		${new_comment}*END)	copy=true ; continue ;;
	esac
	$copy && echo "$line"
done >$outfile.1.tmp
mv $outfile.1.tmp $outfile || exit $?


echo "$new_comment START" >>$outfile

# cerca nelle sezioni [fstab.xxxx] le eventuali definizioni per
# tutti gli hosts (*) e se stesso (hostname)
#
for section in $(jtconf --list fstab.)
do
	###echo ">>> section='$section'" ###
	host=$(echo "$section" | sed -e 's/.*\.//')
	###echo ">>> host='$host'" ###

	[ "$host" = "$myself" -o "$host" = "$myshort" -o "$host" = "*" ] || continue

	entries=$(jtconf --listvars "$section" 2>/dev/null || :)
	###echo ">>> entries='$entries'" ###
	[ "$entries" = "" ] && continue

	echo "$new_comment for host: '$host'" >>$outfile

	for key in $entries
	do
		entry=$(jtconf "$section.$key")
		id=$(echo "$key" | sed -e 's/<dot>/./g')
		###echo ">>> key='$key' id='$id' entry='$entry'"
		[ "$entry" = "" ] && continue

		set $entry
		mount=$1

		# my own share?
		server=
		case $id in
		  *:/*)	server=$(echo $id | sed -e 's/:.*//') ;;			# nfs
		  //*)	server=$(echo $id | sed -e 's/^..//' -e 's#/.*##') ;;	# samba
		esac
		[ "$server" ] && {
			[ $server = $myself -o $server = $myshort ] && {
				###echo ">>> ignore server='$server' for id='$id'" >&2
				continue
			}
		}

		string=$(printf "%-20s %s\n" "$id" "$entry")
		echo "  fstab: $id" >&2
		echo "$string" >> $outfile

		[ -d $mount ] || {
			create_dir $mount root:root || exit $?
		}
	done
done
echo "$new_comment END" >>$outfile

exit 0
