#!/bin/sh

set -eu
set -f

PREREQ=""
DESCRIPTION="Applying AnduinOS Live session timezone..."

prereqs()
{
    echo "$PREREQ"
}

case "${1:-}" in
prereqs)
    prereqs
    exit 0
    ;;
esac

casper_functions=${CASPER_FUNCTIONS:-/scripts/casper-functions}
cmdline_file=${CASPER_CMDLINE_FILE:-/proc/cmdline}
target_root=${CASPER_TARGET_ROOT:-/root}

# shellcheck disable=SC1090
. "$casper_functions"

log_begin_msg "$DESCRIPTION"

live_timezone=
# Kernel command lines are whitespace-delimited, not shell command lines.
# Disable pathname expansion before splitting user-editable boot arguments.
for argument in $(cat "$cmdline_file"); do
    case "$argument" in
    timezone=*)
        live_timezone=${argument#timezone=}
        ;;
    esac
done

if [ -z "$live_timezone" ]; then
    log_end_msg
    exit 0
fi

# Kernel arguments are editable by the user. Treat the timezone as hostile
# input even though normal entries are generated by the AnduinOS ISO builder.
case "$live_timezone" in
/*|*..*|*[!A-Za-z0-9_+./-]*)
    echo "casper: ignoring invalid timezone: $live_timezone" >&2
    log_end_msg
    exit 0
    ;;
esac

zone_file="$target_root/usr/share/zoneinfo/$live_timezone"
if [ ! -f "$zone_file" ]; then
    echo "casper: timezone data is missing: $live_timezone" >&2
    log_end_msg
    exit 0
fi

mkdir -p "$target_root/etc"
printf '%s\n' "$live_timezone" > "$target_root/etc/timezone"
ln -snf "/usr/share/zoneinfo/$live_timezone" "$target_root/etc/localtime"

echo "casper: Live session timezone: $live_timezone"
log_end_msg
