#!/bin/bash

STABLED=trixie
TESTINGD=forky
UNSTABLED=sid
OLDSTABLED=bookworm
OLDOLDSTABLED=bullseye

_usage () {
   echo "Usage:   `basename $0` [ -f ] STABLEPRIORITY TESTINGPRIORITY"
   echo "         `basename $0` [ -f ] STABLEPRIORITY TESTINGPRIORITY UNSTABLEPRIORITY"
   echo "         `basename $0` [ -f ] STABLEPRIORITY TESTINGPRIORITY UNSTABLEPRIORITY OLDSTABLEPRIORITY"
   echo "         `basename $0` [ -f ]"
   echo "         `basename $0` -h "
   echo "Sets /etc/apt/preferences from /etc/apt/preferences.template"
   echo "Default: `basename $0` [ -f ] 800 700"
   echo "Example: `basename $0` -f 800 700         # for a stable machine (currently: $STABLED)"
   echo "         `basename $0` -f 700 800         # for a testing machine (currently: $TESTINGD)" 
   echo "         `basename $0` -f 700 600 501 800 # for an oldstable machine (currently: $OLDSTABLED)" 
}

if [ "$1" = "-f" ]; then
   FORCE=yes
   shift
else
   FORCE=no
fi

if [ \! \( $# = 2 -o $# = 3 -o $# = 4 -o $# = 0 \) -o "$1" = "-h" -o "$1" = "--help" ]; then
   _usage
   exit 0
fi

DEBUTILP=901
STABLEP=800
TESTINGP=700
UNSTABLEP=600
OLDSTABLEP=550
OLDOLDSTABLEP=501

if [ -f /etc/apt/preferences.bk -a -f /etc/apt/preferences -a $FORCE = no ]; then
    echo "/etc/apt/preferences.bk and /etc/apt/preferences exist. Done nothing. Use -f to force."
    exit 0
fi

if [ -f /etc/apt/preferences ]; then
    cp -v /etc/apt/preferences /etc/apt/preferences.bk
fi

if [ $# = 2 ]; then
   STABLEP=$1
   TESTINGP=$2
elif [ $# = 3 ]; then
   STABLEP=$1
   TESTINGP=$2
   UNSTABLEP=$3
elif [ $# = 4 ]; then
   STABLEP=$1
   TESTINGP=$2
   UNSTABLEP=$3
   OLDSTABLEP=$4
fi

echo "writing new /etc/apt/preferences from /etc/apt/preferences.template..."

(
echo "STABLED=$STABLED"
echo "TESTINGD=$TESTINGD"
echo "UNSTABLED=$UNSTABLED"
echo "OLDSTABLED=$OLDSTABLED"
echo "OLDOLDSTABLED=$OLDOLDSTABLED"
echo "DEBUTILP=$DEBUTILP"
echo "STABLEP=$STABLEP"
echo "TESTINGP=$TESTINGP"
echo "UNSTABLEP=$UNSTABLEP"
echo "OLDSTABLEP=$OLDSTABLEP"
echo "OLDOLDSTABLEP=$OLDOLDSTABLEP"
cat /etc/apt/preferences.template
) | awk '/[A-Z][A-Z]*=/{print; next}{printf("echo \"%s\"\n",$0)}' | sh > /etc/apt/preferences

# echo "done."
