#!/bin/bash
# postinst script for dump1090
#
# see: dh_installdeb(1)

set -e

# summary of how this script can be called:
#        * <postinst> `configure' <most-recently-configured-version>
#        * <old-postinst> `abort-upgrade' <new version>
#        * <conflictor's-postinst> `abort-remove' `in-favour' <package>
#          <new-version>
#        * <postinst> `abort-remove'
#        * <deconfigured's-postinst> `abort-deconfigure' `in-favour'
#          <failed-install-package> <version> `removing'
#          <conflicting-package> <version>
# for details, see http://www.debian.org/doc/debian-policy/ or
# the debian-policy package

NAME=dump1090-fa
RUNAS=dump1090
CRONFILE=/etc/cron.d/$NAME
TEMPLATECRON=/usr/share/$NAME/cron-template

case "$1" in
    configure)
        . /usr/share/debconf/confmodule

        if ! getent passwd "$RUNAS" >/dev/null
        then
            adduser --system --home /usr/share/$NAME --no-create-home --quiet "$RUNAS"
        fi

        # create cronjob
        if ! test -e $CRONFILE; then
            echo "Creating cronjob in $CRONFILE to periodically update the aircraft database.." >&2
            MIN=$(($RANDOM % 60))
            DOM=$(( ($RANDOM % 28) + 1 ))
            tail -n +4 $TEMPLATECRON | sed -e "s/@USER@/$RUNAS/g" -e "s/@MIN@/$MIN/g" -e "s/@DOM@/$DOM/g" >$CRONFILE
        fi

        # update the DB
        echo "Updating aircraft database now.."
        mkdir -m 0755 -p /var/cache/$NAME
        chown $RUNAS /var/cache/$NAME
        su $RUNAS -s /bin/bash -c /usr/share/$NAME/update-aircraft-database.sh || true

        # set up lighttpd
        echo "Enabling lighttpd integration.." >&2
        lighty-enable-mod dump1090-fa || true
        echo "Restarting lighttpd.." >&2
        invoke-rc.d lighttpd force-reload || true
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

if [ "$1" = "configure" ]; then db_stop; fi
exit 0