#!/usr/bin/env bash
set -euo pipefail
umask 077
root=${DS1_INSTALL_ROOT:-$HOME/.local/share/ds1cli}
archive='' expected='' link_dir="$HOME/.local/bin" no_path=0 plan=0 downgrade=0
while (($#)); do
 case "$1" in
  --package) archive=$2; shift 2;;
  --sha256) expected=$2; shift 2;;
  --install-root) root=$2; shift 2;;
  --bin-dir) link_dir=$2; shift 2;;
  --no-path) no_path=1; shift;;
  --plan) plan=1; shift;;
  --allow-downgrade) downgrade=1; shift;;
  *) printf 'Unknown argument: %s\n' "$1" >&2; exit 2;;
 esac
done
[[ $(uname -s) == Linux && $(uname -m) == x86_64 ]] || { echo 'Linux x64 required.' >&2; exit 1; }
[[ -f $archive && $root == /* && $link_dir == /* ]] || { echo 'Provide --package and absolute install/link directories.' >&2; exit 1; }
root=$(realpath -m -- "$root")
case "$root" in /|"$HOME"|/usr|/usr/local|/home|/opt) echo 'Choose a dedicated installation root.' >&2; exit 1;; esac
if [[ -z $expected && -f $archive.sha256 ]]; then read -r expected _ < "$archive.sha256"; fi
[[ $expected =~ ^[0-9a-fA-F]{64}$ ]] || { echo 'Expected SHA256 required.' >&2; exit 1; }
scratch=$(mktemp -d "${TMPDIR:-/tmp}/ds1cli-installer-XXXXXXXX")
trap 'case "$scratch" in "${TMPDIR:-/tmp}"/ds1cli-installer-*) rm -rf -- "$scratch";; *) exit 1;; esac' EXIT
command -v unzip >/dev/null && command -v zipinfo >/dev/null || { echo 'Install unzip before running this installer.' >&2; exit 1; }
[[ $archive == *.zip ]] || { echo 'The distribution package must be a ZIP file.' >&2; exit 1; }
cp -- "$archive" "$scratch/package.zip"
actual=$(sha256sum "$scratch/package.zip"); actual=${actual%% *}
[[ ${actual,,} == ${expected,,} ]] || { printf 'SHA256 mismatch. Expected=%s; received=%s. Extraction refused.\n' "$expected" "$actual" >&2; exit 1; }
unzip -Z1 "$scratch/package.zip" > "$scratch/names"
while IFS= read -r entry; do
 [[ $entry != /* && $entry != *\\* && $entry != *:* ]] || { echo 'Unsafe archive path.' >&2; exit 1; }
 case /$entry/ in */../*) echo 'Unsafe archive path.' >&2; exit 1;; esac
done < "$scratch/names"
zipinfo -l "$scratch/package.zip" > "$scratch/types"
awk '$1 ~ /^[bclps]/ {exit 1}' "$scratch/types" || { echo 'Unsupported archive entry type.' >&2; exit 1; }
unzip -tq "$scratch/package.zip" >/dev/null || { echo 'ZIP integrity check failed.' >&2; exit 1; }
mkdir "$scratch/package"
unzip -q "$scratch/package.zip" -d "$scratch/package"
[[ -z $(find "$scratch/package" -type l -print -quit) ]] || { echo 'Package links are forbidden.' >&2; exit 1; }
binary="$scratch/package/ds1cli"
[[ -f $binary && -f $scratch/package/build-manifest.json ]] || { echo 'Incomplete bundle.' >&2; exit 1; }
chmod u+x "$binary"
operation=install
[[ ! -f $root/install-receipt.json && ! -f $root/bin/.ds1-receipt ]] || operation=update
args=(package "$operation" --target "$root")
((plan == 0)) || args+=(--plan)
((downgrade == 0)) || { echo 'Native installer requires a matching or higher version.' >&2; exit 1; }
if ((no_path == 0)); then printf 'Optional command link after separate confirmation: %s/ds1cli -> %s/bin/ds1cli\n' "$link_dir" "$root"; fi
"$binary" "${args[@]}"
((plan == 0)) || exit 0
if ((no_path == 0)); then
 printf 'Create/update only the managed command link? [s/N] '
 read -r answer </dev/tty
 case "$answer" in s|sim|y|yes)
  if [[ -e $link_dir/ds1cli || -L $link_dir/ds1cli ]]; then
   [[ -L $link_dir/ds1cli && $(readlink -- "$link_dir/ds1cli") == "$root/bin/ds1cli" ]] || { echo 'Command link belongs to another installation.' >&2; exit 1; }
  else
   mkdir -p -- "$link_dir"
   ln -s -- "$root/bin/ds1cli" "$link_dir/ds1cli"
  fi
  printf '%s\n' "$link_dir/ds1cli" > "$root/.ds1-link";;
 esac
fi
printf 'Installed: %s/bin/ds1cli\n' "$root"
