#!/bin/sh
# Download a pinned scrcpy-server.jar release, verify SHA-256 against an
# in-script allow-list, and install it into app assets. Idempotent.
#
# Usage:
#   scripts/update-server            # use DEFAULT_VERSION below
#   scripts/update-server 4.0        # use explicit version
#
# Bumping to a new release:
#   1. Run with the new version. The script will print the observed SHA-256
#      and exit non-zero if it is not in the allow-list.
#   2. Paste the printed line into the `case` below.
#   3. Update DEFAULT_VERSION.
#   4. Re-run. Commit the assets.

set -eu

DEFAULT_VERSION='4.0'
VERSION="${1:-$DEFAULT_VERSION}"

ROOT="$(git rev-parse --show-toplevel)"
ASSETS="$ROOT/app/src/main/assets"
URL="https://github.com/Genymobile/scrcpy/releases/download/v$VERSION/scrcpy-server-v$VERSION"

# Known-good SHA-256 sums. Keep one line per blessed version.
EXPECTED=$(cat <<EOF
4.0 84924bd564a1eb6089c872c7521f968058977f91f5ff02514a8c74aff3210f3a
EOF
)

want=$(printf '%s\n' "$EXPECTED" | awk -v v="$VERSION" '$1==v {print $2}')
if [ -z "$want" ]; then
    echo "update-server: version $VERSION is not in the allow-list" >&2
    echo "  to bless it, add this line to the EXPECTED block in this script:" >&2
    echo "    $VERSION <sha256-of-the-downloaded-binary>" >&2
fi

mkdir -p "$ASSETS"
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT

echo "update-server: GET $URL"
curl -fsSL -o "$tmp" "$URL"

got=$(sha256sum "$tmp" | awk '{print $1}')
echo "update-server: sha256 $got"

if [ -z "$want" ]; then
    echo "update-server: refusing to install unverified jar" >&2
    exit 1
fi

if [ "$got" != "$want" ]; then
    echo "update-server: sha256 mismatch" >&2
    echo "  want: $want" >&2
    echo "  got:  $got" >&2
    exit 1
fi

install -m 0644 "$tmp" "$ASSETS/scrcpy-server.jar"
printf '%s\n' "$VERSION" >"$ASSETS/scrcpy-server.version"
printf '%s\n' "$got"     >"$ASSETS/scrcpy-server.sha256"

echo "update-server: installed $ASSETS/scrcpy-server.jar v$VERSION"
