#!/bin/sh -e

if [ $# -lt 2 ]; then
	echo 'uhu-pkg: használat: uhu-pkg {postinst|prerm|postrm} csomagnév [mód [verzió]]' >&2
	exit 1
fi

action="$1"
shift
pkg="$1"
shift

case "$action" in
	postinst)
		ACTION=POSTINST
		;;
	prerm)
		ACTION=PRERM
		;;
	postrm)
		ACTION=POSTRM
		;;
	*)
		echo 'uhu-pkg: hibás első argumentum!' >&2
		exit 1
		;;
esac


export PATH=/sbin:/usr/sbin:/bin:/usr/bin

export LC_ALL=C

umask 0022

#
# /dev/null létezésének garantálása
#

trap=""
if [ ! -e /dev ]; then
	mkdir -m 0755 /dev
	trap="rmdir /dev; $trap"
fi
if [ -e /dev/null -a ! -c /dev/null ]; then
	rm /dev/null
fi
if [ ! -e /dev/null ]; then
	mknod -m 0666 /dev/null c 1 3
	trap="rm /dev/null; $trap"
fi
trap "$trap" EXIT


if [ "$pkg" != "+" ]; then

	#
	# Könyvtárak jogainak beállítása
	#

	if [ "$action" = "postinst" ]; then
		uhu-stat -s -d < /var/lib/dpkg/info/"$pkg".stat || true
	fi


	#
	# Felhasználók, csoportok
	#

	if [ "$action" = "postinst" ]; then
		if [ -f /var/lib/dpkg/info/"$pkg".users \
		  -o -f /var/lib/dpkg/info/"$pkg".groups ]; then
			if [ ! -f /etc/passwd ]; then
				echo 'root:x:0:0:root:/root:/bin/bash' > /etc/passwd
			fi
			if [ ! -f /etc/shadow ]; then
				umask 0077
				echo 'root:!:12000:0:99999:7:::' > /etc/shadow
				umask 0022
			fi
			if [ ! -f /etc/group ]; then
				echo 'root:x:0:' > /etc/group
			fi
			if [ ! -f /etc/gshadow ]; then
				umask 0077
				echo 'root:::root' > /etc/gshadow
				umask 0022
			fi
		fi
		if [ -f /var/lib/dpkg/info/"$pkg".groups ]; then
			while read name gid rest; do
				groupadd -q -r -g $gid $rest $name
			done < /var/lib/dpkg/info/"$pkg".groups
		fi
		if [ -f /var/lib/dpkg/info/"$pkg".users ]; then
			while read name uid gid rest; do
				useradd -q -r -u $uid -g $gid $rest $name
			done < /var/lib/dpkg/info/"$pkg".users
		fi
	fi

	if [ "$action" = "prerm" -a "$1" != "upgrade" ]; then
		if [ -f /var/lib/dpkg/info/"$pkg".users ]; then
			while read name rest; do
				if [ "$name" != "root" ]; then
					userdel $name 2>/dev/null || true
				fi
			done < /var/lib/dpkg/info/"$pkg".users
		fi
		if [ -f /var/lib/dpkg/info/"$pkg".groups ]; then
			while read name rest; do
				if [ "$name" != "root" ]; then
					groupdel $name 2>/dev/null || true
				fi
			done < /var/lib/dpkg/info/"$pkg".groups
		fi
	fi


	#
	# Saját egyéni szkript
	#

	if [ -x /var/lib/dpkg/info/"$pkg"."$action"-custom ]; then
		/var/lib/dpkg/info/"$pkg"."$action"-custom "$@"
	fi

fi


#
# Többi csomag kívánságai - az UHU_PKG_SKIP környezeti változóval letiltható
#

if [ -n "${UHU_PKG_SKIP+_}" ]; then
	exit
fi

shopt -s nullglob

enable -f /usr/lib/bash/unlink unlink 2>/dev/null || true

true > /var/lib/uhu-pkg/_now
for i in /var/lib/uhu-pkg/*; do
	if [ "$i" -nt /var/lib/uhu-pkg/_now ]; then
		unlink "$i"
	fi
done
unlink /var/lib/uhu-pkg/_now

for script in /usr/lib/uhu-pkg/"$action"/*; do
	"$script" "$pkg" "$@"
done

