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

# All user input arrives via environment variables, never executable shell text.
: "${RELEASE_TAG:?Choose an existing release tag}"
: "${GH_REPO:?Missing GitHub repository}"
: "${GITHUB_OUTPUT:?Missing workflow output file}"
[[ "$RELEASE_TAG" == v* ]] || { echo 'Release tags must start with v.' >&2; exit 2; }
REPO_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)
export YOKAN_VERSION="$RELEASE_TAG"
. "$REPO_ROOT/scripts/yokan-version.sh"

selected=false
for platform in ANDROID LINUX MACOS WINDOWS IOS IOS_FRAMEWORK; do
  [[ "${!platform:-false}" != true ]] || selected=true
done
[[ "$selected" == true ]] || { echo 'Select at least one platform.' >&2; exit 2; }

# GitHub hosts releases; the app's source tags live in Forgejo.
refs=$(bash "$REPO_ROOT/.github/scripts/with-forgejo-auth.sh" git ls-remote \
  https://git.friedcutlet.com/friedcutlet/yokan.git "refs/tags/$RELEASE_TAG" "refs/tags/$RELEASE_TAG^{}")
commit=$(printf '%s\n' "$refs" | awk -v tag="refs/tags/$RELEASE_TAG" '
  $2 == tag { direct = $1 }
  $2 == tag "^{}" { peeled = $1 }
  END { print (peeled != "" ? peeled : direct) }
')
[[ "$commit" =~ ^[0-9a-f]{40}$ ]] || { echo 'Could not resolve the selected tag commit.' >&2; exit 2; }
prerelease=true
[[ "$YOKAN_RELEASE_CHANNEL" != stable ]] || prerelease=false

# List once: a network/auth failure must not be treated as a nonexistent release.
release_id=$(gh api --paginate "repos/$GH_REPO/releases?per_page=100" --jq ".[] | select(.tag_name == \"$RELEASE_TAG\") | .id")
if [[ -z "$release_id" ]]; then
  # Release-only repositories may have no matching GitHub tag yet. Pin that
  # hosting tag to the automation commit; source compilation uses Forgejo's SHA.
  args=(--repo "$GH_REPO" --target "${GITHUB_SHA:?Missing workflow commit}" --draft --title "Yokan $RELEASE_TAG ($YOKAN_RELEASE_CHANNEL)")
  [[ "$prerelease" != true ]] || args+=(--prerelease)
  gh release create "$RELEASE_TAG" "${args[@]}"
fi
assets=$(gh release view "$RELEASE_TAG" --repo "$GH_REPO" --json assets --jq '.assets[].name')

needs_asset() {
  [[ "${REBUILD_EXISTING:-false}" == true ]] || ! printf '%s\n' "$assets" | grep -Fxq "$1"
}
need_android=false; need_linux=false; need_macos=false; need_windows=false; need_ios=false; need_framework=false
if [[ "${ANDROID:-false}" == true ]] && needs_asset "Yokan-$RELEASE_TAG-android.apk"; then need_android=true; fi
if [[ "${LINUX:-false}" == true ]] && { needs_asset "Yokan-$RELEASE_TAG-linux.deb" || needs_asset "Yokan-$RELEASE_TAG-linux.AppImage"; }; then need_linux=true; fi
if [[ "${MACOS:-false}" == true ]] && needs_asset "Yokan-$RELEASE_TAG-macos.dmg"; then need_macos=true; fi
if [[ "${WINDOWS:-false}" == true ]] && needs_asset "Yokan-$RELEASE_TAG-windows.msi"; then need_windows=true; fi
if [[ "${IOS:-false}" == true ]] && needs_asset "Yokan-$RELEASE_TAG-ios-unsigned.ipa"; then need_ios=true; fi
if [[ "${IOS_FRAMEWORK:-false}" == true ]] && needs_asset "Yokan-$RELEASE_TAG-ios-framework.zip"; then need_framework=true; fi
{
  echo "commit=$commit"
  echo "channel=$YOKAN_RELEASE_CHANNEL"
  echo "prerelease=$prerelease"
  echo "android=$need_android"
  echo "linux=$need_linux"
  echo "macos=$need_macos"
  echo "windows=$need_windows"
  echo "ios=$need_ios"
  echo "ios_framework=$need_framework"
} >> "$GITHUB_OUTPUT"

if [[ -n "${GITHUB_STEP_SUMMARY:-}" ]]; then
  printf 'Release: **%s (%s)**\n\nSource commit: `%s`\n\nBuilds needed: Android %s; Linux %s; macOS %s; Windows %s; iOS IPA %s; iOS framework %s.\n' \
    "$RELEASE_TAG" "$YOKAN_RELEASE_CHANNEL" "$commit" "$need_android" "$need_linux" "$need_macos" "$need_windows" "$need_ios" "$need_framework" >> "$GITHUB_STEP_SUMMARY"
fi
