#!/bin/bash
#
# File: /usr/local/bin/installbyuser-gpgswitch
#
# Installs a users ~/.gpgswitchrc and ~/.gpgkey
#
#
#    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.6
#
# Exit codes:
# 0 = OK
# 1 = Error in parameters
# 3 = Library old or not found
# 4 = Error in other file or other file not found
# 8 = File exist
# 99= Other error
##############################################################################
# SOURCE STANDARD FILES

. /usr/local/etc/main-inka-sh.conf			# config main
. $LLIBDIR/lib-inka-std.sh				# functions standard
#test -e /usr/local/etc/xyz.conf && . /usr/local/etc/xyz.conf	# global config
##############################################################################
# DECLARATION OF VARIABLES

# STRINGS
pkgname=ksm-gpgswitch-inka				# package name
lib_inka_std_sh_needed=1.3.6				# standard lib version
#conf_file_needed=0.0.0					# conf file version
#--------------- end of variables to configure -------------------------------
progreg=$PROGREG					# registry directory
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=yes/no/""
opt_found=no						# opt_found=yes/no
opt=''							# option
#------------------End Of Standard Variables----------------------------------
#--------------- start of variables to configure -----------------------------
#bft=/usr/local/share/inka-x/x			# exec file template
#bf=$HOME/bin/x					# exec file
cft=/usr/local/share/$pkgname/gpgswitchrc	# conf file template
cf=$HOME/.gpgswitchrc				# conf file or
#cdir=$HOME/.x					#   conf dir and
#cf=""						#   conf file (""), is set in mainprog
#df1dir=""					# dat1 dir
df1t=/usr/local/share/$pkgname/gpgkey		# dat1 file template
#df1=$HOME/$df1dir/.x.dat1			# dat1 file
df1=$HOME/.gpgkey				# dat1 file
# NUMBERS
err=0						# error code of program
ret=0						# return code of function
##############################################################################
# FUNCTIONS

function show_help ()
{
# Show helptext
# Uses: cat, echo
# Return codes: standard

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

cat <<EOT

Aufruf: $scriptname OPTION...
Installiert/Deinstalliert anwenderseitig das Programm des Pakets
$pkgname Version $version
(Wird nur von nach der Installation eingerichteten Benutzern benoetigt.)

        -i      Installiert das Programm anwenderseitig
                  $cf wird neu angelegt
                  $df1 wird neu angelegt
                  Die Dateien muessen den Erfordernissen angepasst werden
        -U      Deinstalliert das Programm anwenderseitig
                  programmbezogene Konfigurationsdateien in ~/ werden entfernt
                  programmbezogene Benutzerdatendateien in ~/ werden entfernt
-h, --help      Hilfe anzeigen und beenden
 --version      Versionsinformationen anzeigen und beenden
   --debug      Debug-Modus benutzen
        -q      ohne Meldungen
        -v      mit vielen Meldungen


EOT
return
}
#-----------------------------------------------------------------------------
function install_bin ()
{
# Installs a new executable file
# Uses: cp, echo
# Return codes: 0 = ok, 8 = file exist, 99 = other error

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

local ret
ret=0

# test bin file exist
if [ -e $bf ]; then
	echo "$bf existiert bereits!" >&2
	return 8
fi

echo "Installiere $bf"
cp $bft $bf						# install new bin file
ret=$?
if [ $ret -eq 0 ]; then					# ok
	echo "$bf wurde installiert."
else							# error
	echo "Fehler beim Kopieren von $bft !" >&2
	ret=99
fi

return $ret
}
#-----------------------------------------------------------------------------
function uninstall_bin ()
{
# Uninstalls an executable file
# Par1: -u, -U
# Uses: echo, rm
# Return codes: 0 = ok, 99 = other error

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

local p1 ret
p1=$1							# -u or -U
ret=0

echo "Deinstalliere $bf"
rm $bf							# uninstall bin file
ret=$?
if [ $ret -eq 0 ]; then					# ok
	echo "$bf wurde deinstalliert."
else							# error
	echo "Fehler beim Deinstallieren von $bf !" >&2
	ret=99
fi

return $ret
}
#-----------------------------------------------------------------------------
function install_cnf ()
{
# Installs a new configuration file
# Uses: cp, echo, test
# Return codes: 0 = ok, 8 = file exist, 99 = other error

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

local ret
ret=0

# test conf file exist
if [ -e $cf ]; then
	echo "$cf existiert bereits!" >&2
	return 8
fi

echo "Installiere $cf"
if [ -n "$cdir" ]; then					# if variable $cdir exist
	mkdir -p $cdir					#   make conf dir, if not exist
fi
cp $cft $cf						# install new conf file
ret=$?
if [ $ret -eq 0 ]; then					# ok
	chmod 600 $cf					# set permision
	echo "$cf wurde neu installiert und muss konfiguriert werden."
else							# error
	echo "Fehler beim Kopieren von $cft !" >&2
	ret=99
fi

return $ret
}
#-----------------------------------------------------------------------------
function uninstall_cnf ()
{
# Uninstalls an configuration file
# Par1: -u, -U
# Uses: echo, rm, rmdir
# Return codes: 0 = ok, 99 = other error

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

local p1 ret
p1=$1							# -u or -U
ret=0

# if -U is given and $cdir is given, deinstall all config files
if [ "$p1" == "-U" ] && [ -n "$cdir" ] ; then
	echo "Deinstalliere $cdir"
	test -d $cdir && rm -r $cdir			#   remove ~/.PROGRAM/
	if [ -d $cdir ]; then
		echo "Fehler beim Deinstallieren von $cdir!"
		ret=99
	else
		echo "$cdir wurde deinstalliert."
	fi
# if -u is given, deinstall named conf file, if $cdir is not given, deinstall conf file
elif [ "$p1" == "-u" ] || [ -z "$cdir" ]; then
	echo "Deinstalliere $cf"
	rm $cf $cf~					# uninstall conf file
	ret=$?
	if [ $ret -eq 0 ]; then				# ok
		echo "$cf wurde deinstalliert."
	else						# error
		echo "Fehler beim Deinstallieren von $cf!"
		ret=99
	fi
	if [ -n "$cdir" ]; then				# if variable $cdir is given
		test -d $cdir && rmdir --ignore-fail-on-non-empty $cdir	#   remove conf dir, if empty
		if [ -d $cdir ]; then
			echo "$cdir wurde nicht deinstalliert."
		else
			echo "$cdir wurde deinstalliert."
		fi
	fi
fi

return $ret
}
#-----------------------------------------------------------------------------
function install_dat1 ()
{
# Installs a dat1 file				### edit this function ###
# Uses: cp, echo, test
# Return codes: 0 = ok, 8 = file exist, 99 = other error

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

local ret
ret=0

# test dat1 file exist
if [ -e "$df1" ]; then
	echo "$df1 existiert bereits!" >&2
	return 8
fi

echo "Installiere $df1"
if [ -n "$df1dir" ]; then				# if $df1dir given
	mkdir -p $HOME/$df1dir				#   make dir in ~/
fi
cp $df1t $df1						# install new file
ret=$?
if [ $ret -eq 0 ]; then					# ok
	chmod 600 $cf					# set permision
	echo "$df1 wurde installiert."
else							# error
	echo "Fehler beim Kopieren von $df1 !" >&2
	ret=99
fi

return $ret
}
#-----------------------------------------------------------------------------
function uninstall_dat1 ()
{
# Uninstalls a dat1 file			### edit this function ###
# Par1: -u, -U
# Uses: echo, rm
# Return codes: 0 = ok, 99 = other error

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

local p1 ret
p1=$1							# -u or -U
ret=0

echo "Deinstalliere $df1"
rm $df1							# uninstall dat file 1
ret=$?
if [ $ret -eq 0 ]; then					# ok
	echo "$df1 wurde deinstalliert."
else							# error
	echo "Fehler beim Deinstallieren von $df1 !" >&2
	ret=99
fi
if [ -n "$df1dir" ]; then				# if $df1dir given
	rmdir $HOME/$df1dir
fi

return $ret
}
##############################################################################
# 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, -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 -d
	  -q|--quiet)	verbose=-q;;			# option -q
	  -v|--verbose)	verbose=-v;;			# option -v
#-------------------------- end of standard options --------------------------
	  -i|-U)	opt="$1";;			# option -i, -u, -U
#	  -z)	opt_z=$1;;				# option -z
#	  -z)	opt_z=$1				# option -z + 1 arg
#		if [ "$#" -gt 1 ] & [ "${2:0:1}" != "-" ]; then	# par2 is 1.arg of opt_z
#			opt_z1=$2
#			shift		# shift option and all args - 1 arg
#		else					# error no arg
#			if [ "$verbose" != no ]; then
#				echo "Fehler - Wert fuer Option $1 fehlt!" >&2
#			else
#				$errlog arg for option $1 is missing
#			fi
#			exit 1
#		fi;;
	  *)	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
case "$opt" in
  -h)	show_help; exit 0;;					# show help
  --v)	echo "$scriptname (${pkgname}) $version"; exit 0;;	# show version
esac

# check arguments after options (comment, if not needed)
case "$opt" in
#  ""|-i|-u)	if [ $# -eq 1 ]; then			# parameter count ok
#				arg1="$1"
#				shift
#		else					# error in param count
#			if [ "$verbose" != "-q" ]; then
#				echo "Fehler - Parameteranzahl falsch!" >&2
#			else
#				$errlog parameter count
#			fi
#			exit 1
#		fi;;
  *)	if [ $# -ne 0 ]; then				# error in param count
		if [ "$verbose" != "-q" ]; then
			echo "Fehler - Parameteranzahl falsch!" >&2
		else
			$errlog parameter count
		fi
		exit 1
	fi;;
esac
##############################################################################
# CHECK LIBRARY AND CONFIG

# 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 version of config files				# set config var!
#Compare_Version $conf_file_needed $Program_Conf
#Compare_Version $conf_file_needed $Program_Rc
ret=$?						# (ret: 0,1,2,9)
if [ $ret -eq 1 ]; then		# needed config-version higher than installed
	if [ "$verbose" != "-q" ]; then
		echo "Fehler - $scriptname benoetigt neuere Version der Konfig-datei!" >&2
	else
		$errlog newer version of conf file needed
	fi
	exit 2
elif [ $ret -eq 9 ]; then		# other error (version or conf file missing)
	if [ "$verbose" != "-q" ]; then
		echo "Fehler - Versionspruefung der Konfig-datei von $scriptname nicht moeglich!"
	else
		$errlog check of version of conf file impossible
	fi
	exit 2
else							# check ok, reset $ret
	ret=0
fi
##############################################################################
# MAINPROGRAM

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

#if [ "$cdir" != "" ]; then				# if variable $cdir exist
#	cf=$cdir/${arg1}rc				#   set $cf
#fi
#-------------------------- section to enable lines --------------------------
# Check what to do (initial cmds, options and args are removed from cmdline)
case $opt in
	|-i)
#		install_bin
#		ret=$?;if [ $ret -ne 0 ];then err=$ret;fi
		install_cnf
		ret=$?;if [ $ret -ne 0 ];then err=$ret;fi
		install_dat1
		ret=$?;if [ $ret -ne 0 ];then err=$ret;fi
		;;
	-u)
#		uninstall_bin -u
#		ret=$?;if [ $ret -ne 0 ];then err=$ret;fi
#		uninstall_cnf -u
#		ret=$?;if [ $ret -ne 0 ];then err=$ret;fi
#		uninstall_dat1 -u
#		ret=$?;if [ $ret -ne 0 ];then err=$ret;fi
		;;
	-U)
#		uninstall_bin -U
#		ret=$?;if [ $ret -ne 0 ];then err=$ret;fi
		uninstall_cnf -U
		ret=$?;if [ $ret -ne 0 ];then err=$ret;fi
		uninstall_dat1 -U
		ret=$?;if [ $ret -ne 0 ];then err=$ret;fi
		;;
	"")
		if [ "$verbose" != "-q" ]; then
			echo "Fehler - Option fehlt!" >&2
		else
			$errlog option missing
		fi
		err=1;;
esac

exit $err
