#!/bin/bash
#
# File: /usr/local/bin/inkabasisupdater or
#       /usr/local/share/inka-basis/inkabasisupdater
#
# Updates an old version of inka-basis to an by inkapkgupdate
# downloaded new version
#
#    Copyright (C) 2013  Ingo 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
. /usr/local/etc/inka-basis.conf			# global config
. $LLIBDIR/lib-inka-std.sh				# functions general
. $LLIBDIR/lib-inka-basis.sh				# functions basis
##############################################################################
# DECLARATION OF VARIABLES

# STRINGS
pkgname=inka-basis					# package name
lib_inka_std_sh_needed=1.3.6				# standard lib version
lib_inka_basis_sh_needed=1.3.3				# basis lib version
conf_file_needed=1.3.0					# conf file version
version=1.3.7						# version
#----------------------- end of variables to configure -----------------------
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 -------------------------
auto=--automatic					# auto=""/--automatic
infofile=/usr/local/share/inka-basis/aktual-inka-basis	# info file

# 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...
Installiert die neue heruntergeladene Version des Pakets inka-basis.
Der Aufruf erfolgt durch die cron-Datei einer bereits installierten Version.

        -x      neue Version installieren
-h, --help      Hilfe anzeigen und beenden
 --version      Versionsinformationen anzeigen und beenden
--show-config   Programmkonfiguration anzeigen und beenden
   --debug      Debug-Modus benutzen
        -q      nur mit Fehlermeldungen
        -v      mit vielen Meldungen

EOT

return
}
#-----------------------------------------------------------------------------
function show_config ()
{
# Show configuration of program
# Uses: cat, cut, grep
# Return codes: standard

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

cat <<EOT

Lokales Paketverzeichnis von .tgz, .tar.gz, .tar, .tar.bz2:
$PackageDir

Programm wird zu folgenden Zeiten aufgerufen:
EOT
grep "&&" /etc/cron.d/inkabasisupdater.cron | cut -f 1

return
}
#-----------------------------------------------------------------------------
function main_proc ()
{
# Test .dat file exist. if yes, get info about new version and install it
# Variables: infofile, InstVers, NewVers, OldVers
# Uses: cat, cd, cp, echo, grep, rm
# Return codes: standard

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

local pkgn vers fnne err
pkgn=""	# name of new package
vers=""	# version of new package
fnne=""	# filename of new package
err=0

if [ -e $infofile ]; then				# info file exist
	. $infofile					# source file
	if [ "$InstVers" != "$NewVers" ]; then		# InstVers differ NewVers
		if [ "$InstVers" != "" ]; then
			# small uninstall old package
			cd $PackageDir/$InstVers
			./install.sh -u $auto
		fi
		# now install new package
		cd $PackageDir/$NewVers
		./install.sh -i $auto			# install new inka-basis version
		if [ $? -eq 0 ]; then			# installation of new inka-basis ok
			# remove other inka-basis dirs
			Rebuild_Pkg_Filename $NewVers	# Decomposite file name
			Pop_Stack pkgn
			Pop_Stack vers
			Pop_Stack fnne
			Clean_Up_Pkgdir $pkgn $fnne
			# write new $InstVers to info file
			. $infofile
			echo "NewVers=$NewVers" > $infofile
			echo "InstVers=$NewVers" >> $infofile
			if [ "$verbose" != "-q" ]; then
				echo "$NewVers wurde installiert."
			fi
		else	# installation of new inka-basis failed
			echo " Fehler - Paket $NewVers konnte nicht installiert werden!"
			return 99
		fi
	fi
else							# $infofile is missing
	echo "Fehler - $infofile fehlt"
	return 8
fi

return $err
}
##############################################################################
# PARSE COMMANDLINE

# 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, --show-config 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
		--show-config)	opt=--s;;			# option --show-config
		--debug)	debug=yes;;			# option --debug
		-q|--quiet)	verbose=-q;;			# option -q
		-v|--verbose)	verbose=-v;;			# option -v
#-------------------------- end of standard options --------------------------
	  -x)	opt="$1";;				# option -x
	  *)
		echo "Fehler - Option $1 falsch!" >&2	# error
		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
  --s)	show_config; exit 0;;					# show config
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
##############################################################################
# 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
  -x)							# opt -x
	main_proc
	err=$?;;
  "")							# no option given
	echo "Fehler - Option fehlt!" >&2
	err=1;;
esac
exit $err
