#!/bin/sh
# postinst script for uptrack
#
# see: dh_installdeb(1)

set -e

. /usr/share/debconf/confmodule

# 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

CONFIGFILE=/etc/uptrack/uptrack.conf
SAMPLEFILE=/usr/share/uptrack/uptrack.conf.sample
REBOOT_REQUIRED_FILE=/var/run/reboot-required

# The package name passed to pycompile for ksplice-uptrack needs to be replaced
pycompile() {
	if [ "x$1" = "x-p" -a "x$2" = "xuptrack" ]; then
		`which pycompile` -p $package
	else
		`which pycompile` "$@"
	fi
}

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

# Automatically added by dh_installinit
if [ -x "/etc/init.d/uptrack" ]; then
	if [ ! -e "/etc/init/uptrack.conf" ]; then
		update-rc.d uptrack start 38 S . >/dev/null
	fi
fi
# End automatically added section
# displace.sh.in: diversion helpers for maintainer scripts
#
# displace_link <prefix> <suffix>
#
#   Ensures that the file <prefix><suffix> is properly diverted to
#   <prefix>.divert-orig<suffix> by this package, and becomes a
#   symbolic link to either <prefix>.divert<suffix> (default) or
#   <prefix>.divert-orig<suffix>.
#
# undisplace_unlink <prefix> <suffix>
#
#   Undoes the action of displace_link <prefix> <suffix> specified
#   above.
#
# Version: 4.0
#
# Copyright © 2008–2012 Tim Abbott <tabbott@mit.edu> and Anders
# Kaseorg <andersk@mit.edu>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the “Software”), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#

package=uptrack

ours=.ksplice
theirs=.ksplice-orig

displace_link_displace()
{
    file=$1
    ourfile=$2
    theirfile=$3
    if ! LC_ALL=C dpkg-divert --list "$package" | \
	grep -xFq "diversion of $file to $theirfile by $package"; then
	dpkg-divert --divert "$theirfile" --rename --package "$package" --add "$file"
    fi
}

displace_link_symlink()
{
    file=$1
    ourfile=$2
    theirfile=$3
    if [ ! -L "$file" ] && [ ! -e "$file" ]; then
	ln -s "$(basename "$ourfile")" "$file"
    elif [ ! -L "$file" ] || \
	[ "$(readlink "$file")" != "$(basename "$ourfile")" -a \
	  "$(readlink "$file")" != "$(basename "$theirfile")" ]; then
	echo "*** OMINOUS WARNING ***: $file is not linked to either $(basename "$ourfile") or $(basename "$theirfile")" >&2
    fi
}

displace_link()
{
    prefix=$1
    suffix=$2

    file=$prefix$suffix
    ourfile=$prefix$ours$suffix
    theirfile=$prefix$theirs$suffix
    displace_link_displace "$file" "$ourfile" "$theirfile"
    displace_link_symlink "$file" "$ourfile" "$theirfile"
}

displace_hide()
{
    file=$1
    ourfile=""
    theirfile=$2
    displace_link_displace "$file" "$ourfile" "$theirfile"
}

undisplace_unlink_symlink()
{
    file="$1"
    ourfile="$2"
    theirfile="$3"
    if [ ! -L "$file" ] || \
	[ "$(readlink "$file")" != "$(basename "$ourfile")" -a \
	  "$(readlink "$file")" != "$(basename "$theirfile")" ]; then
	echo "*** OMINOUS WARNING ***: $file is not linked to either $(basename "$ourfile") or $(basename "$theirfile")" >&2
    else
	rm -f "$file"
    fi
}

undisplace_unlink_displace()
{
    file="$1"
    if [ ! -L "$file" ] && [ ! -e "$file" ]; then
	dpkg-divert --remove --rename --package "$package" "$file"
    else
	echo "Not removing diversion of $file by $package" >&2
    fi
}

undisplace_unlink()
{
    prefix=$1
    suffix=$2

    file=$prefix$suffix
    ourfile=$prefix$ours$suffix
    theirfile=$prefix$theirs$suffix

    undisplace_unlink_symlink "$file" "$ourfile" "$theirfile"
    undisplace_unlink_displace "$file"
}

undisplace_unhide()
{
    file=$1
    undisplace_unlink_displace "$file"
}

check_undisplace_unlink()
{
    prefix=$1
    suffix=$2

    file=$prefix$suffix
    ourfile=$prefix$ours$suffix
    theirfile=$prefix$theirs$suffix

    if LC_ALL=C dpkg-divert --list "$package" | \
	grep -xFq "diversion of $file to $theirfile by $package"; then
	undisplace_unlink "$prefix" "$suffix"
    fi
}

check_undisplace_unhide()
{
    file=$1
    hiddenfile=$2
    if LC_ALL=C dpkg-divert --list "$package" | \
	grep -xFq "diversion of $file to $hiddenfile by $package"; then
	undisplace_unhide "$file"
    fi
}

# End of divert.sh.in
if [ "$1" = "configure" ]; then
    displace_link /sbin/modprobe 
    displace_link /sbin/depmod 
    displace_link /usr/share/update-notifier/notify-reboot-required 
    displace_link /etc/kerneloops.conf 
fi
# Automatically added by dh_pysupport
if which update-python-modules >/dev/null 2>&1; then
	update-python-modules  uptrack.public
fi
# End automatically added section

if [ -x "/etc/init.d/uptrack-late" ]; then
    update-rc.d uptrack-late start 60 S . stop 20 0 6 . &>/dev/null || exit $?
fi

update_systemd_service()
{
    SYSTEMCTL=/bin/systemctl
    if [ ! -x $SYSTEMCTL ]; then
        return
    fi

    if [ ! -L /sbin/init ]; then
        # The trigger is called twice when changing the init system. First when
        # the old init system is removed, then second when the new init system
        # is installed. On the first trigger, /sbin/init doesn't exist.
        # It also needs to be a symlink so we can determine which init system is
        # being used,
        return
    fi

    SYSTEMCTL_ARGS=--quiet
    SBIN_INIT=$(readlink /sbin/init)
    case $SBIN_INIT in
        /lib/systemd/systemd)
            $SYSTEMCTL $SYSTEMCTL_ARGS mask uptrack-late.service
            $SYSTEMCTL $SYSTEMCTL_ARGS disable uptrack-prefetch.service 2> /dev/null || true
            $SYSTEMCTL $SYSTEMCTL_ARGS enable /usr/lib/uptrack/uptrack-prefetch.service
        ;;

        upstart)
            $SYSTEMCTL $SYSTEMCTL_ARGS unmask uptrack-late.service
            $SYSTEMCTL $SYSTEMCTL_ARGS disable uptrack-prefetch.service
        ;;
    esac
}

case "$1" in
    configure)
	db_get uptrack/accesskey
	accesskey="$RET"
	if [ ! -e $CONFIGFILE ]; then
	    sed "s|INSERT_ACCESS_KEY|$accesskey|" $SAMPLEFILE > $CONFIGFILE
	else
	    sed -e "s/^\s*accesskey\s*=.*/accesskey = $accesskey/" \
		< $CONFIGFILE > $CONFIGFILE.tmp
	    mv -f $CONFIGFILE.tmp $CONFIGFILE
	fi

        # Kill the kerneloops applet
        if [ -n "$2" ] && dpkg --compare-versions "$2" "<=" "0.9.2"; then
            # The applet may not be running anyways; That's OK.
            pkill kerneloops-applet || true
        fi

	# To use namespace modules provided by a package in that
	# package's postinst script, with python-support, you must run
	# "update-python-modules -p"
	#
	# See "Namespace packages" section of
	# /usr/share/doc/python-support/README.gz.
	if which update-python-modules >/dev/null 2>&1; then
	    if update-python-modules --help | grep -q -- "--post-install"; then
		update-python-modules --post-install
	    fi
	fi

	if ! [ -f /var/log/uptrack.log ]; then
	    touch /var/log/uptrack.log
	fi

	if [ -z "$2" ] || dpkg --compare-versions "$2" le 0.9.9; then
	    chown -R root:adm /etc/uptrack /var/log/uptrack.log /var/cache/uptrack 2>/dev/null || true
	    chmod -R o-rwx,u+rwX,g+rX /etc/uptrack /var/log/uptrack.log /var/cache/uptrack 2>/dev/null || true
	fi

        # Convert pre-0.9.9 cache to fully unpacked cache format
        if [ -n "$2" ] && dpkg --compare-versions "$2" le 0.9.9; then
            rm -rf /var/cache/uptrack/*/*/*/*/updates/????????/
            if [ -n "$(ls -d /var/cache/uptrack/*/*/*/*/ksplice-*.tar.gz 2>/dev/null)" ]; then
                for t in /var/cache/uptrack/*/*/*/*/ksplice-*.tar.gz; do
                    mkdir -p "$(dirname "$t")"/updates
                    tar --force-local -xzf "$t" -C "$(dirname "$t")"/updates
                done
            fi
        fi

	# Migrate module names from buggy naming in versions <= 1.2.2
	modwildcard="/var/run/ksplice/modules/*/ksplice/*"
	for modpath in $modwildcard; do
            # if wildcard didn't get expanded...
	    if [ "$modpath" != "$modwildcard" ]; then
		orig_dirname=$(dirname "$modpath")
		link_path=$(readlink "$modpath")
		real_basename=$(basename "$link_path")
		if [ "$modpath" != "$orig_dirname/$real_basename" ]; then
		    mv "$modpath" "$orig_dirname/$real_basename"
		fi
	    fi
	done

	mkdir -p /var/lib/uptrack
        (
            python -c 'import fcntl; fcntl.flock(9, fcntl.LOCK_EX)'
            mkdir -p /var/run/ksplice/modules.old
            for d in /var/run/ksplice/modules/*; do
                release=$(basename "$d")
                if [ -d "$d/ksplice.old" ]; then
                    cp -a "$d/ksplice.old/." "/var/run/ksplice/modules.old/$release/"
                    rm -rf "$d/ksplice.old/"
                fi
            done
            /sbin/ksplice-depmod -a
        ) 9>/var/lib/uptrack/lock

	# Download (but don't install) updates if they are
	# available. We might not have network here, though, so fail
	# gracefully
	uptrack-upgrade -q -n 3>&- || true

	# If a reboot-required already exists from having installed a new kernel
	# on disk without rebooting, suppress notifications about the new
	# kernel.
	if [ -e "$REBOOT_REQUIRED_FILE.pkgs" ]; then
            grep '^linux-image-' "$REBOOT_REQUIRED_FILE.pkgs" >> "$REBOOT_REQUIRED_FILE.pkgs.ksplice-orig" || true
            sed -i '/^linux-image-/ d' "$REBOOT_REQUIRED_FILE.pkgs"
	    [ -s "$REBOOT_REQUIRED_FILE.pkgs" ] || rm -f "$REBOOT_REQUIRED_FILE" "$REBOOT_REQUIRED_FILE.pkgs"
	fi

	# Install the crontab. We do so in the postinst to randomize the time.
	# The approach is inspired by and simplified from apticron's
	# maintainer scripts.
	cronfile=/etc/cron.d/uptrack
	if ! [ -e "$cronfile" ] || grep -q '^\*/30' "$cronfile"; then
	    /usr/lib/uptrack/regenerate-crontab
	fi

	if [ -n "$2" ] && dpkg --compare-versions "$2" "<=" "0.9.9.2"; then
	    # Update the initramfs to not have the modprobe wrapper at all
	    update-initramfs -u -k all || true
	fi

        invoke-rc.d kerneloops restart 3>&- || true

        chmod +x /usr/lib/uptrack/uptrack-prefetch.sh

        update_systemd_service
    ;;

    triggered)
        update_systemd_service
    ;;

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

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

exit 0
