#!/bin/sh
#
# Copyright (C) Jamin W. Collins <jcollins@asgardsrealm.net>
# Copyright (C) Jordan Mantha <mantha@ubuntu.com>
# Copyright (C) 2007-2008 Siegfried-A. Gevatter <rainct@ubuntu.com>
#
# ##################################################################
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# See file /usr/share/common-licenses/GPL for more details.
#
# ##################################################################
#
# This script is a wrapper to be able to easily use pbuilder for
# different distributions (eg, Gutsy, Hardy, Debian unstable, etc).
#
# You can create symlinks to a pbuilder-dist executable to get different
# configurations. For example, a symlink called pbuilder-hardy will assume
# that the target distribution is always Ubuntu Hardy.

######################################################################

# Base directory where pbuilder will put all the files it creates.
# This is overriden by the global variable $PBUILDFOLDER
BASE_DIR="$HOME/pbuilder"

# Change this to 0 if you don't want additional components to be used.
# That is, 'universe' and 'multiverse' for Ubuntu chroots and 'contrib'
# and 'non-free' for Debian. (This option can be overwriten at runtime).
EXTRACOMP=1

# Change this to 1 if you want the log for the last operation to be saved
# in the base directory by default (it will be named '.lastlog').
SAVELOG=0

# Allow this script to use /var/cache/apt/archives/ when possible.
if [ -z $SYSCACHE ]
then
	SYSCACHE=1
fi

######################################################################

# Detect system architecture
REALARCH=$(dpkg-architecture -qDEB_HOST_ARCH)

# Detect Ubuntu distribution (wheter it is gutsy, hardy, etc.)
SYSDIST=$(lsb_release -cs 2>/dev/null)

# Overwrite hardcoded base directory by that one in the global variable
if [ $PBUILDFOLDER ] && [ $PBUILDFOLDER != "" ]
then
	BASE_DIR=$PBUILDFOLDER
fi

######################################################################

# Abort if the name of the executable has hypens but it doesn't
# start with "pbuilder-".
if [ -n $(basename $0 | grep '-') ] && [ $(basename $0 | cut -d'-' -f1) != 'pbuilder' ]
then
	echo "Error: " $(basename $0) " is not a valid name for a pbuilder-dist executable."
	exit 1
fi

# Detect if the script has it's original name or if a symlink is being used,
# and if it's a symlink extract the information that it contains.
if [ -n $(basename $0 | grep '-') ] && [ `basename $0` != 'pbuilder-dist' ]
then
	ORIGINAL_NAME=0
	DISTRIBUTION=$(basename $0 | cut -d'-' -f2)
	ARCHITECTURE=$(basename $0 | cut -d'-' -f3)
else
	ORIGINAL_NAME=1
	DISTRIBUTION=$1
	shift 1
fi

# Check if the choosen architecture is supported on the user's system.
if [ "$1" = 'i386' ]  || [ "$1" = 'amd64' ]
then
	if [ $REALARCH = 'amd64' ]; then
		ARCHITECTURE=$1
	else
		echo "Warning: Architecture switching is not supported on your system; ignoring argument '$1'."
	fi

	shift 1
fi

# If architecture hasn't been set yet, use the system's one.
if [ -z "$ARCHITECTURE" ]
then
	ARCHITECTURE=$REALARCH
fi

# Check if there's a component modifier
if [ "$1" = 'mainonly' ]; then
    EXTRACOMP=0
    shift 1
elif [ "$1" = 'allcomp' ]; then
    EXTRACOMP=1
    shift 1
fi

# Check if the default logging preferences should be overwriten
if [ "$1" = 'withlog' ]; then
    SAVELOG=1
    shift 1
elif [ "$1" = 'nolog' ]; then
    SAVELOG=0
    shift 1
fi

# Check if some proxy should be used.
if [ -n "$http_proxy" ]
then
	PROXY=$http_proxy
fi

if [ -z "$PROXY" ] && [ -n "$HTTP_PROXY" ]
then
	PROXY=$HTTP_PROXY
fi

######################################################################

usage()
{
	echo "Usage: $0 "$( [ $ORIGINAL_NAME = 0 ] || echo "<distribution> " )$( [ $ARCHITECTURE != "amd64" ] || echo "[i386|amd64] " )"[mainonly|allcomp] [withlog|nolog] <operation>"
}

distdata()
{
	# Populate variables with Debian / Ubuntu specific data
	if [ "$1" = "debian" ]
	then
		# Set Debian specific data
		
		ISDEBIAN=True
		
		if [ -z $ARCHIVE ]
		then
			ARCHIVE="http://ftp.debian.org"
		fi
		
		COMPONENTS="main"$( [ $EXTRACOMP = 0 ] || echo " contrib non-free" )
	else
		# Set Ubuntu specific data
		
		ISDEBIAN=False
		
		if [ -z $ARCHIVE ]
		then
			ARCHIVE="http://archive.ubuntu.com/ubuntu"
		fi
		
		COMPONENTS="main restricted"$( [ $EXTRACOMP = 0 ] || echo " universe multiverse" )
	fi
}

######################################################################

# Check if there is at least one argument remaining.
if [ $# -lt 1 ]
then
	echo "You provided an insufficent number of arguments."
	usage
	exit 1
fi

######################################################################

# Check if the distribution exists, and fill the variables that change
# depending on wheter the target distribution is Ubuntu or Debian.
case $DISTRIBUTION in
    dapper|edgy|feisty|gutsy|hardy)
        distdata ubuntu
        ;;
    
    oldstable|sarge|stable|etch|testing|lenny|unstable|sid|experimental)
        distdata debian
        ;;
    
    *)
        if [ ! -d $BASE_DIR/${DISTRIBUTION}-* ]
        then
            echo -n "Warning: Unknown distribution «$DISTRIBUTION». Do you want to continue [y/N]? "
            read continue
            
            if [ "$continue" != 'y' ] && [ "$continue" != 'Y' ]
            then
                echo "Aborting..."
                exit 1
            fi
        fi
        
        distdata ubuntu
        ;;
esac

# Save the selected operation in a variable.
OPERATION=$1
shift 1

# Check if the selected operation is an alias for another one.
case "$OPERATION" in
	upgrade)
		OPERATION=update
		;;
esac

# Check if the selected operation is correct, or if it is an alias for
# another one.
case "$OPERATION" in
    create|update|build|clean|login|execute)
    	# Allright.
        ;;
    
    upgrade)
    	OPERATION=update
    	;;
    
    *)
    	if [ ${OPERATION##*.} =  'dsc' ]
    	then
    		OPERATION=build
    	else
        	echo "Unrecognized argument '$OPERATION'. Please use one of those:"
        	echo "    create"
        	echo "    update"
        	echo "    build"
        	echo "    clean"
        	echo "    login"
        	echo "    execute"
        	exit 1
        fi
        ;;
esac

# Determine the base name for the chroot tarball and the folder where the
# resulting files will be stored.
FOLDERBASE="${DISTRIBUTION}-$ARCHITECTURE"

# Create the folder where the resulting files will be placed (if the
# option is build), if it doesn't exist yet.
if [ ! -d $BASE_DIR/${FOLDERBASE}_result ]
then
    mkdir -p $BASE_DIR/${FOLDERBASE}_result
fi

# Determine wheter system cache should be used or not.
if [ $SYSCACHE = 1 ] && [ "$SYSDIST" = "$DISTRIBUTION" ] && [ "$REALARCH" = "$ARCHITECTURE" ]
then
		DEBCACHE='/var/cache/apt/archives/'
fi

# If it's an Ubuntu system, create an editable configuration file,
# and if it's a stable release add the -security and -updates repositories.
if [ $ISDEBIAN = "False" ]
then
	if [ ! -d $BASE_DIR/etc/$DISTRIBUTION/apt.conf/ ]
	then
		mkdir -p $BASE_DIR/etc/$DISTRIBUTION/apt.conf
	fi
	if [ ! -e $BASE_DIR/etc/$DISTRIBUTION/apt.conf/sources.list ]
	then
		echo "deb $ARCHIVE $DISTRIBUTION $COMPONENTS" > $BASE_DIR/etc/$DISTRIBUTION/apt.conf/sources.list
		case $DISTRIBUTION in 
			dapper|edgy|feisty|gutsy )
				cat >>  $BASE_DIR/etc/$DISTRIBUTION/apt.conf/sources.list <<EOF
deb $ARCHIVE $DISTRIBUTION-security $COMPONENTS
deb $ARCHIVE $DISTRIBUTION-updates $COMPONENTS
EOF
				;;
			* )
				;;
		esac
	fi
fi

#if [ -z "$PBUILDAUTH" ]
#then
#	if [ -n "$DESKTOP_SESSION"  ]
#	then
#		case $DESKTOP_SESSION in 
#			gnome )
#				SUDOREPLACE="gksudo -D \"Pbuilder\""
#				;;
#			kde|kde4 )
#				SUDOREPLACE="kdesudo -d --comment \"Pbuilder\""
#				;;
#			* )
#				SUDOREPLACE="sudo"
#				;;
#		esac
#	else
#		SUDOREPLACE=sudo
#	fi
#else
#	SUDOREPLACE=$PBUILDAUTH
#fi

sudo pbuilder $OPERATION \
--basetgz "$BASE_DIR/${FOLDERBASE}-base.tgz" \
--distribution "$DISTRIBUTION" \
--debootstrapopts --arch \
--debootstrapopts "$ARCHITECTURE" \
$( [ "$SAVELOG" = 0 ] || echo "--logfile ${BASE_DIR}/.lastlog" ) \
$( [ -z "$PROXY" ] || echo "--http-proxy ${PROXY}" ) \
$( [ -z "$DEBCACHE" ] || echo "--aptcache ${DEBCACHE}" ) \
--buildresult "${BASE_DIR}/${FOLDERBASE}_result" \
--mirror "${ARCHIVE}" \
$( [ $ISDEBIAN != "False" ] || echo "--aptconfdir ${BASE_DIR}/etc/${DISTRIBUTION}/apt.conf/" ) \
$@