#!/usr/bin/env bash
# Download the signed PautatoTV release, verify it, then run its guided installer.
set -euo pipefail
umask 077
base='https://pautatotv.netlify.app/downloads'
archive='pautatotv-0.5.22-linux-arm64.tar.gz'
if [[ "$(uname -s)" != Linux || "$(uname -m)" != aarch64 ]]; then
  echo 'PautatoTV requires 64-bit Raspberry Pi OS (aarch64). No installation performed.' >&2
  exit 1
fi
for tool in openssl sha256sum tar mktemp; do
  command -v "$tool" >/dev/null || { echo "Missing $tool. Install it before retrying." >&2; exit 1; }
done
if command -v curl >/dev/null; then
  fetch() { curl --proto '=https' --tlsv1.2 -fL --retry 3 --connect-timeout 20 --max-time 180 -o "$2" "$base/$1"; }
elif command -v wget >/dev/null; then
  fetch() { wget --https-only -q --timeout=30 --tries=3 -O "$2" "$base/$1"; }
else
  echo 'Install curl or wget, then retry.' >&2; exit 1
fi
folder=$(mktemp -d "$PWD/pautatotv-install.XXXXXX")
verified=false
trap 'if [[ "$verified" != true ]]; then rm -rf -- "$folder"; fi' EXIT
cd "$folder"
echo 'Downloading the signed PautatoTV package…'
parts=('pautatotv-0.5.22-linux-arm64.tar.gz.part-1' 'pautatotv-0.5.22-linux-arm64.tar.gz.part-2' 'pautatotv-0.5.22-linux-arm64.tar.gz.part-3' 'pautatotv-0.5.22-linux-arm64.tar.gz.part-4' 'pautatotv-0.5.22-linux-arm64.tar.gz.part-5' 'pautatotv-0.5.22-linux-arm64.tar.gz.part-6')
for part in "${parts[@]}"; do fetch "$part" "$part"; done
cat -- "${parts[@]}" > "$archive"
printf '%s  %s\n' 'f0ef10589a6b7cf4ec2d3ecc16982f668f7e3c843f7747cb18f44850684ed1ef' "$archive" | sha256sum -c -
fetch seller-public.pem seller-public.pem
printf '%s  %s\n' '6b5b99bb4828daefa4d489cd7df6f7a9b6537b1ceb67ca5e63c299e7416833fd' seller-public.pem | sha256sum -c -
fetch "$archive.sig" "$archive.sig"
openssl pkeyutl -verify -pubin -inkey seller-public.pem -rawin -in "$archive" -sigfile "$archive.sig"
# Extract only after both the archive checksum and publisher signature pass.
tar -xzf "$archive"
verified=true
printf '\nVerified installer saved in: %s\n' "$folder"
if [[ "${1:-}" == '--download-only' ]]; then
  printf 'To install: cd %q && sudo bash install.sh\n' "$folder"
  exit 0
fi
printf 'Starting the guided installer. Your Pi may ask for your sudo password.\n'
# One command handles a new Pi or an existing installation; explicit repair/options still win.
if [[ "$#" == 0 ]]; then set -- --upgrade; fi
if [[ "$EUID" == 0 ]]; then bash ./install.sh "$@"; else sudo bash ./install.sh "$@"; fi
