#!/bin/sh

## live-build(7) - System Build Scripts
## Copyright (C) 2016-2020 The Debian Live team
## Copyright (C) 2006-2015 Daniel Baumann <mail@daniel-baumann.ch>
##
## This program comes with ABSOLUTELY NO WARRANTY; for details see COPYING.
## This is free software, and you are welcome to redistribute it
## under certain conditions; see COPYING for details.


set -e

# Including common functions
[ -e "${LIVE_BUILD}/scripts/build.sh" ] && . "${LIVE_BUILD}/scripts/build.sh" || . /usr/lib/live/build.sh

# Setting static variables
DESCRIPTION="Enable use of local deb repository"
USAGE="${PROGRAM} {configure|deconfigure} [--force]"

# Processing arguments and configuration files
Init_config_data "${@}"

_ACTION="${1}"
shift

Echo_message "Begin enabling use of temporary local deb repository"

Require_stagefiles config bootstrap

if [ -z "${LB_LOCALREPO_LOCATIONS}" ]
then
    exit 0
fi

_LOCALREPO_COUNT="$(printf '%s\n' "${LB_LOCALREPO_LOCATIONS}" | tr ' ' '\n' | wc -l)"
_LOCALREPO_IDX=1

while [ "${_LOCALREPO_IDX}" -le "${_LOCALREPO_COUNT}" ]
do
	_LOCALREPO_PATH="$(printf '%s\n' "${LB_LOCALREPO_LOCATIONS}" | cut -d' ' -f"${_LOCALREPO_IDX}")"
	_LOCALREPO_LIST="$(printf '%s\n' "${LB_LOCALREPO_LISTS}" | cut -d',' -f"${_LOCALREPO_IDX}")"
	_LOCALREPO_FILE="$(basename "${_LOCALREPO_PATH}")"
	case "${_ACTION}" in
		configure)
			mkdir -p chroot/root/localrepos/"${_LOCALREPO_FILE}"
			mount --bind "${_LOCALREPO_PATH}" chroot/root/localrepos/"${_LOCALREPO_FILE}"
			echo "deb [trusted=yes] file:/root/localrepos/${_LOCALREPO_FILE} ${_LOCALREPO_LIST}" > chroot/etc/apt/sources.list.d/"${_LOCALREPO_FILE}".list
			;;

		deconfigure)
			rm chroot/etc/apt/sources.list.d/"${_LOCALREPO_FILE}".list
			umount chroot/root/localrepos/"${_LOCALREPO_FILE}"
			rm -rf chroot/root/localrepos/"${_LOCALREPO_FILE}"
			;;

		*)
			Echo_error "Invalid action parameter: '${_ACTION}'"
			Usage --fail
			;;
	esac
	_LOCALREPO_IDX=$(( _LOCALREPO_IDX + 1 ))
done

if [ "${_ACTION}" = 'deconfigure' ]
then
	rm -rf chroot/root/localrepos
fi
