#!/usr/bin/env bash
# Package one immutable beagle-store-native-build artifact as a scratch runtime image.
set -euo pipefail

die() {
  echo "beagle-store-cloudflare-native-image: $*" >&2
  exit 2
}

usage() {
  cat <<'USAGE'
Usage: beagle-store-cloudflare-native-image --artifact /absolute/READY-artifact --tag IMAGE

The artifact must be the absolute content-addressed directory emitted by
beagle-store-native-build. The image contains only its static native server and READY
receipt; it never compiles Graal or carries a JVM.
USAGE
}

artifact=""
tag=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --artifact)
      [[ $# -ge 2 && -z "$artifact" ]] || die "--artifact needs one path"
      artifact="$2"
      shift 2
      ;;
    --tag)
      [[ $# -ge 2 && -z "$tag" ]] || die "--tag needs one image name"
      tag="$2"
      shift 2
      ;;
    --help|-h)
      usage
      exit 0
      ;;
    *) die "unknown argument: $1" ;;
  esac
done

[[ -n "$artifact" && -n "$tag" ]] || {
  usage >&2
  exit 2
}
case "$artifact" in
  /*) ;;
  *) die "--artifact must be absolute: $artifact" ;;
esac

for command in docker readelf realpath; do
  command -v "$command" >/dev/null 2>&1 || die "required command is unavailable: $command"
done

artifact="$(realpath "$artifact")"
[[ -d "$artifact" ]] || die "artifact directory is unavailable: $artifact"
hash="${artifact##*/}"
[[ "$hash" =~ ^[0-9a-f]{64}$ ]] ||
  die "artifact directory name is not a content hash: $artifact"

ready="$artifact/READY"
server="$artifact/bin/beagle-store-server-native"
[[ -r "$ready" ]] || die "artifact READY receipt is unavailable: $ready"
[[ "$(<"$ready")" == "beagle-store-native-build/v1 $hash" ]] ||
  die "artifact READY receipt does not match its content hash: $ready"
[[ -x "$server" ]] || die "artifact native server is unavailable: $server"
if readelf -l "$server" | grep -Fq 'Requesting program interpreter'; then
  die "artifact native server is dynamically linked; Cloudflare image requires static musl"
fi

repo="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd -P)"
exec docker build \
  --file "$repo/deploy/cloudflare/Dockerfile.native" \
  --build-arg "BEAGLE_STORE_NATIVE_ARTIFACT_HASH=$hash" \
  --tag "$tag" \
  "$artifact"
