#!/bin/sh
#
# sources: this script will setup the Debian package management system to use
# the specified sources for apt.  The specified sources name must correspond
# to a sources.list file in /etc/apt.  Names containing the word "unstable"
# will cause dselect to be disabled.  Any other name is assumed to be stable,
# thus dselect will be enabled.  Thus, a sources list with the name
# "foo.unstable" will correspond to an unstable archive (dselect will be
# disabled) who's sources.list file is "/etc/apt/sources.list.foo.unstable".
#
# Usage: sources <sources.list file>
#  e.g. sources foo.unstable

set -e

# The standard locations of sources.list and dselect.  These must be converted
# to symbolic links for this script to work.  In the end, they will point to
# the requested sources list and dselect executable.
DEB_SOURCES=/etc/apt/sources.list
DEB_DSELECT=/usr/bin/dselect

# The file specification for the requested sources list.
REQ_SOURCES=/etc/apt/sources.list.$1

# The locations of the real dselect and the disabled dselect (a script the
# displays a warning message).
REAL_DSELECT=/usr/local/bin/dselect.real
MESG_DSELECT=/usr/local/bin/dselect.mesg

# If we were called without a parameter, display where the current sources.list
# link points to
if [ -z $1 ] ; then
    ls -l $DEB_SOURCES
    exit 0
fi

# Check sources.list and dselect to make sure that they are symbolic links
if [ ! -h $DEB_SOURCES ] ; then
    echo "$0: $DEB_SOURCES is not a symbolic link"
    exit 1
fi
if [ ! -h $DEB_DSELECT ] ; then
    echo "$0: $DEB_DSELECT is not a symbolic link"
    exit 1
fi

# Check if the files that the links will point to exist
if [ ! -f $REQ_SOURCES ] ; then
    echo "$0: $REQ_SOURCES does not exist"
    exit 1
fi
if [ ! -f $REAL_DSELECT ] ; then
    echo "$0: $REAL_DSELECT does not exist"
    exit 1
fi
if [ ! -f $MESG_DSELECT ] ; then
    echo "$0: $MESG_DSELECT does not exist"
    exit 1
fi

echo "Using $REQ_SOURCES"

# Decide which dselect this sources list should use.
if [ `echo $1 | awk '{ print index($0,"unstable") }'` == "0" ] ; then
  echo "Enabling dselect."
  REQ_DSELECT=$REAL_DSELECT
else
  echo "Disabling dselect."
  REQ_DSELECT=$MESG_DSELECT
fi

# Remove and then set the symbolic links
rm $DEB_SOURCES
ln -s $REQ_SOURCES $DEB_SOURCES
rm $DEB_DSELECT
ln -s $REQ_DSELECT $DEB_DSELECT
