#!/usr/bin/env bash
# Lifecycle only. Product operations are implemented in the ds1cli binary.
set -euo pipefail
export LC_ALL=C
umask 077
fail() { printf '%s\n' "$*" >&2; exit 1; }
[[ $(uname -s) == Linux && $(uname -m) == x86_64 ]] || fail 'Linux x64 required.'
archive='' expected='' root=${DS1_INSTALL_ROOT:-"$HOME/.local/share/ds1cli"}
link_dir="$HOME/.local/bin" no_path=0 allow_downgrade=0
while (($#)); do
    case $1 in
        --package|--sha256|--install-root|--bin-dir)
            (($# >= 2)) || fail "Missing value: $1"
            case $1 in
                --package) archive=$2;; --sha256) expected=$2;;
                --install-root) root=$2;; --bin-dir) link_dir=$2;;
            esac
            shift 2;;
        --no-path) no_path=1; shift;;
        --allow-downgrade) allow_downgrade=1; shift;;
        *) fail "Unknown argument: $1";;
    esac
done
for tool in realpath sha256sum tar mktemp sort find awk cmp; do
    command -v "$tool" >/dev/null || fail "Missing dependency: $tool"
done
[[ -f $archive ]] || fail 'Provide --package /absolute/package.tar.gz.'
[[ $root == /* && $link_dir == /* && $root != *$'\n'* && $link_dir != *$'\n'* ]] || fail 'Absolute paths without newlines required.'
root=$(realpath -m -- "$root")
link_dir=$(realpath -m -- "$link_dir")
case $root in /|/usr|/usr/local|/opt|/home|"$HOME") fail 'Choose a dedicated installation directory.';; esac
if [[ -z $expected && -f $archive.sha256 ]]; then read -r expected _ < "$archive.sha256"; fi
[[ $expected =~ ^[[:xdigit:]]{64}$ ]] || fail 'Provide --sha256 or adjacent .sha256 file.'
# A private copy prevents the caller from replacing the archive after validation.
scratch=$(mktemp -d)
stage='' backup='' locked=0 swapped=0 had_previous=0 committed=0 created_link=0
cleanup() {
    local rc=$?
    trap - EXIT HUP INT TERM
    set +e
    if ((committed == 0)); then
        if ((created_link)); then rm -f -- "$link_dir/ds1cli"; fi
        if ((swapped)); then rm -rf -- "$root/bin"; fi
        if ((had_previous)); then mv -- "$backup" "$root/bin"; fi
    fi
    [[ -z $stage || $stage != "$root"/.install-* ]] || rm -rf -- "$stage"
    [[ $scratch == /tmp/* || $scratch == "${TMPDIR:-/tmp}"/* ]] && rm -rf -- "$scratch"
    ((locked == 0)) || rmdir -- "$root/.lifecycle-lock"
    exit "$rc"
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' HUP TERM
cp -- "$archive" "$scratch/package.tar.gz"
actual=$(sha256sum "$scratch/package.tar.gz"); actual=${actual%% *}
[[ ${actual,,} == ${expected,,} ]] || fail 'SHA256 mismatch.'
tar -tzf "$scratch/package.tar.gz" > "$scratch/names"
while IFS= read -r entry; do
    [[ $entry != /* && $entry != *\\* ]] || fail 'Unsafe archive path.'
    case /$entry/ in */../*) fail 'Unsafe archive path.';; esac
done < "$scratch/names"
# Portable package v1 contains regular files/directories only (no links/devices).
tar -tvzf "$scratch/package.tar.gz" > "$scratch/types"
awk 'substr($0,1,1)!="-" && substr($0,1,1)!="d" {exit 1}' "$scratch/types" || fail 'Unsupported archive entry type.'
mkdir -p -- "$root"
mkdir -- "$root/.lifecycle-lock" 2>/dev/null || fail 'Another lifecycle operation is active; inspect .lifecycle-lock.'
locked=1
stage=$(mktemp -d "$root/.install-XXXXXXXX")
tar --extract --gzip --file "$scratch/package.tar.gz" --directory "$stage" --no-same-owner --no-same-permissions --keep-old-files
for file in VERSION PLATFORM ds1cli install-client.sh update-client.sh uninstall-client.sh; do
    [[ -f $stage/$file && ! -L $stage/$file ]] || fail "Incomplete package: $file"
done
[[ $(cat "$stage/PLATFORM") == linux-x64 ]] || fail 'Incompatible platform.'
version=$(cat "$stage/VERSION")
[[ $version =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || fail 'Invalid package version.'
if [[ -e $root/bin || -L $root/bin ]]; then
    [[ -d $root/bin && ! -L $root/bin && -f $root/bin/.ds1-receipt ]] || fail 'Unmanaged installation.'
    printf 'ds1cli\n%s\n' "$root" > "$scratch/receipt"
    cmp -s "$scratch/receipt" "$root/bin/.ds1-receipt" || fail 'Invalid installation receipt.'
    previous=$(cat "$root/bin/VERSION")
    [[ $previous =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] || fail 'Invalid installed version.'
    if ((allow_downgrade == 0)) && [[ $previous != "$version" && $(printf '%s\n%s\n' "$previous" "$version" | sort -V | head -n 1) == "$version" ]]; then
        fail 'Downgrade blocked; use --allow-downgrade explicitly.'
    fi
fi
if ((no_path == 0)); then
    if [[ -e $link_dir/ds1cli || -L $link_dir/ds1cli ]]; then
        [[ -L $link_dir/ds1cli && $(readlink -- "$link_dir/ds1cli") == "$root/bin/ds1cli" ]] || fail 'Command path already belongs to another installation.'
    fi
fi
chmod u+x "$stage/ds1cli" "$stage/"*-client.sh
output=$("$stage/ds1cli" --version) || fail 'Executable validation failed.'
[[ $output == "ds1cli/$version "* ]] || fail 'Executable/package version mismatch.'
printf 'ds1cli\n%s\n' "$root" > "$stage/.ds1-receipt"
if ((no_path == 0)); then printf '%s\n' "$link_dir/ds1cli" > "$stage/.ds1-link";
elif [[ -f $root/bin/.ds1-link ]]; then cp -- "$root/bin/.ds1-link" "$stage/.ds1-link"; fi
backup="$root/.backup-${stage##*.install-}"
if [[ -d $root/bin ]]; then mv -- "$root/bin" "$backup"; had_previous=1; fi
mv -- "$stage" "$root/bin"; swapped=1
if ((no_path == 0)) && [[ ! -L $link_dir/ds1cli ]]; then
    mkdir -p -- "$link_dir"
    ln -s -- "$root/bin/ds1cli" "$link_dir/ds1cli"
    created_link=1
fi
committed=1
if ((had_previous)); then rm -rf -- "$backup"; fi
printf 'Installed: %s/bin/ds1cli\n%s\n' "$root" "$output"
if ((no_path == 0)) && [[ :$PATH: != *":$link_dir:"* ]]; then
    printf 'Add this directory to PATH: %s\n' "$link_dir"
fi
