#! /bin/bash
#echo "$0 $*"
option="none"
case "$1" in
-*)
	option="$1"
	shift
	;;
esac
File="$1"
Original="$2"
Result="$3"
download_source="http://download.sisalp.net/scripts/ADD"
case "$option" in
-h|--help)
	echo "$0 : add a string to lines which contain a key string"
	$0 --version
	echo "	Usage	: $0 [-s|--save] file_path \"key_string\" \"added_string\""
	echo "	 	--save option will backup file before changing"
	echo "	Usage: $0 --help			: print this help"
	echo "	Usage: $0 --version			: print version and exit"
	echo "	Usage: $0 --update [download_source]	: update from $download_source and exit"
	exit 0
	;;
-v|--version)
	echo "$0 version 1 revision 0 30 octobre 2015"
	exit 0
	;;
-u|--update)
	CURRENTUSER=`whoami`
	if [ ! -z "$1" ] ; then
		download_source="$1"
	fi
	case "$CURRENTUSER" in
	root)
		OLDVERSION=`$0 --version`
		cd /usr/local/bin
		mv $0 $0.old
		if wget -q $download_source ; then
			chmod 755 $0
			rm $0.old
			NEWVERSION=`$0 --version`
			case "$NEWVERSION" in
			$OLDVERSION)
				echo "$0 is uptodate $NEWVERSION"
				;;
			*)
				echo "$0 downloaded new version from $download_source $NEWVERSION"
				;;
			esac
		else
			echo "cannot download new version from $download_source"
			rm $0
			mv $0.old $0
		fi
		exit 0
		;;
	*)
		echo "You must get administration priviledges root to succeed, please consider sudo"
		exit 1
		;;
	esac
	;;
esac
if [ ! -f "$File" ] || [ ! -w "$File" ] ; then
	echo "$LINENO `date` File $File is not found or modification is not permitted and won't be changed"
	exit 1
fi
cp --archive --backup=numbered $File $File.save
OldContent=`cat $File`
if ! echo "$OldContent" | grep -q "$Original" ; then
	echo "$LINENO `date` string $Original is not found in $File"
else
	LinesToChange=`echo "$OldContent" | grep -e "$Original"`
	#echo "found : $LinesToChange"
	old_IFS=$IFS
	IFS=$'\n'
	for linetochange in $LinesToChange ; do
		IFS=$old_IFS
		#echo "traite $linetochange"
		if ! echo "$linetochange" | grep -eq "$Result" ; then
			#echo "ligne non trouvee et modifiee : $linetochange	$Result" ; 
			NewContent=`echo "$OldContent" | sed s!"$linetochange"!"$linetochange	$Result"!`
			OldContent="$NewContent"
		fi
		IFS=$'\n'
	done
	IFS=$old_IFS
	echo "$OldContent" > $File
	diff $File.save $File
fi
case "$option" in
--save|-s)
	;;
*)
	rm $File.save
	;;
esac
exit 0
