#!/usr/bin/env bash
set -euo pipefail

url="https://nostr-stg.devruntime.xyz/trust-setup/psy-groth16-trust-setup.tar.gz"
expected_sha="abfd0ad0f2b21be722e0b0b890c1f3255bcf8b70cfd0fe579a591b30be34f978"
target="$HOME/.psy"
tmp_dir="$(mktemp -d)"
archive="$tmp_dir/psy-groth16-trust-setup.tar.gz"

cleanup() {
  rm -rf "$tmp_dir"
}
trap cleanup EXIT

if command -v curl >/dev/null 2>&1; then
  curl -fL --retry 3 --connect-timeout 10 "$url" -o "$archive"
elif command -v wget >/dev/null 2>&1; then
  wget -O "$archive" "$url"
else
  echo "curl or wget is required" >&2
  exit 1
fi

if [ -n "$expected_sha" ]; then
  if command -v sha256sum >/dev/null 2>&1; then
    actual_sha="$(sha256sum "$archive" | awk '{print $1}')"
  else
    actual_sha="$(shasum -a 256 "$archive" | awk '{print $1}')"
  fi
  if [ "$actual_sha" != "$expected_sha" ]; then
    echo "sha256 mismatch: expected $expected_sha, got $actual_sha" >&2
    exit 1
  fi
fi

conflicts=()
while IFS= read -r path; do
  [ -e "$target/$path" ] && conflicts+=("$target/$path")
done <<'PATHS'
keystore/circuit_groth16.bin
keystore/pk_groth16.bin
keystore/vk_groth16.bin
keystore/deposit_append/circuit_groth16.bin
keystore/deposit_append/pk_groth16.bin
keystore/deposit_append/vk_groth16.bin
keystore/withdrawal_claim/circuit_groth16.bin
keystore/withdrawal_claim/pk_groth16.bin
keystore/withdrawal_claim/vk_groth16.bin
PATHS

if [ "${#conflicts[@]}" -gt 0 ]; then
  echo "The following trust setup files already exist:"
  printf "  %s\n" "${conflicts[@]}"
  printf "Overwrite them? [y/N] "
  read -r answer
  case "$answer" in
    y|Y|yes|YES) ;;
    *)
      echo "Install cancelled; existing files were not changed."
      exit 1
      ;;
  esac
fi

mkdir -p "$target"
tar -xzf "$archive" -C "$target"
while IFS= read -r path; do
  chmod 0600 "$target/$path"
done <<'PATHS'
keystore/circuit_groth16.bin
keystore/pk_groth16.bin
keystore/vk_groth16.bin
keystore/deposit_append/circuit_groth16.bin
keystore/deposit_append/pk_groth16.bin
keystore/deposit_append/vk_groth16.bin
keystore/withdrawal_claim/circuit_groth16.bin
keystore/withdrawal_claim/pk_groth16.bin
keystore/withdrawal_claim/vk_groth16.bin
PATHS

echo "Installed Groth16 trust setup into $target/keystore"
