#!/bin/sh
# Create an Alpine APK package from an existing kerTeX installation.
# $Id: mk_kertex_apk,v 1.2 2020/09/08 07:45:09 tlaronde Exp $
#
# C) 2020 Thierry Laronde <tlaronde@polynum.com>
# KerTeX Public License.
# No warranty! Use at your own risks!

set -eu

#========== CUSTOMIZABLE
#
# These shall match the kerTeX installation.
#
USER0=kertex
GROUP0=kertex
TARGETOPTDIR=/home/kertex

#========== CHECKS

test -d "$TARGETOPTDIR" && test -f "$TARGETOPTDIR/bin/which_kertex"\
	|| { 
	echo "KerTeX is not installed in '$TARGETOPTDIR'!"
	exit 1
}

command -v abuild-tar || {
	echo "You need to install alpine-sdk: apk add alpine-sdk" >&2
	exit 2
}

#========== NOTHING TO CHANGE BELOW

mkdir /tmp/$$
cd /tmp/$$

. "$TARGETOPTDIR/bin/which_kertex"

cat <<EOT >.PKGINFO
pkgname = kertex
pkgver = $KERTEX_VERSION
pkgdesc = The kerTeX TeX, METAFONT, MetaPost and al. distribution
url = http://www.kergis.com/en/kertex.html
license = http://downloads.kergis.com/kertex/licence_kerTeX_T.txt
source = http//downloads.kergis.com/kertex/kertex_bundle.tar
depends = ed
depends = lftp
EOT

cat <<EOT >.pre-install
#!/bin/sh

echo "I will create $USER0 if not existing but won't set a password." >&2
echo "Change this afterwards if needed." >&2
adduser -D $USER0 || true
if test $USER0 != $GROUP0; then
	addgroup $GROUP0 || true
	addgroup $USER0 $GROUP0 || true
fi

cat <<EOP >>/home/$USER0/.profile
##BEGINKERTEX
test "x$PATH" != x || . /etc/profile
PATH="\$PATH:$TARGETOPTDIR/bin:$TARGETOPTDIR/bin/kertex"
##ENDKERTEX
EOP

chmod 644 /home/$USER0/.profile
chown $USER0 /home/$USER0/.profile

EOT

chmod 755 .pre-install

cat <<EOT >>.post-deinstall
#!/bin/sh

ed "home/$USER0/.profile" <<"EOED" >/dev/null 2>&1
/^##BEGINKERTEX\$/,/^##ENDKERTEX\$/d
w
q
EOED
EOT

chmod 755 .post-deinstall

tar -c "$TARGETOPTDIR/bin/which_kertex" \
	"$TARGETOPTDIR/bin/kertex" \
	"$TARGETOPTDIR/share/kertex"\
	| abuild-tar --cut | gzip -9 >data.tar.gz

tar -c .PKGINFO .pre-install .post-deinstall\
	| abuild-tar --cut | gzip -9 >control.tar.gz

pkgname=kertex-$KERTEX_VERSION-1.apk

cat control.tar.gz data.tar.gz >/tmp/$pkgname

echo "Package /tmp/$pkgname created" >&2

cd /tmp/$$
rm -fr .[Pp]* *
cd ..
rmdir $$

exit 0
