#!/bin/bash
set -e
set -u
set -o pipefail

BASE_DIR="$(git rev-parse --show-toplevel)"

cd "$BASE_DIR"

METADATA_DIR='fastlane/metadata'
ALLOWED_LOCALES='en-US ms th zh-Hans zh-Hant'
REQUIRED_FILES='description.txt keywords.txt name.txt privacy_url.txt release_notes.txt subtitle.txt support_url.txt'

# Upload only the five Kivo localizations that have been reviewed for release.
# An unreviewed upstream localization must never be uploaded under the Kivo app.
for locale_dir in "$METADATA_DIR"/*; do
  [ -d "$locale_dir" ] || continue
  locale="${locale_dir##*/}"
  case " $ALLOWED_LOCALES " in
    *" $locale "*) ;;
    *)
      if find "$locale_dir" -type f -print -quit | grep -q .; then
        echo "Refusing App Store upload: unsupported metadata locale '$locale'." >&2
        exit 1
      fi
      ;;
  esac
done

for locale in $ALLOWED_LOCALES; do
  for filename in $REQUIRED_FILES; do
    path="$METADATA_DIR/$locale/$filename"
    if [ ! -s "$path" ]; then
      echo "Refusing App Store upload: missing metadata file '$path'." >&2
      exit 1
    fi
  done
done

if grep -R -E -i -q 'signal(app)?|support\.signal\.org|github\.com/signalapp|\.invalid([/:]|$)' "$METADATA_DIR"; then
  echo 'Refusing App Store upload: upstream Signal or placeholder metadata is still present.' >&2
  exit 1
fi

# Store links are part of App Review. Do not upload metadata until every public
# Kivo policy/support/source page is live and returns a successful HTTP status.
for url in \
  'https://kivo.it389.com/support' \
  'https://kivo.it389.com/privacy' \
  'https://kivo.it389.com/terms' \
  'https://kivo.it389.com/source'
do
  if ! curl --fail --location --silent --show-error --max-time 15 --output /dev/null "$url"; then
    echo "Refusing App Store upload: required release URL is unavailable: $url" >&2
    exit 1
  fi
done

bundle exec fastlane deliver \
  --skip-screenshots \
  --skip-binary-upload \
  --username "$FASTLANE_USERNAME" \
  --phased_release true \
  --reset_ratings false \
  --automatic_release false \
  --run_precheck_before_submit false \
  --app_identifier 'com.zhiera.kivo'
