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

out="${1:-/srv/lcs-downloads}"
stage="$(mktemp -d)"
trap 'rm -rf "$stage"' EXIT

get_release() {
  local repo="$1" tag="$2" file="$3"
  curl --fail --silent --show-error --location \
    --proto '=https' --proto-redir '=https' \
    -H 'Accept: application/vnd.github+json' \
    -H 'X-GitHub-Api-Version: 2022-11-28' \
    "https://api.github.com/repos/${repo}/releases/tags/${tag}" \
    --output "$file"

  jq -e --arg tag "$tag" '.tag_name == $tag' "$file" >/dev/null || {
    echo "Release tag mismatch for $repo $tag; stopping." >&2
    exit 1
  }
}

get_release "daylight-hub/lcs-meshchat" "v2.0.9" "$stage/meshchat.json"
get_release "daylight-hub/libertychat" "v2.3.4" "$stage/libertychat.json"

urls=(
  "https://github.com/daylight-hub/lcs-meshchat/releases/download/v2.0.9/LCS-ReticulumMeshChat-v2.0.9-linux.AppImage"
  "https://github.com/daylight-hub/lcs-meshchat/releases/download/v2.0.9/LCS-ReticulumMeshChat-v2.0.9-mac-arm64.dmg"
  "https://github.com/daylight-hub/lcs-meshchat/releases/download/v2.0.9/LCS-ReticulumMeshChat-v2.0.9-mac-x64.dmg"
  "https://github.com/daylight-hub/lcs-meshchat/releases/download/v2.0.9/LCS-ReticulumMeshChat-v2.0.9-win-installer.exe"
  "https://github.com/daylight-hub/libertychat/releases/download/v2.3.4/libertychat-2.3.4-official-rns-py-arm64-v8a.apk"
)

for url in "${urls[@]}"; do
  name="${url##*/}"
  if [[ "$url" == *"/libertychat/"* ]]; then
    release_file="$stage/libertychat.json"
  else
    release_file="$stage/meshchat.json"
  fi

  digest="$(jq -r --arg name "$name" \
    '[.assets[]? | select(.name == $name) | .digest // empty] | .[0] // empty' \
    "$release_file")"

  if [[ ! "$digest" =~ ^sha256:[0-9a-fA-F]{64}$ ]]; then
    echo "No published SHA-256 digest for $name; stopping." >&2
    exit 1
  fi

  curl --fail --silent --show-error --location \
    --proto '=https' --proto-redir '=https' \
    --retry 3 --output "$stage/$name" "$url"

  expected="${digest#sha256:}"
  actual="$(sha256sum "$stage/$name" | awk '{print $1}')"

  if [[ "${actual,,}" != "${expected,,}" ]]; then
    echo "CHECKSUM MISMATCH: $name" >&2
    exit 1
  fi
  echo "SHA-256 OK: $name"
done

mkdir -p "$out"
for url in "${urls[@]}"; do
  name="${url##*/}"
  install -m 0644 "$stage/$name" "$out/$name"
done

echo "All five verified files saved in: $out"
