#!/usr/bin/env bash
set -euo pipefail
base=${VARIONOTE_DOWNLOAD_URL:-https://varionote-install.bigu.tools}
version=${VARIONOTE_VERSION:-0.1.0}
php_version=${VARIONOTE_PHP_VERSION:-8.4}
[[ $base == https://* && $version =~ ^[0-9]+\.[0-9]+\.[0-9]+$ && $php_version =~ ^8\.[234]$ ]] || exit 1
[[ $(uname -s) == Linux ]] || { echo 'Dieses Installationspaket ist für Linux vorgesehen.'; exit 1; }
case $(uname -m) in x86_64) arch=amd64;; aarch64) arch=arm64;; *) echo 'Nicht unterstützte Architektur'; exit 1;; esac
command -v python3 >/dev/null || { echo 'python3 wird benötigt'; exit 1; }
name="varionote-${version}-php${php_version}-linux-${arch}.tar.gz"
work=$(mktemp -d)
trap 'rm -rf -- "$work"' EXIT
cd -- "$work"
for file in "$name" "$name.sha256"; do
  curl --fail --show-error --location --proto '=https' --proto-redir '=https' --retry 3 "${base%/}/v${version}/$file" -o "$file"
done
python3 - "$name" <<'PY'
import hashlib,pathlib,re,sys,tarfile
p=pathlib.Path(sys.argv[1]); record=p.with_name(p.name+'.sha256').read_text().strip()
assert re.fullmatch(r'[a-f0-9]{64}  '+re.escape(p.name),record), 'Unerwartetes Prüfsummenformat'
h=hashlib.sha256()
with p.open('rb') as f:
 for chunk in iter(lambda:f.read(1024*1024),b''): h.update(chunk)
assert h.hexdigest()==record[:64], 'SHA-256 stimmt nicht'
with tarfile.open(p) as a:
 for m in a.getmembers():
  parts=pathlib.PurePosixPath(m.name).parts
  assert parts and parts[0]=='varionote-install' and '..' not in parts and not m.name.startswith('/'), 'Unsicherer Archivpfad'
  assert m.isfile() or m.isdir(), 'Links und Sonderdateien sind nicht erlaubt'
 a.extractall('.')
PY
sudo bash varionote-install/install.sh "$@"
