#!/bin/sh
# Copyright © 2012  Andy Whitcroft <apw@ubuntu.com>
#
# schroot 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 3 of the License, or
# (at your option) any later version.
#
# schroot 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.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see
# <http://www.gnu.org/licenses/>.
#
#####################################################################

set -e

. "$SETUP_DATA_DIR/common-data"
. "$SETUP_DATA_DIR/common-functions"
. "$SETUP_DATA_DIR/common-config"

changed=false
if [ $STAGE = "setup-start" ] || [ $STAGE = "setup-recover" ]; then
    sources="${CHROOT_PATH}/etc/apt/sources.list"

    if [ "$CHROOT_SESSION_PURGE" = 'false' ]; then
	exit 0
    fi

    if [ -n "$APT_POCKETS" ]; then
	echo "setting apt pockets to 'release $APT_POCKETS' in sources.list"
	awk -v pockets="$APT_POCKETS" '
		BEGIN		{ n = 0; split(pockets, plist); }
		/^#/		{ print ; next }
		($3 !~ /-/)	{ print;
				  release = $3;
				  for (m in plist) {
					$3 = release "-" plist[m];
					new[n] = $0; n++;
				  }
			  	  next;
				}
		END		{ for (x = 0; x < n; x++) {
					print new[x]
				  }
				}
	' <"$sources" >"$sources.new"
	mv "$sources.new" "$sources"
	changed=true
    fi
    if [ -n "$APT_COMPONENTS" ]; then
	echo "setting apt components to '$APT_COMPONENTS' in sources.list"
	awk -v components="$APT_COMPONENTS" '
		/^#/		{ print ; next }
				{ print $1 " " $2 " " $3 " " components }
	' <"$sources" >"$sources.new"
	mv "$sources.new" "$sources"
	changed=true
    fi

    if [ "$VERBOSE" = 'verbose' -a "$changed" = 'true' ]; then
	echo "Resulting sources.list"
	cat "$sources"
    fi
fi
