#!/bin/sh
# Install the local transaction chosen against this exact live image.
set -eu
mode=${1:?expected live, target or verify}
case "$mode" in live|target|verify);; *) exit 2;; esac
export DEBIAN_FRONTEND=noninteractive
medium=/run/live/medium
[ -d "$medium/compact" ] || medium=/run/initramfs/live
[ -d "$medium/compact" ] || { echo 'The USB package directory is unavailable.' >&2; exit 1; }
cd "$medium/compact"
# Calamares runs Debian's package cleanup after this transaction. Verify
# each package after that cleanup while the installation medium is mounted.
if [ "$mode" = verify ]; then
    [ -s requested-packages.txt ] || { echo 'Missing installed package manifest.' >&2; exit 1; }
    status=$(xargs -r dpkg-query --show --showformat='${binary:Package}\t${db:Status-Status}\n' < requested-packages.txt) || exit 1
    printf '%s\n' "$status" | awk -F '\t' '
        $2 != "installed" {
            print "Required package unavailable: " $1 " (" $2 ")" > "/dev/stderr"
            failed = 1
        }
        END { exit failed }
    '
    exit 0
fi
sha256sum -c packages.sha256 --status

# An empty package-list directory prevents reaching any external repository.
state=$(mktemp -d)
trap 'rm -rf "$state"' EXIT
mkdir -p "$state/lists/partial"
set --
for archive in "$PWD"/desktop/*.deb; do
    [ ! -f "$archive" ] || set -- "$@" "$archive"
done
if [ "$mode" = target ]; then
    for archive in "$PWD"/kernel/*.deb; do
        [ ! -f "$archive" ] || set -- "$@" "$archive"
    done
fi
if [ "$#" -gt 0 ]; then
    apt-get -y --no-remove --no-install-recommends -o DPkg::Lock::Timeout=120 \
        -o Dir::Etc::sourcelist=/dev/null -o Dir::Etc::sourceparts=- \
        -o "Dir::State::lists=$state/lists" \
        -o Dpkg::Options::=--force-confold install "$@"
fi
# Packages already installed in the live base can be marked automatic.
# Protect every explicitly selected desktop and language package from the
# stock Calamares autoremove of dependencies of its live-only metapackages.
if [ "$mode" = target ]; then
    xargs -r apt-mark manual < requested-packages.txt
fi
# Both language choices remain available regardless of the installer's default.
for locale in en_US he_IL; do
    if ! grep -qx "$locale.UTF-8 UTF-8" /etc/locale.gen; then
        printf '%s.UTF-8 UTF-8\n' "$locale" >> /etc/locale.gen
    fi
    if ! locale -a | grep -ixq "$locale.utf8"; then
        localedef -i "$locale" -f UTF-8 "$locale.UTF-8"
    fi
done
