#!/bin/sh
# First-run entry: system tools only, then the verified installation Skill.
set -eu
umask 077

web_fail() {
  printf '{"status":"blocked","error_code":"%s"}\n' "$1"
  exit 2
}

case "${1:-}" in
  --help|-h)
    printf '%s\n' 'Install from https://www.mediapilot.vip/submission/ using system tools.' \
      'Arguments are passed unchanged to the verified installation Skill.'
    exit 0 ;;
esac

[ "$(uname -s)" = Darwin ] && [ "$(uname -m)" = arm64 ] || web_fail WEB_INSTALL_PLATFORM_UNSUPPORTED
for web_tool in curl plutil tar shasum cmp find sort sed awk wc tr mktemp chmod mkdir mv rm rmdir cat; do
  command -v "$web_tool" >/dev/null 2>&1 || web_fail WEB_INSTALL_SYSTEM_TOOL_MISSING
done
[ -x /usr/bin/perl ] || web_fail WEB_INSTALL_SYSTEM_TOOL_MISSING
case "${HOME:-}" in /*) ;; *) web_fail WEB_INSTALL_HOME_INVALID ;; esac
[ "$HOME" != / ] && [ -d "$HOME" ] || web_fail WEB_INSTALL_HOME_INVALID
web_home=$(CDPATH= cd -- "$HOME" && pwd -P) || web_fail WEB_INSTALL_HOME_INVALID
web_codex="$web_home/.codex"
web_skills="$web_codex/skills"
web_target="$web_skills/submission-install"
for web_path in "$web_codex" "$web_skills" "$web_target"; do
  [ ! -L "$web_path" ] || web_fail WEB_INSTALL_PATH_UNSAFE
done
mkdir -p "$web_skills" || web_fail WEB_INSTALL_HOME_UNWRITABLE
web_lock="$web_codex/.submission-web-install.lock"
# Preserve an unidentifiable legacy directory lock for explicit review. It may
# still belong to an older running installer, which did not record its owner.
[ ! -L "$web_lock" ] || web_fail WEB_INSTALL_LOCK_UNSAFE
[ ! -d "$web_lock" ] || web_fail WEB_INSTALL_LEGACY_LOCK_REQUIRES_REVIEW
if [ ! -e "$web_lock" ]; then
  (set -C; : > "$web_lock") 2>/dev/null || true
fi
[ ! -L "$web_lock" ] && [ -f "$web_lock" ] && [ -w "$web_lock" ] || web_fail WEB_INSTALL_LOCK_UNSAFE
if ! { exec 9>> "$web_lock"; } 2>/dev/null; then
  web_fail WEB_INSTALL_LOCK_FAILED
fi
# macOS Perl uses flock's shared open-file-description lock. Descriptor 9 stays
# open in this shell and its installation child, including across exec. The
# kernel releases it when the last holder exits, including after SIGKILL.
# Keep the inode permanently: unlinking it would permit two different locks.
if /usr/bin/perl -MFcntl=:flock,:mode -MErrno=EAGAIN,EWOULDBLOCK - "$web_lock" <<'WEB_LOCK'
use strict;
use warnings;
sub fail {
    print '{"status":"blocked","error_code":"' . $_[0] . '"}' . "\n";
    exit 2;
}
my ($path) = @ARGV;
open(my $handle, '>&=9') or fail('WEB_INSTALL_LOCK_FAILED');
sub safe_identity {
    my @opened = stat($handle);
    my @named = lstat($path);
    return @opened && @named && S_ISREG($opened[2]) && !S_ISLNK($named[2])
        && $opened[4] == $> && ($opened[2] & 07777) == 0600 && $opened[3] == 1
        && $opened[0] == $named[0] && $opened[1] == $named[1];
}
safe_identity() or fail('WEB_INSTALL_LOCK_UNSAFE');
if (!flock($handle, LOCK_EX | LOCK_NB)) {
    fail(($! == EAGAIN || $! == EWOULDBLOCK) ? 'WEB_INSTALL_BUSY' : 'WEB_INSTALL_LOCK_FAILED');
}
safe_identity() or fail('WEB_INSTALL_LOCK_UNSAFE');
WEB_LOCK
then
  :
else
  exit "$?"
fi
web_temp=''
web_rollback=''
web_cleanup() {
  if [ -n "$web_rollback" ] && [ ! -e "$web_target" ] && [ ! -L "$web_target" ]; then
    mv "$web_rollback" "$web_target" || true
  fi
  [ -z "$web_temp" ] || rm -rf "$web_temp"
}
trap web_cleanup EXIT
trap 'exit 130' HUP INT TERM
web_temp=$(mktemp -d "$web_codex/.submission-web.XXXXXXXX") || web_fail WEB_INSTALL_TEMP_FAILED

web_json() { plutil -extract "$1" raw -expect "${3:-string}" -o - "$2" 2>/dev/null; }
web_sha() { shasum -a 256 "$1" | sed 's/ .*//'; }
web_valid_sha() {
  case "$1" in ''|*[!0-9a-f]*) return 1 ;; esac
  [ "${#1}" -eq 64 ]
}
web_valid_version() {
  case "$1" in ''|*[!0-9.]*) return 1 ;; esac
  [ "${#1}" -le 32 ] || return 1
  [ "$(printf '%s\n' "$1" | LC_ALL=C sed -n '/^[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*$/p')" = "$1" ] && [ -n "$1" ]
}
web_download() {
  # Deliberately do not follow redirects to another host or another release.
  web_http_code=$(curl -q --fail --silent --show-error --proto '=https' --connect-timeout 15 \
    --max-time 300 --max-filesize "$3" -H 'Cache-Control: no-cache' "$1" -o "$2" \
    --write-out '%{http_code}' 2>"$web_temp/download-error") || return 1
  [ "$web_http_code" = 200 ]
}

web_download 'https://www.mediapilot.vip/submission/latest.json' "$web_temp/latest.json" 16384 || web_fail WEB_INSTALL_MANIFEST_DOWNLOAD_FAILED
web_manifest_size=$(wc -c < "$web_temp/latest.json" | tr -d '[:space:]')
[ "$web_manifest_size" -le 16384 ] || web_fail WEB_INSTALL_MANIFEST_TOO_LARGE
[ "$(web_json schemaVersion "$web_temp/latest.json")" = 'submission-installer.release.v1' ] || web_fail WEB_INSTALL_MANIFEST_INVALID
[ "$(web_json publishable "$web_temp/latest.json" bool)" = true ] || web_fail WEB_INSTALL_RELEASE_NOT_PUBLISHED
[ "$(web_json source.kind "$web_temp/latest.json")" = committed_snapshot ] || web_fail WEB_INSTALL_SOURCE_NOT_COMMITTED
web_source_sha=$(web_json source.sha256 "$web_temp/latest.json") || web_fail WEB_INSTALL_MANIFEST_INVALID
web_valid_sha "$web_source_sha" || web_fail WEB_INSTALL_SOURCE_DIGEST_INVALID
web_version=$(web_json version "$web_temp/latest.json") || web_fail WEB_INSTALL_MANIFEST_INVALID
web_url=$(web_json installer.url "$web_temp/latest.json") || web_fail WEB_INSTALL_MANIFEST_INVALID
web_expected=$(web_json installer.sha256 "$web_temp/latest.json") || web_fail WEB_INSTALL_MANIFEST_INVALID
web_size=$(web_json installer.size "$web_temp/latest.json" integer) || web_fail WEB_INSTALL_MANIFEST_INVALID
web_valid_version "$web_version" || web_fail WEB_INSTALL_VERSION_INVALID
web_valid_sha "$web_expected" || web_fail WEB_INSTALL_DIGEST_INVALID
case "$web_size" in ''|*[!0-9]*) web_fail WEB_INSTALL_SIZE_INVALID ;; esac
[ "${#web_size}" -le 8 ] && [ "$web_size" -gt 0 ] && [ "$web_size" -le 67108864 ] || web_fail WEB_INSTALL_SIZE_INVALID
[ "$web_url" = "https://www.mediapilot.vip/submission/releases/$web_version/submission-install-$web_version.zip" ] || web_fail WEB_INSTALL_URL_REJECTED

web_archive="$web_temp/installer.zip"
web_download "$web_url" "$web_archive" 67108864 || web_fail WEB_INSTALL_PACKAGE_DOWNLOAD_FAILED
[ "$(wc -c < "$web_archive" | tr -d '[:space:]')" = "$web_size" ] || web_fail WEB_INSTALL_PACKAGE_SIZE_MISMATCH
[ "$(web_sha "$web_archive")" = "$web_expected" ] || web_fail WEB_INSTALL_PACKAGE_DIGEST_MISMATCH

cat > "$web_temp/files" <<'WEB_FILES'
CHANGELOG.md
SKILL.md
VERSION
agents/openai.yaml
assets/manifest.json
assets/source.tar.gz
assets/source.tar.gz.sha256
scripts/install.sh
WEB_FILES
sed 's#^#submission-install/#' "$web_temp/files" > "$web_temp/expected-members"
tar -tf "$web_archive" > "$web_temp/members" 2>/dev/null || web_fail WEB_INSTALL_ARCHIVE_INVALID
LC_ALL=C sort "$web_temp/members" > "$web_temp/members-sorted"
cmp -s "$web_temp/expected-members" "$web_temp/members-sorted" || web_fail WEB_INSTALL_ARCHIVE_MEMBERS_INVALID
LC_ALL=C tar -tvf "$web_archive" > "$web_temp/member-types" 2>/dev/null || web_fail WEB_INSTALL_ARCHIVE_INVALID
while IFS= read -r web_type; do
  case "$web_type" in -*) ;; *) web_fail WEB_INSTALL_ARCHIVE_TYPE_INVALID ;; esac
done < "$web_temp/member-types"
awk 'BEGIN {total=0} $5 !~ /^[0-9]+$/ || $5 > 67108864 {exit 1} {total += $5} END {if (total > 83886080) exit 1}' "$web_temp/member-types" || web_fail WEB_INSTALL_ARCHIVE_SIZE_INVALID
tar -xf "$web_archive" -C "$web_temp" 2>/dev/null || web_fail WEB_INSTALL_ARCHIVE_INVALID
web_stage="$web_temp/submission-install"
[ "$(web_json repository_version "$web_stage/assets/manifest.json")" = "$web_version" ] || web_fail WEB_INSTALL_PACKAGE_VERSION_MISMATCH
[ "$(web_json source_kind "$web_stage/assets/manifest.json")" = committed_snapshot ] || web_fail WEB_INSTALL_SOURCE_NOT_COMMITTED
[ "$(web_json source_sha256 "$web_stage/assets/manifest.json")" = "$web_source_sha" ] || web_fail WEB_INSTALL_SOURCE_DIGEST_MISMATCH

web_receipt='.submission-web-install.json'
if [ -e "$web_target" ]; then
  if [ ! -e "$web_target/$web_receipt" ] && [ ! -L "$web_target/.submission-installer-package.json" ] \
      && [ -f "$web_target/.submission-installer-package.json" ] \
      && [ "$(web_json owner "$web_target/.submission-installer-package.json")" = 'mac-submission-skills/installer' ]; then
    web_fail WEB_INSTALL_LEGACY_REGISTRATION_REQUIRES_MIGRATION
  fi
  [ -d "$web_target" ] && [ ! -L "$web_target/$web_receipt" ] && [ -f "$web_target/$web_receipt" ] || web_fail WEB_INSTALL_FOREIGN_SKILL
  [ "$(web_json schemaVersion "$web_target/$web_receipt")" = 'submission-installer.registration.v1' ] || web_fail WEB_INSTALL_FOREIGN_SKILL
  [ "$(web_json owner "$web_target/$web_receipt")" = 'mac-submission-skills/web-installer' ] || web_fail WEB_INSTALL_FOREIGN_SKILL
  web_old_sha=$(web_json packageSha256 "$web_target/$web_receipt") || web_fail WEB_INSTALL_FOREIGN_SKILL
  web_old_version=$(web_json version "$web_target/$web_receipt") || web_fail WEB_INSTALL_FOREIGN_SKILL
  web_valid_sha "$web_old_sha" && web_valid_version "$web_old_version" || web_fail WEB_INSTALL_FOREIGN_SKILL
  [ "$(web_json repository_version "$web_target/assets/manifest.json")" = "$web_old_version" ] || web_fail WEB_INSTALL_FOREIGN_SKILL
  web_index=0
  while IFS= read -r web_file; do
    [ ! -L "$web_target/$web_file" ] && [ -f "$web_target/$web_file" ] || web_fail WEB_INSTALL_CHANGED_SKILL
    [ "$(web_json "files.$web_index.path" "$web_target/$web_receipt")" = "$web_file" ] || web_fail WEB_INSTALL_FOREIGN_SKILL
    web_old_file_sha=$(web_json "files.$web_index.sha256" "$web_target/$web_receipt") || web_fail WEB_INSTALL_FOREIGN_SKILL
    web_valid_sha "$web_old_file_sha" || web_fail WEB_INSTALL_FOREIGN_SKILL
    [ "$(web_sha "$web_target/$web_file")" = "$web_old_file_sha" ] || web_fail WEB_INSTALL_CHANGED_SKILL
    web_index=$((web_index + 1))
  done < "$web_temp/files"
  [ "$(web_json files "$web_target/$web_receipt" array)" = 8 ] || web_fail WEB_INSTALL_FOREIGN_SKILL
  # Compare the entire tree: unknown files and empty directories are retained,
  # never silently discarded by installing a different package over them.
  (cd "$web_target" && find . -mindepth 1 -print | sed 's#^./##' | LC_ALL=C sort) > "$web_temp/installed-members"
  { cat "$web_temp/files"; printf '%s\n' "$web_receipt" agents assets scripts; } | LC_ALL=C sort > "$web_temp/expected-installed"
  cmp -s "$web_temp/installed-members" "$web_temp/expected-installed" || web_fail WEB_INSTALL_CHANGED_SKILL
fi

find "$web_stage" -type d -exec chmod 700 {} +
while IFS= read -r web_file; do chmod 600 "$web_stage/$web_file"; done < "$web_temp/files"
chmod 700 "$web_stage/scripts/install.sh"
{
  printf '{"schemaVersion":"submission-installer.registration.v1","owner":"mac-submission-skills/web-installer","version":"%s","packageSha256":"%s","files":[' "$web_version" "$web_expected"
  web_separator=''
  while IFS= read -r web_file; do
    printf '%s{"path":"%s","sha256":"%s"}' "$web_separator" "$web_file" "$(web_sha "$web_stage/$web_file")"
    web_separator=','
  done < "$web_temp/files"
  printf ']}\n'
} > "$web_stage/$web_receipt"

web_reused=false
if [ -e "$web_target" ] && [ "$web_old_sha" = "$web_expected" ]; then
  while IFS= read -r web_file; do
    cmp -s "$web_target/$web_file" "$web_stage/$web_file" || web_fail WEB_INSTALL_PACKAGE_IDENTITY_CONFLICT
  done < "$web_temp/files"
  web_reused=true
else
  if [ -e "$web_target" ]; then
    web_backups="$web_codex/skill-backups"
    [ ! -L "$web_backups" ] || web_fail WEB_INSTALL_PATH_UNSAFE
    mkdir -p "$web_backups"
    web_backup=$(mktemp -d "$web_backups/submission-install.XXXXXXXX") || web_fail WEB_INSTALL_BACKUP_FAILED
    web_rollback="$web_backup/skill"
    mv "$web_target" "$web_rollback" || web_fail WEB_INSTALL_REGISTRATION_FAILED
  fi
  mv "$web_stage" "$web_target" || web_fail WEB_INSTALL_REGISTRATION_FAILED
  web_rollback=''
fi

printf '{"status":"installer_ready","repository_version":"%s","reused":%s}\n' "$web_version" "$web_reused"
if /bin/sh "$web_target/scripts/install.sh" "$@"; then
  exit 0
else
  web_exit=$?
  printf '{"status":"partially_installed","error_code":"WEB_INSTALL_SKILLS_FAILED","installer_registered":true,"exit_code":%s}\n' "$web_exit"
  exit "$web_exit"
fi
