#!/bin/bash
#
# File: /usr/local/bin/repl-inka-cnfvar
#
# Replace a configuration variable in a file.
#
#    Copyright (C) 2013 Ingo Kaesmann
#    Code from replcnfvar 2008 by Juergen Kaesmann
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#
# Script template: 0.3.0
#
# Exit codes:
# 0 = OK
# 1 = Error in parameters
# 2 = Error in configfile, configfile old or not found
# 3 = Library old or not found
# 8 = Error in other file or other file not found
# 99= Other error
##############################################################################
# SOURCE FILES

. /usr/local/etc/main-inka-sh.conf			# config main
. $LLIBDIR/lib-inka-std.sh				# functions general
##############################################################################
# DECLARATION OF VARIABLES

# STRINGS
pkgname=inka-basis					# package name
lib_inka_std_sh_needed=1.3.6				# standard lib version
#----------------------- end of variables to configure -----------------------
version=$(grep "^VERSION" $PROGREG/$pkgname.inf | cut -f 2)	# version
scriptname=$(basename $0)				# name of script
tempfile=$TEMPDIR/$scriptname.$UID.$$.tmp		# temporary file
infolog="logger -p user.info -t $scriptname --"		# log info messages
errlog="logger -p user.err -t $scriptname -- ERROR:"	# log error messages
debuglog="logger -p user.debug -t $scriptname -- DEBUG:" # log debug messages
debug=no						# debug=yes/no
verbose=""						# verbose=""/-q/-v
opt_found=no						# opt_found=yes/no
opt=""							# option
#------------------------- end of standard variables -------------------------
cnffile=''						# conf file
cnfvar=''						# conf var name
cnfval=''						# new value
arg1=''							# 1. arg from cmdline

# NUMBERS
err=0							# exit code
##############################################################################
# FUNCTIONS

function show_help ()
{
# Show help
# Uses: cat
# Return codes: standard

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG show_help: $# $@" >&2
	#$debuglog show_help: $# $@
fi

cat <<EOT

Aufruf: $scriptname [OPTION]... DATEI VARIABLE WERT
Ersetzt den Wert einer Variablen in einer Konfigurationsdatei

-h, --help      Hilfe anzeigen und beenden
 --version       Versionsinformationen anzeigen und beenden
   --debug      Debug-Modus benutzen
	-q      Mit wenigen Fehlermeldungen
	-v      Mit Erklaerungen der Taetigkeiten

DATEI:          Konfigurationsdatei, deren Variable neuen Wert erhalten soll
VARIABLE:       Variable, deren Wert geaendert werden soll
WERT:           Wert, der der Variablen zugewiesen werden soll
EOT

return
}
#-----------------------------------------------------------------------------
function set_cnf ()
{
# Sets the value of a cnfvar in a cnffile
# Par1:
# Variables: cnffile = file to configure, cnfvar = variable, cnfval = new value
# Uses: cat, cp, echo, grep, rm
# Return codes:
# 0 = ok
# 99= error

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG set_cnf: $# $@" >&2
fi

local cnfline s tfile1 tfile2 l ret
cnfline="${cnfvar}=${cnfval}"				# new conf line
s=''
tfile1=$tempfile.1.tmp
tfile2=$tempfile.2.tmp
l=0
ret=0

# find first line with conf var
if [ "$verbose" == "-v" ]; then				# verbose
	echo "Replace: $cnffile $cnfvar $cnfval"
fi

s=$(cat $cnffile | grep -n -m 1 "^[[:space:]]*$cnfvar=")	# read line of new conf file
ret=$?
if [ "$ret" -eq 0 ]; then				# cnfvar found
	l=${s%%:*}					# rm ':*' from EOL

	# del line with conf var
	if [ "$debug" == "yes" ]; then			# debug
		echo "DEBUG Remove Line: $l"
	fi
	Erase_Lines $cnffile $l $l > $tfile1
	ret=$?
	if [ "$ret" -eq 0 ]; then			# insert new line
		let l--
		if [ "$debug" == "yes" ]; then		# debug
			echo "DEUBG Insert Line: $l $cnfline"
		fi
		Write_Line $tfile1 $l "$cnfline" > $tfile2
		ret=$?
		if [ "$ret" -eq 0 ]; then		# cp all to cnffile
			cp $tfile2 $cnffile
		else
			ret=99
		fi
	else
		ret=99
	fi
else
	ret=99
fi

rm -f $tfile1 $tfile2
return $ret
}
##############################################################################
# PARSE COMMANDLINE	# bearbeiten

# Read all options with args and all additional args into variables.
# Stop parsing after last parameter.
# Try to do a check on all parameters and version numbers.
# Handle options -h, -C and -V directly.
# Exit on error.

if [ "$debug" == "yes" ]; then				# DEBUG
	echo "DEBUG Parse Commandline: $# $@" >&2
	#$debuglog Parse Commandline: $# $@
fi

# get options and options with arguments
while [ "${1:0:1}" == "-" ]; do				# get all options
	case "$1" in
	  -h|--help)	opt=-h;;			# option -h
	  --version)	opt=--v;; 			# option --version
	  --debug)	debug=yes;;			# option --debug
	  -q|--quiet)	verbose=-q;;			# option -q
	  -v|--verbose)	verbose=-v;;			# option -v
#-------------------------- end of standard options --------------------------
	  *)	if [ "$verbose" != "-q" ]; then
			echo "Fehler - Option $1 falsch!" >&2	# error
		else
			$errlog unknown option $1
		fi
		exit 1;;
	esac
	shift
	opt_found=yes
done

# handle standard options -h, -V, -C
case "$opt" in
  -h)	show_help; exit 0;;					# show help
  --v)	echo "$scriptname (${pkgname}) $version"; exit 0;;	# show version
esac

# check library
Compare_Version $lib_inka_std_sh_needed $Lib_Inka_Std_Sh_Version
ret=$?						# ret: 0,1,2,9,127
if [ $ret -eq 1 ]; then		# needed lib-version higher than installed
	if [ "$verbose" != "-q" ]; then
		echo "Fehler - Programm benoetigt neuere Version von lib-inka-std.sh!" >&2
	else
		$errlog newer version of lib-inka-std.sh needed
	fi
	exit 3
elif [ $ret -eq 9 ] || [ $ret -eq 127 ]; then	# other error (version or lib missing)
	if [ "$verbose" != "-q" ]; then
		echo "Fehler - Versionspruefung von lib-inka-std.sh nicht moeglich!"
	else
		$errlog check of version of lib-inka-std.sh impossible
	fi
	exit 3
else						# check ok, reset $ret
	ret=0
fi

# check arguments after options
case "$opt" in
  '')
	if [ "$#" -eq 3 ]; then				# parameter count ok
		cnffile="$1"
		cnfvar="$2"
		cnfval="$3"
		shift 3
	else						# error in param count
		echo "Fehler - Parameteranzahl falsch!" >&2
		exit 1
	fi;;
  *)	if [ "$#" -ne 0 ]; then				# error in param count
		echo "Fehler - Parameteranzahl falsch!" >&2
		exit 1
	fi;;
esac
##############################################################################
# MAINPROGRAM

if [ "$debug" == "yes" ]; then				# debug
	echo "DEBUG Main: $# $@" >&2
	#$debuglog Main: $# $@
fi

# Check what to do (initial options and args are removed from cmdline)
case "$opt" in
  "")							# no opt given
	set_cnf
	err=$?;;
esac
exit $err
