#!/bin/sh
# postinst script for fliwi-apt-cacher-ng-config
#
# 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


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

#DEBHELPER#

apt_cacher_dir="/etc/apt-cacher-ng"
fliwi_apt_cacher_opts_file="$apt_cacher_dir/fliwi-apt-cacher-opts.conf"
fliwi_service_dir="/etc/fliwi/services/apt-cacher/apt-cacher-ng"

case "$1" in
  configure)
    ### Fixup permissions
    chown -R apt-cacher-ng:apt-cacher-ng /var/cache/apt-cacher-ng
    chown -R apt-cacher-ng:apt-cacher-ng /var/log/apt-cacher-ng

    # Which apt-cacher is this server?
    apt_cacher_service=$(fliwi-get-my-services --limit=apt-cacher)
    echo "### WARNING: This file is under control of Fliwi." > $fliwi_apt_cacher_opts_file
    echo "#   DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN" >> $fliwi_apt_cacher_opts_file
    echo "BindAddress=$apt_cacher_service" >> $fliwi_apt_cacher_opts_file

    # check for dead links we automatically created in past, and remove them
    for file in $(find $apt_cacher_dir -maxdepth 1 -type l -name "*_fliwiautolink.conf" -! -exec test -e {} \; -print); do
      rm -f $file
    done

    # check for additional config files and add a link to them, if applicable
    if [ -d "$fliwi_service_dir" ]; then
      for file in $(find "$fliwi_service_dir/" -maxdepth 1 -type f -name "*.conf"); do
        filename=$(basename $file)
        linkname=$(echo $filename | sed 's/.conf/_fliwiautolink.conf/')
        if [ ! -e $apt_cacher_dir/$linkname ]; then
          ln -s $fliwi_service_dir/$filename $apt_cacher_dir/$linkname
        fi
      done
    fi
  ;;

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

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


### Finally restart apt-cacher-ng
if [ "$1" = "configure" ]; then
  if which invoke-rc.d >/dev/null 2>&1; then
    invoke-rc.d apt-cacher-ng restart || true
  else
    /etc/init.d/apt-cacher-ng restart || true
  fi
fi


exit 0
