#!/usr/bin/env bash
#
# Rebuilds a self-hosted F-Droid repo for PaperScan: downloads every release APK
# from the Gitea repository and regenerates the (signed) index.
#
# Prerequisites:
#   * fdroidserver installed (`pipx install fdroidserver`)
#   * `fdroid init` run once in $FDROID_HOME (creates config.yml + keystore)
#   * JDK + Android SDK build-tools on PATH
#
# Usage:
#   FDROID_HOME=~/paperscan-fdroid ./scripts/update-fdroid-repo.sh
#
set -euo pipefail

FDROID_HOME="${FDROID_HOME:-$HOME/paperscan-fdroid}"
GITEA_API="${GITEA_API:-https://git.geyskens.eu/api/v1/repos/sam/paperscan}"

if [ ! -f "$FDROID_HOME/config.yml" ]; then
  echo "No F-Droid repo at $FDROID_HOME. Run 'fdroid init' there first (see docs/FDROID.md)." >&2
  exit 1
fi

mkdir -p "$FDROID_HOME/repo"
cd "$FDROID_HOME"

echo "Fetching release APK list from Gitea…"
curl -fsSL "$GITEA_API/releases?limit=50" \
  | python3 -c "import sys,json;[print(a['browser_download_url']) for r in json.load(sys.stdin) for a in r.get('assets',[]) if a['name'].endswith('.apk')]" \
  | while read -r url; do
      dest="repo/$(basename "$url")"
      if [ -f "$dest" ]; then
        echo "  have $(basename "$url")"
      else
        echo "  get  $(basename "$url")"
        curl -fsSL "$url" -o "$dest"
      fi
    done

echo "Rebuilding index…"
fdroid update --create-metadata --pretty

echo
echo "Done. Publish the repo, e.g.:"
echo "  rsync -a --delete \"$FDROID_HOME/repo/\" web:/var/www/fdroid/repo/"
