#!/bin/sh
# postinst script for cvmfs-release
#
# 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


case "$1" in
    configure)
	# select relevant .list file now, so one deb package can work
	#  on all the supported releases
	. /etc/os-release
	basename="`echo "$NAME"|awk '{print $1}'`"
	basever="`echo "$VERSION_ID"|cut -d. -f1`"
	subver=""
	case "$basename" in
	    Ubuntu) subver=".04";;
	    Debian) if [ "$basever" -lt 10 ]; then subver=".0"; fi;;
	esac
	namever="${basename}_${basever}${subver}"
	listpfx="/usr/share/cvmfs-contrib-release/cvmfs-contrib-"
	listsrc=${listpfx}${namever}.list
	if [ ! -f $listsrc ]; then
	    wantedver="${basever}${subver}"
	    gotver="`(echo $wantedver;ls ${listpfx}${basename}_* 2>/dev/null|sed 's/.*_//;s/\.list//')|sort -n|grep -B 1 "^$wantedver"|head -1`"
	    if [ -n "$gotver" ] && [ "$gotver" != "$wantedver" ]; then
		# falling back to an older version
		gotnamever="${basename}_${gotver}"
	    else
		# pick the oldest one listed
		gotnamever="`ls ${listpfx}*|sed 's/.*-//;s/\.list//'|sort -t_ -k 2 -n|head -1`"
	    fi
	    echo "Warning: $namever is not supported.  Using $gotnamever instead."
	    listsrc="${listpfx}${gotnamever}.list"
	fi
	mkdir -p /etc/apt/sources.list.d
	listdest=/etc/apt/sources.list.d/cvmfs-contrib.list
	if [ -L $listdest ]; then
	    rm -f $listdest
	fi
	if [ ! -f $listdest ]; then
	    ln -s $listsrc $listdest
	fi
	# remove write permission on the real files so hopefully system
	#  administrators will notice the symlink and make a copy of
	#  the file to edit instead.
	chmod a-w /usr/share/cvmfs-contrib-release/*.list
    ;;

    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#

exit 0
