#!/usr/bin/env bash
# Sahi — build the upload zip for the Chrome Web Store.
#
#   ./store/package.sh
#
# Checks the things the store rejects submissions for before you find out the
# slow way, then writes store/sahi-extension-<version>.zip.

set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
ext="$root/extension"
out="$root/store"

version=$(python3 -c "import json;print(json.load(open('$ext/manifest.json'))['version'])")
echo "Packaging Sahi $version"

# 1. Manifest must parse.
python3 -c "import json;json.load(open('$ext/manifest.json'))" \
  || { echo "manifest.json is not valid JSON"; exit 1; }

# 2. Every icon the manifest names must exist.
python3 - "$ext" <<'PY'
import json, os, sys
ext = sys.argv[1]
m = json.load(open(os.path.join(ext, 'manifest.json')))
missing = [p for p in m.get('icons', {}).values() if not os.path.isfile(os.path.join(ext, p))]
if missing:
    print('Missing icons: ' + ', '.join(missing)); sys.exit(1)
PY

# 3. No development leftovers. A hardcoded localhost server address is the
#    classic one — it passes review and then works for nobody.
if grep -rInE "localhost|127\.0\.0\.1" "$ext" --include='*.js' --include='*.json' >/dev/null; then
  echo "A localhost reference is still in the extension source:"
  grep -rInE "localhost|127\.0\.0\.1" "$ext" --include='*.js' --include='*.json'
  exit 1
fi

# 4. Anything left logging to the console in a shipped build is noise in a
#    user's devtools. Warnings are allowed; console.log is not.
if grep -rIn "console\.log" "$ext" --include='*.js' >/dev/null; then
  echo "console.log left in:"
  grep -rIn "console\.log" "$ext" --include='*.js'
  exit 1
fi

rm -f "$out/sahi-extension-$version.zip"
( cd "$ext" && zip -qr "$out/sahi-extension-$version.zip" . \
    -x '*.DS_Store' -x '__MACOSX/*' -x '*.map' )

echo "Wrote store/sahi-extension-$version.zip"
echo
echo "Before you submit:"
echo "  - host store/privacy-policy.html somewhere public and put the URL in the listing"
echo "  - paste the permission justifications from store/listing.md"
echo "  - the reviewer needs a working test key; issue one and put it in the review notes"
