#!/bin/sh
set -eu

base_url="${CHILDPHONE_BASE_URL:-https://www.childphone.co}"
base_url="${base_url%/}"
version="0.18.6"
json_path="/downloads/childphone-managed-${version}-enrollment.json"
apk_path="/downloads/childphone-managed-${version}.apk"
script_name="${0##*/}"
pass_count=0
fail_count=0

pass() {
  pass_count=$((pass_count + 1))
  printf '[PASS] %s\n' "$1"
}

fail() {
  fail_count=$((fail_count + 1))
  printf '[FAIL] %s\n' "$1"
}

info() {
  printf '[INFO] %s\n' "$1"
}

if ! command -v curl >/dev/null 2>&1; then
  echo "curl was not found. Install curl and try again." >&2
  exit 2
fi
if ! command -v openssl >/dev/null 2>&1; then
  echo "openssl was not found. Install OpenSSL and try again." >&2
  exit 2
fi
if ! command -v base64 >/dev/null 2>&1; then
  echo "base64 was not found. Install a standard base64 utility and try again." >&2
  exit 2
fi

tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT INT TERM
json_file="$tmp_dir/enrollment.json"
apk_file="$tmp_dir/managed.apk"
headers_file="$tmp_dir/headers.txt"

echo "ChildPhone Managed ${version} enrollment-endpoint preflight"
echo "Read-only scope: enrollment JSON, HTTPS response headers, APK bytes, and optional package metadata."
echo "No phone, account, pairing key, family data, or device setting is accessed."
echo

json_url="${base_url}${json_path}"
if curl -fsSL --max-time 30 "$json_url" -o "$json_file"; then
  pass "Enrollment JSON downloads over HTTPS"
else
  fail "Enrollment JSON downloads over HTTPS"
fi

apk_url="$(sed -n 's/.*PROVISIONING_DEVICE_ADMIN_PACKAGE_DOWNLOAD_LOCATION[^:]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$json_file" 2>/dev/null | head -n 1)"
expected_checksum="$(sed -n 's/.*PROVISIONING_DEVICE_ADMIN_PACKAGE_CHECKSUM[^:]*:[[:space:]]*"\([A-Za-z0-9_-]*\)".*/\1/p' "$json_file" 2>/dev/null | head -n 1)"
component="$(sed -n 's/.*PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME[^:]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$json_file" 2>/dev/null | head -n 1)"
system_apps_enabled="$(sed -n 's/.*PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED[^:]*:[[:space:]]*//p' "$json_file" 2>/dev/null | head -n 1 | tr -d ' ,\r\n')"
expected_component="co.childphone.agent.managed/co.childphone.core.ui.ChildPhoneDeviceAdminReceiver"

if [ -n "$apk_url" ]; then
  pass "Enrollment JSON contains an APK download URL"
else
  fail "Enrollment JSON contains an APK download URL"
fi
if [ -n "$expected_checksum" ]; then
  pass "Enrollment JSON contains a URL-safe SHA-256 checksum"
else
  fail "Enrollment JSON contains a URL-safe SHA-256 checksum"
fi
if [ -n "$component" ]; then
  pass "Enrollment JSON contains a Device Owner component"
else
  fail "Enrollment JSON contains a Device Owner component"
fi
if [ "$component" = "$expected_component" ]; then
  pass "Device Owner component matches the published Managed receiver"
else
  fail "Device Owner component matches the published Managed receiver"
fi
if [ "$system_apps_enabled" = "true" ]; then
  pass "Enrollment JSON keeps system apps enabled during setup"
else
  fail "Enrollment JSON keeps system apps enabled during setup"
fi

case "$apk_url" in
  "${base_url}"/*) pass "APK URL stays on the selected ChildPhone host" ;;
  "") fail "APK URL stays on the selected ChildPhone host" ;;
  *) fail "APK URL stays on the selected ChildPhone host" ;;
esac

if [ -n "$apk_url" ] && http_status="$(curl -fsSL -L --max-redirs 3 -D "$headers_file" -o "$apk_file" -w '%{http_code}' --max-time 90 -A 'AndroidDownloadManager/14' "$apk_url")"; then
  if [ "$http_status" = "200" ]; then
    pass "APK download returns HTTP 200"
  else
    fail "APK download returns HTTP 200 (received ${http_status})"
  fi
else
  fail "APK download returns HTTP 200"
fi

content_type="$(sed -n 's/^content-type:[[:space:]]*//Ip' "$headers_file" 2>/dev/null | tail -n 1 | tr -d '\r')"
case "$content_type" in
  application/vnd.android.package-archive|application/octet-stream)
    info "APK content type: ${content_type}" ;;
  "")
    fail "APK response includes a usable content type" ;;
  *)
    info "APK content type is ${content_type}; checksum remains authoritative" ;;
esac

if [ -s "$apk_file" ]; then
  downloaded_checksum="$(openssl dgst -sha256 -binary "$apk_file" | base64 | tr -d '\r\n=' | tr '+/' '-_')"
  if [ -n "$expected_checksum" ] && [ "$downloaded_checksum" = "$expected_checksum" ]; then
    pass "Downloaded APK matches the QR checksum"
  else
    fail "Downloaded APK matches the QR checksum"
  fi
else
  fail "Downloaded APK contains bytes"
fi

aapt_bin="${AAPT_BIN:-}"
if [ -z "$aapt_bin" ]; then
  sdk_root="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-$HOME/Library/Android/sdk}}"
  for candidate in "$sdk_root"/build-tools/*/aapt; do
    if [ -x "$candidate" ]; then aapt_bin="$candidate"; fi
  done
fi

if [ -s "$apk_file" ] && [ -n "$aapt_bin" ] && [ -x "$aapt_bin" ]; then
  badging="$($aapt_bin dump badging "$apk_file" 2>/dev/null || true)"
  if printf '%s\n' "$badging" | grep -F "package: name='co.childphone.agent.managed'" >/dev/null 2>&1; then
    pass "Downloaded APK has the Managed package identity"
  else
    fail "Downloaded APK has the Managed package identity"
  fi
  if printf '%s\n' "$badging" | grep -F "versionCode='26' versionName='0.18.6'" >/dev/null 2>&1; then
    pass "Downloaded APK has the expected signed Managed release"
  else
    fail "Downloaded APK has the expected Managed release"
  fi
else
  info "Android aapt was not found; package metadata check skipped"
fi

echo
if [ "$fail_count" -eq 0 ]; then
  printf 'Endpoint preflight: PASS (%s checks)\n' "$pass_count"
else
  printf 'Endpoint preflight: FAIL (%s passed, %s failed)\n' "$pass_count" "$fail_count"
fi
echo "If this passes but the phone still shows a setup error, factory-reset the phone again and record its model and Android/ColorOS version."

if [ "$fail_count" -ne 0 ]; then exit 1; fi
