#!/usr/bin/sh

# Script called by qubesbuilder.ProcessGithubCommand for handling "Build-template"
# command
#
# First argument is expected to be a command file path, already
# verified against trusted keys set. 
# Second argument is a key fingerprint used to sign the command

if [ $# -lt 2 ]; then
    echo "Usage: $0 <command-file> <key-fingerprint>" >&2
    exit 1
fi

command_file="$1"
signer_fpr="$2"

scripts_dir="/usr/local/lib/qubes-builder-github"

# shellcheck source=lib/functions.sh
. "$scripts_dir/functions.sh"

read -r action release_name dist timestamp \
        < "$command_file"

if [ "x$action" != "xBuild-template" ]; then
    echo "Invalid action" >&2
    exit 1
fi

case "${dist}" in
    *[/.$IFS]*)
        echo "Forbidden character in dist" >&2
        exit 1
        ;;
    "")
        echo "Empty dist" >&2
        exit 1
        ;;
esac


# release_name verified in build_template_for_release function
# dist verified in build_template_for_release function

if ! printf "%s" "$timestamp" | grep -q "^[0-9]\{12\}$"; then
    echo "Invalid timestamp format" >&2
    exit 1
fi

timestamp_format="%Y%m%d%H%M"
timestamp_max=$(date -u -d '+5 min' +$timestamp_format)
timestamp_min=$(date -u -d '-1 hour' +$timestamp_format)
if [ "$timestamp" -gt "$timestamp_max" ] || \
        [ "$timestamp" -lt "$timestamp_min" ]; then
    echo "Timestamp outside of allowed range" >&2
    exit 1
fi

# enable logging (use qrexec policy to redirect to the right VM)
export QUBES_BUILD_LOG_CMD="qrexec-client-vm 'dom0' qubesbuilder.BuildLog"

build_template_for_release() {
    local_config_release_name="$1"
    local_builder_dir="$2"

    if [ "$local_config_release_name" != "$release_name" ]; then
        return
    fi

    # get DISTS_VM as configured in builder.conf, without resolving aliases yet
    supported_dists=$(make --no-print-directory -C "$local_builder_dir" \
            TEMPLATE_ALIAS= \
            get-var GET_VAR=DISTS_VM)
    allowed_dists=$(get_allowed_dists "$local_builder_dir" "$signer_fpr")

    if ! echo " $supported_dists " | grep -q " $dist "; then
        # not listed in this builder instance
        return
    fi

    if ! echo " $allowed_dists " | grep -q " $dist "; then
        # not allowed here
        return
    fi

    # $dist verified to be in DISTS_VM, now check BUILDER_TEMPLATE_CONF; for
    # that $dist must be translated via TEMPLATE_ALIAS
    dist_translated=$(DISTS_VM=$dist \
            make --no-print-directory -C "$local_builder_dir" \
            get-var GET_VAR=DISTS_VM)
    builder_template_conf=$(make --no-print-directory -C "$local_builder_dir" \
            get-var GET_VAR=BUILDER_TEMPLATE_CONF)
    if ! echo " $builder_template_conf"|grep -q " $dist_translated:"; then
        # template config not set
        return
    fi

    "$local_builder_dir/scripts/auto-build-template" \
        "$dist" "$timestamp"
}

execute_in_each_builder build_template_for_release
