#!/bin/sh

# prepare_pdeb  version 0.8
# a hook script to prepare a pdebuild environment (e.g. by downgrading or
# upgrading some packages to versions from other Debian releases), before
# running other hook scripts
#
# Copyright (c) 2010-2017 Francesco Poli
#
# 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.


echo " ===== starting ${0} ====="

COMMON="$( dirname ${0} )/pdeb_common"
. $COMMON

CHANGED="no"

CONFFILE="$( dirname ${0} )/prepare_pdeb.conf"
PKG_LIST=$( grep -v '^#\|^UPDATE' $CONFFILE )

if grep '^UPDATE' $CONFFILE > /dev/null
then
    CHANGED="yes"
fi

SRCLIST="/etc/apt/sources.list"
REPO=$( grep '^deb ' $SRCLIST | tail -n 1 | cut -d ' ' -f 2 )

for PKGDIST in $PKG_LIST
do
    CHANGED="yes"
    echo " => installing $PKGDIST"

    # determine distribution
    TDIST=$( echo $PKGDIST | cut -d '/' -f 2 | cut -d ';' -f 1 )

    # split groups of packages
    PACKAGES=$( echo $PKGDIST | tr ';' ' ' )

    if test "x$TDIST" = "xunreleased"
    then
        init_aptitude_log APTITUDE_TLOG
        $APTITUDE_TLOG install awk apt-utils
        create_local_repo LOC_REPO LOC_SOURCES LOC_PREFS
        purge_installed_pkgs APTITUDE_TLOG /var/log/aptitude
        $APTITUDE -t $TDIST install $PACKAGES
        destroy_local_repo LOC_REPO LOC_SOURCES LOC_PREFS
    else
        TMP_SOURCES=$( mktemp /etc/apt/sources.list.d/otherXXXXXX.list )
        echo "deb $REPO $TDIST main" > $TMP_SOURCES
        $APTITUDE update
        $APTITUDE -t $TDIST install $PACKAGES
        rm -f $TMP_SOURCES
        $APTITUDE update
    fi
done

if test $CHANGED = "yes"
then
    $APTITUDE update
else
    echo " => nothing to be done: exiting"
fi

echo " ===== finished ${0} ====="
