#!/usr/bin/env nix-shell
#!nix-shell -i bash --pure --keep GITHUB_TOKEN -p nix git curl cacert jq

set -euo pipefail

cd "$(dirname "${BASH_SOURCE[0]}")"

# Fetch the latest release version from GitHub
payload=$(curl -sL https://api.github.com/repos/bisq-network/bisq/releases/latest)
version=$(jq -r .tag_name <<< "$payload" | sed 's/^v//')

echo "Updating bisq1 to version $version"

# URLs for the new version
deb_url="https://github.com/bisq-network/bisq/releases/download/v${version}/Bisq-64bit-${version}.deb"
sig_url="https://github.com/bisq-network/bisq/releases/download/v${version}/Bisq-64bit-${version}.deb.asc"

# Fetch and compute hashes using nix-prefetch-url and convert to SRI format
echo "Prefetching .deb package..."
deb_hash_raw=$(nix-prefetch-url "$deb_url" 2>/dev/null)
deb_hash=$(nix --extra-experimental-features nix-command hash convert --to sri --hash-algo sha256 "$deb_hash_raw")
echo "  deb hash: $deb_hash"

echo "Prefetching signature..."
sig_hash_raw=$(nix-prefetch-url "$sig_url" 2>/dev/null)
sig_hash=$(nix --extra-experimental-features nix-command hash convert --to sri --hash-algo sha256 "$sig_hash_raw")
echo "  signature hash: $sig_hash"

# Fetch and compute hashes for public keys (these may not exist in all releases)
get_key_hash() {
  local key_name=$1
  local url="https://github.com/bisq-network/bisq/releases/download/v${version}/${key_name}.asc"
  local hash_raw
  if hash_raw=$(nix-prefetch-url "$url" 2>/dev/null); then
    nix --extra-experimental-features nix-command hash convert --to sri --hash-algo sha256 "$hash_raw"
  else
    echo ""  # Return empty if key doesn't exist
  fi
}

echo "Prefetching public keys..."
key_E222AA02_hash=$(get_key_hash "E222AA02")
if [ -n "$key_E222AA02_hash" ]; then
  echo "  E222AA02 hash: $key_E222AA02_hash"
else
  echo "  E222AA02: not found in this release, keeping old hash"
  key_E222AA02_hash=$(grep 'key-E222AA02-hash' sources.nix | sed 's/.*= "\(.*\)".*/\1/')
fi

key_4A133008_hash=$(get_key_hash "4A133008")
if [ -n "$key_4A133008_hash" ]; then
  echo "  4A133008 hash: $key_4A133008_hash"
else
  echo "  4A133008: not found in this release, keeping old hash"
  key_4A133008_hash=$(grep 'key-4A133008-hash' sources.nix | sed 's/.*= "\(.*\)".*/\1/')
fi

key_387C8307_hash=$(get_key_hash "387C8307")
if [ -n "$key_387C8307_hash" ]; then
  echo "  387C8307 hash: $key_387C8307_hash"
else
  echo "  387C8307: not found in this release, keeping old hash"
  key_387C8307_hash=$(grep 'key-387C8307-hash' sources.nix | sed 's/.*= "\(.*\)".*/\1/')
fi

# Write sources.nix (only include keys that exist)
cat >sources.nix <<EOF
# Generated by ./update.sh
{
  version = "$version";
  deb-hash = "$deb_hash";
  sig-hash = "$sig_hash";
  key-E222AA02-hash = "$key_E222AA02_hash";
  key-4A133008-hash = "$key_4A133008_hash";
  key-387C8307-hash = "$key_387C8307_hash";
}
EOF

echo "Updated sources.nix with version $version"
