#!/bin/bash
#
# SPDX-License-Identifier: GPL-3.0-or-later

LIBDIR=${LIBDIR:-'/usr/share/artools/lib'}

# shellcheck source=src/lib/base/message.sh
source "${LIBDIR}"/base/message.sh
# shellcheck source=src/lib/base/chroot.sh
source "${LIBDIR}"/base/chroot.sh

CHROOTVERSION=0.12

# umask might have been changed in /etc/profile
# ensure that sane default is set again
umask 0022

working_dir=''
umode=''

files=()
chroot_args=()
nosetarch=0

usage() {
    printf "Usage: %s [options] working-dir package-list...\n" "${0##*/}"
    printf ' options:\n'
    printf '    -U            Use pacman -U to install packages\n'
    printf '    -C <file>     Location of a pacman config file\n'
    printf '    -M <file>     Location of a makepkg config file\n'
    printf '    -c <dir>      Set pacman cache\n'
    printf '    -f <file>     Copy file from the host to the chroot\n'
    printf '    -s            Do not run setarch\n'
    printf '    -h            This message\n'
    exit 1
}

orig_args=("$@")

opts='hUC:M:c:f:s'

while getopts ${opts} arg; do
    case "${arg}" in
        U) umode=U ;;
        C) pacman_conf="$OPTARG" ;;
        M) makepkg_conf="$OPTARG" ;;
        c) cache_dir="$OPTARG" ;;
        f) files+=("$OPTARG") ;;
        s) nosetarch=1 ;;
        h|?) usage ;;
    esac
    if [[ $arg != U ]]; then
        chroot_args+=("-$arg")
        [[ -v OPTARG ]] && chroot_args+=("$OPTARG")
    fi
done
shift $(( OPTIND - 1 ))

(( $# < 2 )) && die 'You must specify a directory and one or more packages.'

check_root "" "${BASH_SOURCE[0]}" "${orig_args[@]}"

working_dir="$(readlink -f "$1")"
shift 1

[[ -z $working_dir ]] && die 'Please specify a working directory.'

if (( ${#cache_dirs[@]} == 0 )); then
    mapfile -t cache_dirs < <(pacman-conf CacheDir)
fi

umask 0022

[[ -e $working_dir ]] && die "Working directory '%s' already exists" "$working_dir"

mkdir -p "$working_dir"

[[ ! -d $working_dir ]] && mkdir -p "$working_dir"

lock 9 "${working_dir}.lock" "Locking chroot"

if is_btrfs "$working_dir"; then
    rmdir "$working_dir"
    if ! btrfs subvolume create "$working_dir"; then
        die "Couldn't create subvolume for '%s'" "$working_dir"
    fi
    chmod 0755 "$working_dir"
fi

for f in "${files[@]}"; do
    mkdir -p "$(dirname "$working_dir$f")"
    cp "$f" "$working_dir$f"
done

unshare --mount basestrap -${umode}Mc ${pacman_conf:+-C "$pacman_conf"} "$working_dir" \
    "${cache_dirs[@]/#/--cachedir=}" "$@" || die 'Failed to install all packages'

printf '%s.UTF-8 UTF-8\n' en_US de_DE > "$working_dir/etc/locale.gen"
printf 'LANG=C.UTF-8\n' > "$working_dir/etc/locale.conf"
# printf 'KEYMAP=en\n' > "$working_dir/etc/vconsole.conf"
printf "%s\n" "${CHROOTVERSION}" > "$working_dir/.artix-chroot"

dbus-uuidgen --ensure="$working_dir"/etc/machine-id

exec chroot-run \
    "${chroot_args[@]}" \
    "$working_dir" locale-gen
