#!/bin/ksh93

PKGNAME=LNFpkgtools

FPROG=${.sh.file}
PROG=${FPROG##*/}
SDIR=${.sh.match%\/}

typeset -r DTAB='/etc/device.tab'
typeset -r SPOOL='/var/spool/pkg'
typeset -r DTAB_E="spool:::${SPOOL}:desc="'"Packaging Spool Directory"'

function checkDeviceTab {
	typeset DTAB_F=${DEST}${DTAB} X=''
	[[ -f ${DTAB_F} ]] && X=${ grep '^spool:' ${DTAB_F} 2> /dev/null ; }
	[[ -n $X ]] && return
	print "${DTAB_E}" >>${DTAB_F}
	if (( $? )); then
		print -u2 "\nMake sure you are allowed to create/modify ${DTAB_F}" \
			"and try again."
		return 1
	fi
	print "Setting spool directory for packages to default path '${SPOOL}'." \
		"\nYou can change it within '${DTAB_F}'."
}

function getBaseCmd {
	typeset -n X=$1
	typeset CMD
	X=''

	(( UNINSTALL )) && CMD='pkgrm' || CMD='pkgadd -v -I'

	# Try to use GZ binaries
	if [[ ${DEST} != '/' ]]; then
		[[ -x /usr/sbin/${CMD} ]] && X="/usr/sbin/${CMD}" || \
			X="${DEST}/usr/sbin/${CMD}"
		# ${DEST}/usr/sadm/install/bin/{pkginstall|pkgremove} -N {pkgadd|pkgrm}\
		#	[-v -I -a ${PKG_admin_file}] ${PKGDIR} ${PKGNAME} 
		# should actually work as well - called under the hood
		X+=" -R ${DEST}"
		[[ -x /usr/sadm/install/bin/pkgremove ]] || \
			X+=" -b ${DEST}/usr/sadm/install/bin -M"
	else
		X="/usr/sbin/${CMD} -M"
	fi
	(( DEBUG )) && X+=' -O debug'
}

function unInstall {
	typeset X L
	getBaseCmd X
	$X ${PKGNAME} || return $?
	if rmdir ${DEST}/var/sadm/pkg 2>/dev/null ; then
		# no pkgs installed anymore - so remove artifacts as well
		rm -rf ${DEST}/var/sadm/install
		rmdir /var/tmp/ptest/var/sadm
		X=${DEST}${DTAB}
		if [[ -e $X ]]; then
			while read L ; do
				[[ -z $L || ${L:0:1} == '#' || $L == ${DTAB_E} ]] && continue
				return 0	# found a modified/new entry
			done < $X
			rm -f $X
		fi
		rmdir ${DEST}/var 2>/dev/null
		rmdir ${DEST}/etc 2>/dev/null
	fi
	return 0
}

function doMain {
	# We rather make sure, that we do not pollute the system on error.
	if [[ -z ${DEST} || ! -d ${DEST} ]]; then
		print -u2 "The directory '${DEST}' does not yet exist."
		return 1
	fi

	(( UNINSTALL )) && { unInstall ; return $? ; }
	
	typeset  DIR=$1 NF='' X
	integer C
	[[ -z ${DIR} ]] && DIR="${SDIR%/*}/reloc" || DIR+="/${PKGNAME}/reloc"

	for X in /usr/sadm/install/bin/pkginstall /usr/sbin/pkgadd ; do
		[[ ! -f ${DIR}/$X ]] && NF+=" $X" && (( C++ ))
	done
	if (( C == 2 )); then
		print -u2 "\n${DIR%/*/*}/ does not seem to contain the extracted" \
			"${PKGNAME} package."
		return 1
	elif [[ -n ${NF} ]]; then 
		print -u2 "\nUnable to find the following files in ${DIR}: ${NF}"
		return 1
	fi

	for X in etc usr/sbin usr/sadm/install/bin ; do
		if [[ ! -d ${DEST}/$X ]]; then
			mkdir -p ${DEST}/$X || return $?
		fi
	done

	checkDeviceTab || return $?

	for X in usr/sadm/install/bin/pkginstall usr/sbin/pkgadd ; do
		cp ${DIR}/$X ${DEST}/${X%/*}/ || return $?
		chmod 0755 ${DEST}/$X || return $?
	done
	# finally add myself ;-)
	getBaseCmd X
	$X -a ${DIR}/var/sadm/install/admin/default -d ${DIR%/*/*} ${PKGNAME}
}

function showUsage {
	getopts -a ${PROG} "${USAGE}" OPT --man
}

USAGE='[-?$Id$ ]
[-copyright?Copyright (c) 2002 Jens Elkner. All rights reserved.]
[-license?CDDL 1.0]
[+NAME?'"${PROG}"' - installs SVr4 pkgtools on this virgin system]
[+DESCRIPTION?Install SVr4 pkgtools on this virgin system. If \apkg_dir\a is given, it is assumed, that this directory contains the extracted '"${PKGNAME}"' package. Otherwise it is assumed, that this script is called directly from within the extracted '"${PKGNAME}"' package directory.]
[h:help?Print this help and exit.]
[F:functions?Print a list of all functions available in this script.]
[T:trace]:[functionList?A comma separated list of functions of this script to trace (convinience for troubleshooting).]
[+?]
[d:debug?Switch on debug output for the '"${PKGNAME}"' utilities itself.]
[R:rootdir]:[root_path?Set the full path name of a directory to use as the system root.  All files, including package system information files, are relocated to a directory tree starting in the specified \aroot_path\a. Default: /]
[U:uninstall?Uninstall the '"${PKGNAME}"' package and try to remove all related artifacts as well if safe.]
[+EXAMPLES?]{
	[+Example 1?Install on a virgin system:]
	[+?\b# \bcd /tmp]
	[+?\b# \btar xzf '"${PKGNAME}"'.tar.gz]
	[+?\b# \bmkdir /tmp/test]
	[+?\b# \bksh93 '"${PKGNAME}"'/install/bootstrap -R/tmp/test]
	[+?]
	[+Example 2?Uninstall including artifiacts if possible:]
		[+?\b# \bksh93 /tmp/test/var/sadm/pkg/'"${PKGNAME}"'/install/bootstrap -U -R/tmp/test]
}

[\apkg_dir\a]
'

DEST=/
integer DEBUG=0 UNINSTALL=0

USAGE="${ print "${USAGE}" ; }"
while getopts -a ${PROG} "${USAGE}" OPT ; do
	case ${OPT} in
		h) showUsage ; exit 0 ;;
		T) if [[ ${OPTARG} == 'ALL' ]]; then
				typeset -ft ${ typeset +f ; }
			else
				typeset -ft ${OPTARG//,/ }
			fi
			;;
		F) typeset +f && exit 0 ;;
		R) [[ ${OPTARG} != '/' ]] && DEST="${OPTARG%/}" ;;
		U) UNINSTALL=1 ;;
		d) DEBUG=1 ;;
	esac
done
integer IDX=$((OPTIND-1))
shift ${IDX}

doMain "$@" || print -u2 'Installation failed.'
