#!/usr/bin/env bash
set -euo pipefail
umask 077

base_url="${GAMENAVIGATOR_SERVER:-}"
if [[ -z "$base_url" ]]; then
  base_url="https://gamenavigator.raycraftlab.com"
fi
base_url="${base_url%/}"
gn_address_policy="current"
gn_download_budget=900
os="$(uname -s | tr '[:upper:]' '[:lower:]')"
arch="$(uname -m)"
case "$os-$arch" in
  darwin-arm64) rid="osx-arm64" ;;
  darwin-x86_64) rid="osx-x64" ;;
  linux-x86_64) rid="linux-x64" ;;
  linux-aarch64) rid="linux-arm64" ;;
  *) echo "This installer supports macOS and Linux. On Windows use install.ps1." >&2; exit 1 ;;
esac

if [[ "$os" == "darwin" ]]; then
  data_root="${GAMENAVIGATOR_HOME:-$HOME/Library/Application Support/GameNavigator}"
else
  data_root="${GAMENAVIGATOR_HOME:-$HOME/.local/share/GameNavigator}"
fi
skill_root="$data_root/skill"
app_root="$data_root/app"
pack_root="$data_root/packs/current"
mkdir -p "$data_root/app" "$data_root/artifacts" "$pack_root"
[[ -O "$data_root" && -O "$data_root/app" && ! -L "$data_root" && ! -L "$data_root/app" ]] || {
  echo "The Navigator data and program directories must belong to this account and must not be links." >&2; exit 1;
}
# Upgrade legacy default-umask directories without changing any data or parent folder.
chmod 700 "$data_root" "$data_root/app"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT

install_key=""
install_key_file="$data_root/install-key.txt"
if [[ -f "$install_key_file" ]]; then
  install_key="$(tr -d '[:space:]' < "$install_key_file" | tr '[:upper:]' '[:lower:]')"
fi
if [[ ! "$install_key" =~ ^ins_[0-9a-f]{32}$ ]]; then
  install_key="ins_$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')"
  printf '%s\n' "$install_key" > "$install_key_file"
  chmod 600 "$install_key_file"
fi

shell_quote() {
  local quoted
  quoted=$(printf '%s' "$1" | sed "s/'/'\\\\''/g")
  printf "'%s'" "$quoted"
}

# Durable minimal records, replayed only by this script or a normal Navigator invocation.
gn_journey_operation="$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')"
gn_journey_stage=download
gn_journey_code=unknown
gn_journey_note() {
  local stage="$1" outcome="$2" code="$3" dir="$data_root/journey-outbox" id key="" rehearsal=false
  [[ -d "$data_root" && -O "$data_root" && ! -L "$data_root" && ! -L "$dir" ]] || return 0
  mkdir -p "$dir" 2>/dev/null || return 0
  chmod 700 "$dir" 2>/dev/null || return 0
  local n=0 f
  for f in "$dir"/*.json; do [[ -f "$f" ]] && n=$((n+1)); done
  [[ "$n" -lt 64 ]] || return 0
  id="$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')"
  [[ "${install_key:-}" =~ ^ins_[0-9a-f]{32}$ ]] && key="$install_key"
  [[ "${GAMENAVIGATOR_REHEARSAL:-}" == 1 ]] && rehearsal=true
  printf '{"event":{"eventId":"%s","product":"navigator","area":"install","operation":"%s","stage":"%s","outcome":"%s","code":"%s","version":"unknown","at":"%s","installKey":"%s","rehearsal":%s,"source":"client"},"attempts":0}\n' \
    "$id" "$gn_journey_operation" "$stage" "$outcome" "$code" "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$key" "$rehearsal" > "$dir/$id.new" 2>/dev/null && mv "$dir/$id.new" "$dir/$id.json" 2>/dev/null || true
}
gn_journey_flush() {
  local dir="$data_root/journey-outbox"
  [[ -d "$dir" && ! -L "$dir" ]] || return 0
  # JSON::PP is optional here; the installed runtime also drains this same queue.
  command -v perl >/dev/null 2>&1 || return 0
  nohup perl -MJSON::PP -MTime::Local=timegm -MFcntl=:DEFAULT -e '
    use strict; use warnings;
    my ($dir,$base)=@ARGV; exit unless $base =~ m{\Ahttps://} || $base =~ m{\Ahttp://(?:127\.0\.0\.1|localhost)(?::\d+)?\z};
    exit if -l $dir; my $lock="$dir/.flush.lock";
    if (-f $lock && !-l $lock) { open my $r,"<",$lock or exit; my $pid=<$r>;close $r; unlink $lock if defined($pid) && $pid =~ /\A\d+\z/ && !kill(0,$pid); }
    sysopen(my $guard,$lock,O_CREAT|O_EXCL|O_WRONLY,0600) or exit; print $guard $$;close $guard;
    eval {
      my $done=0;
      for my $file (sort glob "$dir/*.json") {
        last if $done>=4; next if -l $file || -s $file>4096;
        open my $in,"<",$file or next;local $/;my $row=eval {decode_json(<$in>)};close $in;next unless $row && ref($row->{event}) eq "HASH";
        if (($row->{attempts}//0)>=5) { unlink $file;next; }
        my $at=$row->{event}{at}//"";
        next unless $at =~ /\A(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|\+00:00)\z/;
        my $epoch=eval {timegm($6,$5,$4,$3,$2-1,$1)};next unless defined $epoch;
        if (time-$epoch>30*86400) { unlink $file;next; } next if $epoch-time>300;
        my $e=$row->{event};next unless ref($e->{rehearsal}) eq "JSON::PP::Boolean";next unless ($e->{eventId}//"") =~ /\A[a-f0-9]{32}\z/ && ($e->{operation}//"") =~ /\A(?:[a-f0-9]{32}|[a-f0-9]{64})\z/;
        next unless ($e->{product}//"") =~ /\A(?:navigator|play)\z/ && ($e->{area}//"") =~ /\A(?:install|runtime|pairing)\z/;
        next unless ($e->{stage}//"") =~ /\A(?:download|verify|extract|write|launch|run|claim|connect|confirm)\z/ && ($e->{outcome}//"") =~ /\A(?:observed|failed|cancelled|recovered|unknown)\z/;
        next unless ($e->{code}//"") =~ /\A(?:none|network|timeout|integrity|permission|invalid|expired|unavailable|rate-limited|unauthorized|mismatch|unexpected|incomplete|storage|not-confirmed|unknown)\z/;
        next unless ($e->{version}//"") =~ /\A(?:unknown|[0-9]+\.[0-9]+\.[0-9]+(?:-[a-z]+\.[0-9]+)?)\z/ && ($e->{installKey}//"") =~ /\A(?:|ins_[0-9a-f]{32})\z/ && ($e->{at}//"") =~ /\A[0-9TZ:.+\-]+\z/;
        my %payload=map {$_=>$e->{$_}} qw(eventId product area operation stage outcome code version at installKey rehearsal);$payload{source}="client";
        $row->{attempts}++;open my $out,">","$file.new" or next;print $out encode_json($row);close $out;rename "$file.new",$file or next;$done++;
        open my $curl,"-|","curl","--silent","--show-error","--max-time","2","--connect-timeout","2","--output","/dev/null","--write-out","%{http_code}","-A","curl/8.7.1","-H","Content-Type: application/json","--data-binary",encode_json(\%payload),"$base/api/journey-diagnostics" or next;
        my $status=<$curl>;close $curl;unlink $file if defined($status) && $status =~ /\A2[0-9]{2}\z/;
      }
    };unlink $lock;
  ' "$dir" "$base_url" >/dev/null 2>&1 &
}
gn_journey_exit() {
  local result=$?
  if [[ "$result" -ne 0 ]]; then
    if [[ "$result" -eq 130 ]]; then gn_journey_note "$gn_journey_stage" cancelled none
    elif [[ "$result" -ge 128 ]]; then gn_journey_note "$gn_journey_stage" unknown incomplete
    else gn_journey_note "$gn_journey_stage" failed "$gn_journey_code"; fi
  fi
  gn_journey_flush
  rm -rf "$tmp"
  trap - EXIT
  exit "$result"
}

report_onboarding() {
  local step="$1" outcome="$2" bytes="${3:-0}" size="${4:-0}" speed="${5:-0}" source="${6:-script}" cache="${7:-}" colo="${8:-}" progress="${9:-0}" network="${10:-unknown}" duration="${11:-0}"
  case "$network" in ipv4|ipv6) ;; *) network="unknown" ;; esac
  case "$cache" in hit|miss|expired|revalidated|updating|bypass|dynamic|none|unobserved) ;; *) cache="" ;; esac
  if [[ ! "$colo" =~ ^[A-Za-z]{3}$ ]]; then colo=""; else colo="$(printf '%s' "$colo" | tr '[:lower:]' '[:upper:]')"; fi
  if [[ "$speed" -lt 0 ]]; then speed=0; fi
  if [[ "$speed" -gt 1000000000 ]]; then speed=1000000000; fi
  if [[ ! "$duration" =~ ^[0-9]+$ ]] || [[ "$duration" -lt 0 ]]; then duration=0; fi
  if [[ "$duration" -gt 86400000 ]]; then duration=86400000; fi
  # Only the boolean leaves this machine. The variable's text is not a name and is not sent.
  local rehearsal=""
  if [[ "${GAMENAVIGATOR_REHEARSAL:-}" == "1" ]]; then rehearsal=',"rehearsal":true'; fi
  case "$step" in
    download-start|download-complete) gn_journey_stage=download; gn_journey_note download observed none ;;
    extract) gn_journey_stage=extract; gn_journey_note extract observed none ;;
    install) gn_journey_stage=write; gn_journey_note write recovered none ;;
  esac
  # The report must not hold the download. nohup keeps it alive after this script exits.
  nohup curl -fsS --max-time 8 --connect-timeout 5 -H 'Content-Type: application/json' \
    --data-binary "{\"product\":\"navigator\",\"step\":\"${step}\",\"outcome\":\"${outcome}\",\"version\":\"\",\"installKey\":\"${install_key}\",\"progressPct\":${progress},\"bytesReceived\":${bytes},\"sizeBytes\":${size},\"speedBytesPerSecond\":${speed},\"networkType\":\"${network}\",\"source\":\"${source}\",\"cacheStatus\":\"${cache}\",\"colo\":\"${colo}\",\"durationMs\":${duration}${rehearsal}}" \
    "$base_url/api/onboarding" >/dev/null 2>&1 &
}

trap gn_journey_exit EXIT
gn_journey_flush

gn_ipv6_hint() {
  [[ "$gn_address_policy" == "ipv6-first" && "$gn_last_network" == "ipv4" ]] || return 0
  local flag="$data_root/ipv6-hint.txt"
  [[ -f "$flag" ]] && return 0
  local lang="${LANG:-en}" encoded text
  case "$lang" in
    zh_TW*|zh_Hant*|zh-TW*) encoded="6YCZ5qyh5LiL6LyJ6LWw55qE5pivIElQdjTjgILlnKjot6/nlLHlmajmiJblhYnnupbmlbjmk5rmqZ/kuIrplovllZ8gSVB2Nu+8jOaIluWcqOmAmeasoeS4i+i8ieaZgumXnOmWieS7o+eQhuaIluWKoOmAn+WZqO+8jOmAmuW4uOacg+abtOW/q+OAgumAmeWJh+iqquaYjuWPquWHuuePvuS4gOasoeOAgg==" ;;
    zh*) encoded="6L+Z5qyh5LiL6L296LWw55qE5pivIElQdjTjgILlnKjot6/nlLHlmajmiJblhYnnjKvkuIrmiZPlvIAgSVB2Nu+8jOaIluWcqOi/measoeS4i+i9veaXtuWFs+aOieS7o+eQhuaIluWKoOmAn+WZqO+8jOmAmuW4uOS8muabtOW/q+OAgui/meadoeivtOaYjuWPquWHuueOsOS4gOasoeOAgg==" ;;
    ja*) encoded="44GT44Gu44OA44Km44Oz44Ot44O844OJ44GvIElQdjQg44KS5L2/44Gj44Gm44GE44G+44GZ44CC44Or44O844K/44O844G+44Gf44Gv5YWJ5Zue57ea57WC56uv6KOF572u44GnIElQdjYg44KS5pyJ5Yq544Gr44GZ44KL44GL44CB44GT44Gu44OA44Km44Oz44Ot44O844OJ44Gu6ZaT44Gv44OX44Ot44Kt44K344G+44Gf44Gv44Ki44Kv44K744Op44Os44O844K/44O844KS5YiH44KL44Go44CB6YCa5bi444Gv6YCf44GP44Gq44KK44G+44GZ44CC44GT44Gu5qGI5YaF44Gv5LiA5bqm44Gg44GR6KGo56S644GX44G+44GZ44CC" ;;
    ko*) encoded="7J2067KIIOuLpOyatOuhnOuTnOuKlCBJUHY066W8IOyCrOyaqe2VmOqzoCDsnojsirXri4jri6QuIOqzteycoOq4sOuCmCDqtJHrqqjrjoDsl5DshJwgSVB2NuulvCDsvJzqsbDrgpgsIOydtOuyiCDri6TsmrTroZzrk5wg64+Z7JWIIO2UhOuhneyLnOuCmCDqsIDsho3quLDrpbwg64GE66m0IOuztO2GtSDrjZQg67mo65287KeR64uI64ukLiDsnbQg7JWI64K064qUIO2VnCDrsojrp4wg7ZGc7Iuc65Cp64uI64ukLg==" ;;
    de*) encoded="RGllc2VyIERvd25sb2FkIHZlcndlbmRldCBJUHY0LiBJUHY2IGFtIFJvdXRlciBvZGVyIGFtIEdsYXNmYXNlcm1vZGVtIGVpbnp1c2NoYWx0ZW4sIG9kZXIgZWluZW4gUHJveHkgb2RlciBCZXNjaGxldW5pZ2VyIGbDvHIgZGllc2VuIERvd25sb2FkIGF1c3p1c2NoYWx0ZW4sIG1hY2h0IGlobiBnZXfDtmhubGljaCBzY2huZWxsZXIuIERpZXNlciBIaW53ZWlzIGVyc2NoZWludCBudXIgZWlubWFsLg==" ;;
    fr*) encoded="Q2UgdMOpbMOpY2hhcmdlbWVudCB1dGlsaXNlIElQdjQuIEFjdGl2ZXIgSVB2NiBzdXIgbGUgcm91dGV1ciBvdSBsZSBtb2RlbSBmaWJyZSwgb3UgZMOpc2FjdGl2ZXIgbGUgcHJveHkgb3UgbOKAmWFjY8OpbMOpcmF0ZXVyIHBvdXIgY2UgdMOpbMOpY2hhcmdlbWVudCwgbGUgcmVuZCBlbiBnw6luw6lyYWwgcGx1cyByYXBpZGUuIENldCBhdmlzIG7igJlhcHBhcmHDrnQgcXXigJl1bmUgZm9pcy4=" ;;
    *) encoded="VGhpcyBkb3dubG9hZCBpcyB1c2luZyBJUHY0LiBUdXJuaW5nIG9uIElQdjYgb24gdGhlIHJvdXRlciBvciBvcHRpY2FsIG1vZGVtLCBvciB0dXJuaW5nIG9mZiBhIHByb3h5IG9yIGFjY2VsZXJhdG9yIGZvciB0aGlzIGRvd25sb2FkLCB1c3VhbGx5IG1ha2VzIGl0IGZhc3Rlci4gVGhpcyBub3RlIGlzIHNob3duIG9uY2Uu" ;;
  esac
  if ! text="$(printf '%s' "$encoded" | base64 -d 2>/dev/null)"; then text="$(printf '%s' "$encoded" | base64 -D 2>/dev/null || true)"; fi
  [[ -n "$text" ]] || return 0
  # A pipe or a hidden run never shows the note, so it must not count as shown.
  [[ -t 1 ]] || return 0
  printf '%s\n' "$text"
  printf 'once\n' > "$flag"
  report_onboarding ipv6-hint ok 0 0 0 script "" "" 0 ipv4
}

gn_last_cache=""
gn_last_colo=""
gn_last_network="unknown"
gn_last_speed=0
gn_download_deadline=0
gn_budget_armed=0
gn_force_family=""

# SECONDS is the shell's monotonic counter. A new package is the only place
# that arms the budget. An expired window is not armed again.
gn_arm_package_budget() {
  gn_download_deadline=$((SECONDS + gn_download_budget))
  gn_budget_armed=1
  gn_force_family=""
}

gn_begin_package_budget() {
  if [[ "$gn_budget_armed" -ne 1 ]]; then
    return 0
  fi
}

gn_pin_retry_family() {
  # ipv6-first (domestic) retries try IPv4 first, then IPv6, on the time left.
  # Any other policy, including overseas, keeps its existing order.
  if [[ "$gn_address_policy" == "ipv6-first" ]]; then gn_force_family="retry"
  else gn_force_family=""; fi
}

gn_set_speed() {
  local bytes="$1" elapsed=0
  if [[ "$gn_budget_armed" -eq 1 ]]; then elapsed=$(( SECONDS - (gn_download_deadline - gn_download_budget) )); fi
  [[ "$elapsed" -lt 1 ]] && elapsed=1
  gn_last_speed=$(( bytes / elapsed ))
  if [[ "$gn_last_speed" -gt 1000000000 ]]; then gn_last_speed=1000000000; fi
}

gn_elapsed_ms() {
  local elapsed=0
  if [[ "$gn_budget_armed" -eq 1 ]]; then elapsed=$(( (SECONDS - (gn_download_deadline - gn_download_budget)) * 1000 )); fi
  [[ "$elapsed" -lt 0 ]] && elapsed=0
  [[ "$elapsed" -gt 86400000 ]] && elapsed=86400000
  printf '%s' "$elapsed"
}

gn_budget_left() {
  if [[ "$gn_budget_armed" -ne 1 ]]; then
    printf '0'
    return
  fi
  local left=$(( gn_download_deadline - SECONDS ))
  if [[ "$left" -lt 0 ]]; then left=0; fi
  printf '%s' "$left"
}

gn_stop_for_budget() {
  local quiet="$1" have="$2" total="$3" source="$4"
  if [[ -z "$quiet" ]]; then
    report_onboarding download-stalled stalled "$have" "$([[ "$total" -ge 0 ]] && echo "$total" || echo 0)" "$gn_last_speed" "$source" "$gn_last_cache" "$gn_last_colo" 0 "$gn_last_network" "$(gn_elapsed_ms)"
  fi
  return 1
}

# 4 MiB ranges. A stall is no bytes for 30 seconds. curl -fsSL follows the alias redirect.
fetch_download() {
  local url="$1" output="$2" source="${3:-cdn}" quiet="${4:-}"
  local chunk=4194304 header="$output.headers" part="$output.part" total=-1 have=0 code got seen family attempt progress=0 left wait
  local gn_address_family="${gn_force_family-}" families attempts
  local cache="" colo=""
  gn_last_cache=""
  gn_last_colo=""
  gn_last_network="unknown"
  gn_last_speed=0
  # Sources and address families share the package deadline. A fetch must not
  # start a new window after a slow edge already used part of it.
  gn_begin_package_budget
  if [[ -f "$output" ]]; then have=$(wc -c < "$output" | tr -d ' '); fi
  while true; do
    if [[ "$total" -ge 0 && "$have" -eq "$total" ]]; then
      gn_set_speed "$have"
      return 0
    fi
    if [[ "$total" -ge 0 && "$have" -gt "$total" ]]; then rm -f "$output"; have=0; fi
    if [[ "$(gn_budget_left)" -le 0 ]]; then
      if [[ -z "$quiet" ]]; then
        report_onboarding download-stalled stalled "$have" "$([[ "$total" -ge 0 ]] && echo "$total" || echo 0)" "$gn_last_speed" "$source" "$gn_last_cache" "$gn_last_colo" 0 "$gn_last_network" "$(gn_elapsed_ms)"
      fi
      return 1
    fi
    local end=$((have + chunk - 1))
    if [[ "$total" -ge 0 && "$end" -ge "$total" ]]; then end=$((total - 1)); fi
    progress=0
    if [[ "$gn_address_family" == "retry" ]]; then families="-4 -6"; attempts=1
    elif [[ "$gn_address_policy" == "ipv6-first" && -z "$gn_address_family" ]]; then families="-6 -4"; attempts=1
    elif [[ "$gn_address_policy" == "ipv6-first" && "$gn_address_family" == "-4" ]]; then families="-4"; attempts=4
    elif [[ "$gn_address_policy" == "ipv6-first" && "$gn_address_family" == "-6" ]]; then families="-6 -4"; attempts=4
    elif [[ -n "$gn_address_family" ]]; then families="$gn_address_family"; attempts=4; else families="-4 -6"; attempts=1; fi
    for family in $families; do
      attempt=0
      family_attempts="$attempts"
      if [[ "$gn_address_policy" == "ipv6-first" && "$family" == "-4" && "$gn_address_family" != "-4" ]]; then family_attempts=1; fi
      while [[ "$attempt" -lt "$family_attempts" ]]; do
        left="$(gn_budget_left)"
        if [[ "$left" -le 0 ]]; then gn_stop_for_budget "$quiet" "$have" "$total" "$source" || return 1; fi
        if [[ "$attempt" -gt 0 ]]; then
          wait=$((1 << attempt))
          if [[ "$wait" -gt "$left" ]]; then wait="$left"; fi
          if [[ "$wait" -gt 0 ]]; then sleep "$wait"; fi
          left="$(gn_budget_left)"
          if [[ "$left" -le 0 ]]; then gn_stop_for_budget "$quiet" "$have" "$total" "$source" || return 1; fi
        fi
        attempt=$((attempt + 1))
        rm -f "$part" "$header"
        code=$(curl -fsSL --retry 0 --connect-timeout 15 --speed-limit 1 --speed-time 30 \
          --max-time "$left" \
          "$family" --range "${have}-${end}" -D "$header" -o "$part" -w '%{http_code}' "$url" || true)
        [[ -f "$part" ]] || continue
        got=$(wc -c < "$part" | tr -d ' ')
        # HTTP/2 writes lowercase names, and macOS/Linux awk has no IGNORECASE.
        # Keep the last header block so the redirect does not hide the object.
        parsed="$(awk '
          BEGIN { cache=""; colo=""; total="" }
          {
            gsub(/\r/, "")
            key = tolower($1)
            if (key == "cf-cache-status:") cache = tolower($2)
            else if (key == "cf-ray:") {
              if (match($2, /-[A-Za-z][A-Za-z][A-Za-z]$/)) colo = toupper(substr($2, RSTART + 1, 3))
            } else if (key == "content-range:") {
              line = tolower($0)
              if (match(line, /\/[0-9]+$/)) total = substr(line, RSTART + 1, RLENGTH - 1)
            }
          }
          END { printf "%s\t%s\t%s\n", cache, colo, total }
        ' "$header" 2>/dev/null || printf '\t\t\n')"
        cache=""; colo=""; seen=""
        if [[ "$parsed" == *$'\t'*$'\t'* ]]; then
          cache="${parsed%%$'\t'*}"
          rest="${parsed#*$'\t'}"
          colo="${rest%%$'\t'*}"
          seen="${rest#*$'\t'}"
          seen="${seen//$'\n'/}"
          seen="${seen//$'\r'/}"
        fi
        if [[ -n "$cache" || -n "$colo" ]]; then
          gn_last_cache="$cache"
          gn_last_colo="$colo"
        fi
        if [[ "$family" == "-4" ]]; then gn_last_network="ipv4"; else gn_last_network="ipv6"; fi
        if [[ "$gn_last_network" == "ipv4" ]]; then gn_ipv6_hint; fi
        if [[ "$have" -eq 0 && "$code" == "200" ]]; then
          if [[ "$gn_address_family" == "retry" ]]; then gn_address_family="$family"
          elif [[ "$gn_address_policy" == "ipv6-first" && "$family" == "-4" ]]; then gn_address_family="-4"
          elif [[ -z "$gn_address_family" ]]; then gn_address_family="$family"; fi
          mv "$part" "$output"
          if [[ -z "$quiet" ]]; then
            local full
            full="$(wc -c < "$output" | tr -d ' ')"
            gn_set_speed "$full"
            report_onboarding download-start start 0 "$full" "$gn_last_speed" "$source" "$cache" "$colo" 0 "$gn_last_network" "$(gn_elapsed_ms)"
          fi
          rm -f "$header"
          return 0
        fi
        [[ "$code" == "206" ]] || continue
        [[ -n "$seen" ]] || continue
        if [[ "$total" -lt 0 ]]; then
          total=$seen
          if [[ -z "$quiet" ]]; then report_onboarding download-start start "$have" "$total" 0 "$source" "$cache" "$colo" 0 "$gn_last_network" "$(gn_elapsed_ms)"; fi
        fi
        [[ "$total" -eq "$seen" ]] || continue
        local last=$((have + chunk - 1))
        if [[ "$last" -ge "$total" ]]; then last=$((total - 1)); fi
        [[ "$got" -eq $((last - have + 1)) ]] || continue
        if [[ "$have" -eq 0 ]]; then mv "$part" "$output"; else cat "$part" >> "$output"; rm -f "$part"; fi
        have=$(wc -c < "$output" | tr -d ' ')
        local pct=$((have * 100 / total))
        local mark
        for mark in 25 50 75 100; do
          if [[ "$pct" -ge "$mark" && ! -f "$output.mark$mark" ]]; then
            : > "$output.mark$mark"
            if [[ -z "$quiet" ]]; then
              gn_set_speed "$have"
              report_onboarding download-progress progress "$have" "$total" "$gn_last_speed" "$source" "$cache" "$colo" "$mark" "$gn_last_network" "$(gn_elapsed_ms)"
            fi
          fi
        done
        if [[ "$gn_address_family" == "retry" ]]; then gn_address_family="$family"
        elif [[ "$gn_address_policy" == "ipv6-first" && "$family" == "-4" ]]; then gn_address_family="-4"
        elif [[ -z "$gn_address_family" ]]; then gn_address_family="$family"; fi
        progress=1
        break
      done
      [[ "$progress" -eq 1 ]] && break
    done
    if [[ "$progress" -ne 1 ]]; then
      if [[ -z "$quiet" ]]; then
        gn_set_speed "$have"
        report_onboarding download-stalled stalled "$have" "$([[ "$total" -ge 0 ]] && echo "$total" || echo 0)" "$gn_last_speed" "$source" "$gn_last_cache" "$gn_last_colo" 0 "$gn_last_network" "$(gn_elapsed_ms)"
      fi
      rm -f "$part" "$header"
      return 28
    fi
  done
}

# Beta warns. Stable, or this switch, rejects a missing list, a 404, and an
# unsigned list. The switch cannot turn the stable rule off. A bad signature
# or an older list still stops on either channel.
gn_release_channel="beta"
gn_require_release_signature=0
[[ "${GN_REQUIRE_RELEASE_SIGNATURE:-}" == "1" ]] && gn_require_release_signature=1

gn_signature_required() {
  [[ "$gn_release_channel" == "stable" || "$gn_require_release_signature" -eq 1 ]]
}

gn_manifest_is_stable() {
  local manifest="$1"
  [[ -f "$manifest" ]] && grep -Eq '"channel"[[:space:]]*:[[:space:]]*"stable"' "$manifest"
}

gn_status_line() {
  local kind="$1" lang="${LANG:-en}" key
  case "$lang" in
    zh_TW*|zh_Hant*|zh-TW*|zh_HK*|zh-HK*|zh_MO*|zh-MO*) key="zh-TW" ;;
    zh*) key="zh-CN" ;;
    ja*) key="ja" ;;
    ko*) key="ko" ;;
    de*) key="de" ;;
    fr*) key="fr" ;;
    *) key="en" ;;
  esac
  case "$kind:$key" in
    skill:zh-CN) printf '%s\n' "正在下载游戏领航师技能包。" ;;
    skill:zh-TW) printf '%s\n' "正在下載遊戲領航師技能包。" ;;
    skill:en) printf '%s\n' "Downloading the Game Navigator skill package." ;;
    skill:ja) printf '%s\n' "ゲームナビゲーターのスキルをダウンロードしています。" ;;
    skill:ko) printf '%s\n' "게임 내비게이터 스킬을 다운로드하는 중입니다." ;;
    skill:de) printf '%s\n' "Das Game-Navigator-Skillpaket wird heruntergeladen." ;;
    skill:fr) printf '%s\n' "Téléchargement du paquet de compétence Game Navigator." ;;
    catalog:zh-CN) printf '%s\n' "正在下载游戏领航师基础目录。" ;;
    catalog:zh-TW) printf '%s\n' "正在下載遊戲領航師基礎目錄。" ;;
    catalog:en) printf '%s\n' "Downloading the Game Navigator base catalog." ;;
    catalog:ja) printf '%s\n' "ゲームナビゲーターの基本カタログをダウンロードしています。" ;;
    catalog:ko) printf '%s\n' "게임 내비게이터 기본 목록을 다운로드하는 중입니다." ;;
    catalog:de) printf '%s\n' "Der Game-Navigator-Grundkatalog wird heruntergeladen." ;;
    catalog:fr) printf '%s\n' "Téléchargement du catalogue de base Game Navigator." ;;
    installed:zh-CN) printf '%s\n' "游戏领航师已安装并校验。" ;;
    installed:zh-TW) printf '%s\n' "遊戲領航師已安裝並校驗。" ;;
    installed:en) printf '%s\n' "Game Navigator is installed and verified." ;;
    installed:ja) printf '%s\n' "ゲームナビゲーターをインストールし、検証しました。" ;;
    installed:ko) printf '%s\n' "게임 내비게이터를 설치하고 검증했습니다." ;;
    installed:de) printf '%s\n' "Game Navigator ist installiert und geprüft." ;;
    installed:fr) printf '%s\n' "Game Navigator est installé et vérifié." ;;
  esac
}

gn_completion_notice() {
  local lang="${LANG:-en}" key
  case "$lang" in
    zh_TW*|zh_Hant*|zh-TW*|zh_HK*|zh-HK*|zh_MO*|zh-MO*) key="zh-TW" ;;
    zh*) key="zh-CN" ;;
    ja*) key="ja" ;;
    ko*) key="ko" ;;
    de*) key="de" ;;
    fr*) key="fr" ;;
    *) key="en" ;;
  esac
  case "$key" in
    zh-CN) printf '%s\n' "安装好了。请留在这次对话里完成一次性登录。请沿用下面已经打印的链接，不要再次运行 login --begin。下面没有链接时，才运行 $quoted journey；只有结果仍要登录时，才运行一次 $quoted login --begin --open --pretty。如果网站已经登录，打开安全链接后确认，刚才发起的游戏领航师登录将使用当前网站账号，不必再登录一次；还没登录就在该页登录。如果这边没有打开浏览器，用你自己的手机或电脑打开这个链接就行，这不是登录失败。确认之后回到刚才的对话，页面不会自动跳回来。收到链接后立刻执行 login --wait --id，不要等玩家回来报告完成。等待中沿用同一次登录；只有过期或找不到时才重新开始一次。状态是 upgrade-required 时，先更新游戏领航师再重新开始一次，不要读取或转抄会话令牌，也不要改用无密钥领取。网络错误和登录失败要与过期分开。打不开浏览器不是登录失败：请在你自己的手机或电脑上打开这个 https 链接。网站登录只在打开链接的那个浏览器里。默认等待约 180 秒、最长 300 秒，和链接 15 分钟过期不是一回事。你说已经授权，或程序重启后本机密钥还在，就继续同一次登录。成功页只是请你回到刚才的对话，不会自动跳回，也不要复制令牌。成功后继续原来的旅程。如果这个助手不能自己醒来，下一轮仍等待同一次登录，不要承诺它会自动继续。安装器若在 NEXT 之前停下，最多再运行一次；第二次仍停下，就把情况告诉玩家。" ;;
    zh-TW) printf '%s\n' "安裝好了。請留在這次對話裡完成一次性登入。請沿用下面已經印出的連結，不要再次執行 login --begin。下面沒有連結時，才執行 $quoted journey；只有結果仍要登入時，才執行一次 $quoted login --begin --open --pretty。如果網站已經登入，打開安全連結後確認，剛才發起的遊戲領航師登入將使用當前網站帳號，不必再登入一次；還沒登入就在該頁登入。如果這邊沒有打開瀏覽器，用你自己的手機或電腦打開這個連結就行，這不是登入失敗。確認之後回到剛才的對話，頁面不會自動跳回來。收到連結後立刻執行 login --wait --id，不要等玩家回來報告完成。等待中沿用同一次登入；只有過期或找不到時才重新開始一次。狀態是 upgrade-required 時，先更新遊戲領航師再重新開始一次，不要讀取或轉抄會話令牌，也不要改用無金鑰領取。網路錯誤和登入失敗要與過期分開。打不開瀏覽器不是登入失敗：請在你自己的手機或電腦上打開這個 https 連結。網站登入只在打開連結的那個瀏覽器裡。預設等待約 180 秒、最長 300 秒，和連結 15 分鐘過期不是一回事。你說已經授權，或程式重啟後本機金鑰還在，就繼續同一次登入。成功頁只是請你回到剛才的對話，不會自動跳回，也不要複製會話令牌。成功後繼續原來的旅程。如果這個助手不能自己醒來，下一輪仍等待同一次登入，不要承諾它會自動繼續。安裝器若在 NEXT 之前停下，最多再執行一次；第二次仍停下，就把情況告訴玩家。" ;;
    ja) printf '%s\n' "インストールできました。この会話のまま、一度だけのログインを終えてください。下に出たリンクをそのまま使ってください。そのリンクがあるときは login --begin を再実行しないでください。リンクが無いときだけ $quoted journey を実行します。結果がまだログインを求めるときだけ、$quoted login --begin --open --pretty を一度実行してください。サイトにログイン済みなら、リンクを開いて確認すると、先ほど始めたゲームナビゲーターのログインが今のアカウントを使います。未ログインならそのページでログインします。リンクを出したらすぐに login --wait --id を実行し、完了の報告を待たないでください。pending は同じログインを待ちます。期限切れか見つからないときだけ一度やり直します。upgrade-required のときはゲームナビゲーターを更新してから一度やり直します。セッショントークンを読んだり転記したりせず、鍵なしでは受け取らないでください。ネットワークエラーは期限切れと分けてください。ブラウザが開かなくてもログイン失敗ではありません。ご自身のスマホかパソコンでこの https リンクを開いてください。サイトのログインはそのリンクを開いたブラウザにだけあります。既定の待ちは約180秒、最長300秒で、リンクの15分の期限とは別です。承認したと言うとき、または再起動後も手元の鍵が残っているときは、同じログインを続けます。成功ページは先ほどの会話へ戻る案内であり、自動では戻りません。トークンはコピーしないでください。成功後は元の手順を続けます。この助手が自分で再開できない場合、次のターンも同じログインを待ち、自動で起きると約束しないでください。インストーラが NEXT の前に止まったときは、もう一度だけ実行してください。その再実行も止まったら、起きたことをプレイヤーに伝えてください。" ;;
    ko) printf '%s\n' "설치되었습니다. 이 대화에서 일회용 로그인을 마치세요. 아래에 이미 출력된 링크를 그대로 사용하세요. 그 링크가 있으면 login --begin 을 다시 실행하지 마세요. 링크가 없을 때만 $quoted journey 를 실행합니다. 결과가 아직 로그인을 요구할 때만 $quoted login --begin --open --pretty 를 한 번 실행하세요. 웹사이트에 이미 로그인되어 있으면 링크를 열고 확인하면, 방금 시작한 게임 내비게이터 로그인이 현재 계정을 사용합니다. 아니면 그 페이지에서 로그인합니다. 링크를 보여 준 즉시 login --wait --id 를 실행하고, 완료했다고 돌아오기를 기다리지 마세요. pending 은 같은 로그인을 기다립니다. 만료되었거나 찾을 수 없을 때만 한 번 다시 시작합니다. upgrade-required 이면 게임 내비게이터를 업데이트한 뒤 한 번 다시 시작합니다. 세션 토큰을 읽거나 옮겨 적지 말고, 키 없이 받지 마세요. 네트워크 오류는 만료와 구분하세요. 브라우저가 열리지 않아도 로그인 실패가 아닙니다. 본인 휴대폰이나 컴퓨터에서 이 https 링크를 여세요. 웹사이트 로그인은 그 링크를 연 브라우저에만 있습니다. 기본 대기는 약 180초, 최대 300초이며 링크의 15분 만료와는 다릅니다. 이미 허용했다고 말하거나, 프로그램이 다시 시작된 뒤에도 이 기기의 키가 남아 있으면 같은 로그인을 계속합니다. 성공 페이지는 방금 대화로 돌아가라는 안내이며 자동으로 돌아가지 않습니다. 토큰을 복사하지 마세요. 성공하면 원래 여정을 계속합니다. 이 도우미가 스스로 깨어날 수 없으면 다음 차례에도 같은 로그인을 기다리고, 자동으로 이어진다고 약속하지 마세요. 설치기가 NEXT 전에 멈추면 한 번만 다시 실행하세요. 그 재시도도 멈추면 일어난 일을 플레이어에게 알리세요." ;;
    de) printf '%s\n' "Installation abgeschlossen. Bleib in diesem Gespräch und schließe die einmalige Anmeldung ab. Verwende den unten bereits ausgegebenen Link. Führe login --begin nicht erneut aus, wenn dieser Link vorhanden ist. Nur ohne Link: $quoted journey. Nur wenn das Ergebnis weiterhin eine Anmeldung verlangt, einmal $quoted login --begin --open --pretty. Wenn die Website schon angemeldet ist, öffne den Link und bestätige, dass die gerade gestartete Game-Navigator-Anmeldung dieses Konto verwendet. Sonst melde dich auf dieser Seite an. Starte sofort login --wait --id und warte nicht auf eine Fertigmeldung. pending verwendet dieselbe Anmeldung. Nur bei Ablauf oder fehlender Anmeldung einmal neu beginnen. Bei upgrade-required zuerst Game Navigator aktualisieren und dann einmal neu beginnen. Ein Sitzungstoken nicht lesen oder weitergeben und die Anmeldung nicht ohne den Warteschlüssel abholen. Ein Netzwerkfehler ist kein Ablauf. Wenn kein Browser aufgeht, ist das keine fehlgeschlagene Anmeldung: öffne den https-Link auf deinem eigenen Telefon oder Computer. Die Website-Anmeldung gilt nur in dem Browser, der den Link öffnet. Das Warten dauert standardmäßig etwa 180 Sekunden und höchstens 300. Das ist nicht das 15-Minuten-Ablaufdatum des Links. Sagst du, dass du es erlaubt hast, oder startet das Programm neu und der lokale Schlüssel ist noch da, bleibt es dieselbe Anmeldung. Die Erfolgsseite weist nur zurück in diesen Chat. Sie springt nicht selbst zurück, und du kopierst kein Token. Nach Erfolg die ursprüngliche Reise fortsetzen. Wenn dieser Assistent sich nicht selbst weckt, wartet die nächste Runde auf dieselbe Anmeldung. Versprich kein automatisches Aufwachen. Stoppt der Installer vor NEXT, führe ihn höchstens einmal erneut aus. Stoppt auch dieser Versuch, sag dem Spieler, was geschehen ist." ;;
    fr) printf '%s\n' "Installation terminée. Restez dans cette conversation et finissez la connexion unique. Utilisez le lien https déjà imprimé plus bas. Ne relancez pas login --begin quand ce lien est présent. Sans lien, lancez $quoted journey. Seulement si le résultat demande encore une connexion, lancez une fois $quoted login --begin --open --pretty. Si le site est déjà connecté, ouvrez le lien et confirmez pour que la connexion Game Navigator que vous venez de commencer utilise ce compte. Sinon, connectez-vous sur cette page. Si aucun navigateur ne s’ouvre ici, ouvrez le lien sur votre propre téléphone ou ordinateur. Ce n’est pas un échec. Après la confirmation, revenez à cette conversation. La page n’y revient pas toute seule. Lancez tout de suite login --wait --id et n’attendez pas que le joueur annonce la fin. pending réutilise la même connexion. Ne recommencez qu’une fois si elle est expirée ou introuvable. Pour upgrade-required, mettez à jour Game Navigator puis recommencez une fois. Ne lisez ni ne recopiez de jeton de session, et ne récupérez pas la connexion sans le secret d’attente. Une erreur réseau n’est pas une expiration. Si aucun navigateur ne s’ouvre, ce n’est pas un échec : ouvrez le lien https sur votre propre téléphone ou ordinateur. La connexion au site n’existe que dans le navigateur qui ouvre le lien. Une attente d’environ 180 secondes, 300 au plus, n’est pas l’expiration du lien au bout de 15 minutes. Si vous dites que c’est autorisé, ou si le programme redémarre alors que sa clé locale est encore là, continuez la même connexion. La page de succès demande seulement de revenir à cette conversation. Elle n’y saute pas, et ne copiez pas de jeton. Après le succès, continuez le parcours d’origine. Si cet assistant ne peut pas se réveiller seul, le tour suivant attend la même connexion. Ne promettez pas un réveil automatique. Si l’installateur s’arrête avant NEXT, relancez-le une seule fois. Si cette nouvelle tentative s’arrête aussi, dites au joueur ce qui s’est passé." ;;
    *) printf '%s\n' "Installed. Stay in this conversation and finish the one-time sign-in. Use the https link already printed below. Do not run login --begin again when that link is present. If no link was printed, run $quoted journey. Only when that result still needs sign-in, run $quoted login --begin --open --pretty once. If the website is already signed in, open the link and confirm to use that account for the Game Navigator sign-in you just started. Otherwise sign in on that page. As soon as the link is shown, run login --wait --id. Do not wait for the player to report completion. A pending result reuses the same sign-in. Begin again only when it is expired or missing. On upgrade-required, update Game Navigator and begin once more. Do not read or copy a session token, and do not claim the sign-in without the wait secret. A network error is not expiry. If no browser opens, that is not a failed sign-in: open the https link on your own phone or computer. The website sign-in exists only in the browser that opens the link. A wait of about 180 seconds, or 300 at most, is not the link's 15-minute expiry. If you say it is authorized, or the program restarts while its local key remains, continue the same sign-in. The success page only points back to this chat. It does not jump back, and do not copy a token. After success, continue the original journey. If this assistant cannot wake itself, the next turn waits on the same sign-in. Do not promise that it will resume by itself. browserOpened false is not a failed sign-in. The player opens the https link on their own phone or computer. A wait of 180 seconds, or 300 at most, is not the 15-minute expiry. If the player says it is authorized, or the program restarts and the local key remains, continue the same sign-in. The success page only points back to this chat. It does not jump back and is not a token to copy. If the installer stops before NEXT, run it once more. If that retry also stops, tell the player what happened." ;;
  esac
}
gn_release_judged=0
gn_release_signed=0
gn_release_status=""
gn_release_reason=""
gn_release_version=""
gn_release_sequence=0
gn_release_remember=0
gn_release_manifest_path=""

gn_release_public_pem() {
  cat <<'PEM'
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEHdT6jh64BJY3OR/HAcZqSefBA8d4
idCPOpzN9D7rh1ZvwKb4ivwbDF+dIQzG/FTrwyZKxrpWokpy0RKDoAnLPw==
-----END PUBLIC KEY-----
PEM
}

gn_release_sentence() {
  local reason="$1" lang="${LANG:-en}" key
  case "$lang" in
    zh_TW*|zh_Hant*|zh-TW*|zh_HK*|zh-HK*|zh_MO*|zh-MO*) key="zh-TW" ;;
    zh*) key="zh-CN" ;;
    ja*) key="ja" ;;
    ko*) key="ko" ;;
    de*) key="de" ;;
    fr*) key="fr" ;;
    *) key="en" ;;
  esac
  case "$reason" in
    rollback-version|rollback-sequence) reason="rollback" ;;
    bad-manifest|bad-signature) reason="bad-signature" ;;
  esac
  case "$reason:$key" in
    rollback:zh-CN) printf '%s\n' "这份发布清单比这台电脑上已有的版本更旧，下载已停止。" ;;
    rollback:zh-TW) printf '%s\n' "這份發布清單比這台電腦上已有的版本更舊，下載已停止。" ;;
    rollback:en) printf '%s\n' "This release list is older than the copy on this computer. The download has stopped." ;;
    rollback:ja) printf '%s\n' "この公開一覧は、このパソコンにある版より古いため、ダウンロードを止めました。" ;;
    rollback:ko) printf '%s\n' "이 배포 목록은 이 컴퓨터에 있는 버전보다 오래되어 다운로드를 멈췄습니다." ;;
    rollback:de) printf '%s\n' "Diese Veröffentlichungsliste ist älter als die Fassung auf diesem Computer. Der Download wurde gestoppt." ;;
    rollback:fr) printf '%s\n' "Cette liste de publication est plus ancienne que la copie de cet ordinateur. Le téléchargement s’est arrêté." ;;
    unsigned:zh-CN) printf '%s\n' "这次发布清单还没有签名。下载会继续。签名核对尚未强制。" ;;
    unsigned:zh-TW) printf '%s\n' "這次發布清單還沒有簽名。下載會繼續。簽名核對尚未強制。" ;;
    unsigned:en) printf '%s\n' "This release list has no signature yet. The download continues. A signature is not required yet." ;;
    unsigned:ja) printf '%s\n' "この公開一覧にはまだ署名がありません。ダウンロードは続きます。署名の確認はまだ必須ではありません。" ;;
    unsigned:ko) printf '%s\n' "이번 배포 목록에는 아직 서명이 없습니다. 다운로드는 계속됩니다. 서명 확인은 아직 필수가 아닙니다." ;;
    unsigned:de) printf '%s\n' "Diese Veröffentlichungsliste hat noch keine Signatur. Der Download geht weiter. Eine Signatur ist noch nicht erforderlich." ;;
    unsigned:fr) printf '%s\n' "Cette liste de publication n’a pas encore de signature. Le téléchargement continue. Une signature n’est pas encore exigée." ;;
    signature-required:zh-CN) printf '%s\n' "这次发布清单没有签名，下载已停止。" ;;
    signature-required:zh-TW) printf '%s\n' "這次發布清單沒有簽名，下載已停止。" ;;
    signature-required:en) printf '%s\n' "This release list has no signature. The download has stopped." ;;
    signature-required:ja) printf '%s\n' "この公開一覧には署名がないため、ダウンロードを止めました。" ;;
    signature-required:ko) printf '%s\n' "이번 배포 목록에 서명이 없어 다운로드를 멈췄습니다." ;;
    signature-required:de) printf '%s\n' "Diese Veröffentlichungsliste hat keine Signatur. Der Download wurde gestoppt." ;;
    signature-required:fr) printf '%s\n' "Cette liste de publication n’a pas de signature. Le téléchargement s’est arrêté." ;;
    *)
      case "$key" in
        zh-CN) printf '%s\n' "这次发布清单的签名对不上，下载已停止。" ;;
        zh-TW) printf '%s\n' "這次發布清單的簽名對不上，下載已停止。" ;;
        ja) printf '%s\n' "この公開一覧の署名が一致しないため、ダウンロードを止めました。" ;;
        ko) printf '%s\n' "이번 배포 목록의 서명이 맞지 않아 다운로드를 멈췄습니다." ;;
        de) printf '%s\n' "Die Signatur dieser Veröffentlichungsliste stimmt nicht. Der Download wurde gestoppt." ;;
        fr) printf '%s\n' "La signature de cette liste de publication ne correspond pas. Le téléchargement s’est arrêté." ;;
        *) printf '%s\n' "This release list signature does not match. The download has stopped." ;;
      esac
      ;;
  esac
}

gn_version_tuple() {
  local value="${1%%+*}"
  gn_vt_major=0
  gn_vt_minor=0
  gn_vt_patch=0
  gn_vt_beta=-1
  [[ "$value" =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)(-beta\.([0-9]+))?$ ]] || return 1
  gn_vt_major=$((10#${BASH_REMATCH[1]}))
  gn_vt_minor=$((10#${BASH_REMATCH[2]}))
  gn_vt_patch=$((10#${BASH_REMATCH[3]}))
  if [[ -n "${BASH_REMATCH[5]:-}" ]]; then gn_vt_beta=$((10#${BASH_REMATCH[5]})); fi
}

gn_version_is_older() {
  local c_major c_minor c_patch c_beta i_major i_minor i_patch i_beta
  gn_version_tuple "$1" || return 1
  c_major=$gn_vt_major; c_minor=$gn_vt_minor; c_patch=$gn_vt_patch; c_beta=$gn_vt_beta
  gn_version_tuple "$2" || return 1
  i_major=$gn_vt_major; i_minor=$gn_vt_minor; i_patch=$gn_vt_patch; i_beta=$gn_vt_beta
  if (( c_major != i_major )); then
    if (( c_major < i_major )); then return 0; fi
    return 1
  fi
  if (( c_minor != i_minor )); then
    if (( c_minor < i_minor )); then return 0; fi
    return 1
  fi
  if (( c_patch != i_patch )); then
    if (( c_patch < i_patch )); then return 0; fi
    return 1
  fi
  if (( c_beta == i_beta )); then return 1; fi
  if (( c_beta < 0 )); then return 1; fi
  if (( i_beta < 0 )); then return 0; fi
  if (( c_beta < i_beta )); then return 0; fi
  return 1
}

gn_judge_release_manifest() {
  local manifest="$1" signature="${2:-}" installed="${3:-}" seen="${4:-0}" require="${5:-0}" public_key="${6:-}"
  local bytes version="" sequence="" signed=0 count pem
  gn_release_status="rejected"
  gn_release_reason="bad-manifest"
  gn_release_version=""
  gn_release_sequence=0
  gn_release_remember=0
  gn_release_signed=0
  [[ -f "$manifest" ]] || return 0
  bytes="$(wc -c < "$manifest" | tr -d ' ')"
  if [[ "$bytes" -le 0 || "$bytes" -gt 131072 ]]; then return 0; fi
  count="$(grep -c '"version"' "$manifest" || true)"
  count="$(printf '%s' "$count" | tr -d '[:space:]')"
  if [[ "$count" -ne 1 ]]; then return 0; fi
  count="$(grep -c '"sequence"' "$manifest" || true)"
  count="$(printf '%s' "$count" | tr -d '[:space:]')"
  if [[ "${count:-0}" -gt 1 ]]; then return 0; fi
  if [[ "$(cat "$manifest")" =~ \"version\"[[:space:]]*:[[:space:]]*\"([^\"]+)\" ]]; then
    version="${BASH_REMATCH[1]}"
  fi
  gn_version_tuple "$version" || return 0
  if [[ "$count" -eq 1 ]]; then
    if [[ "$(cat "$manifest")" =~ \"sequence\"[[:space:]]*:[[:space:]]*([0-9]+) ]]; then
      sequence="${BASH_REMATCH[1]}"
    fi
    if [[ ! "$sequence" =~ ^[1-9][0-9]*$ ]]; then return 0; fi
  fi
  if [[ -n "$signature" && -s "$signature" ]]; then
    if [[ -z "$public_key" ]]; then
      pem="$(mktemp)"
      gn_release_public_pem > "$pem"
      public_key="$pem"
    fi
    if ! openssl dgst -sha256 -verify "$public_key" -signature "$signature" "$manifest" >/dev/null 2>&1; then
      [[ -n "${pem:-}" ]] && rm -f "$pem"
      gn_release_reason="bad-signature"
      return 0
    fi
    [[ -n "${pem:-}" ]] && rm -f "$pem"
    signed=1
  elif [[ "$require" -eq 1 ]]; then
    gn_release_reason="signature-required"
    return 0
  fi
  if [[ -n "$installed" ]] && gn_version_is_older "$version" "$installed"; then
    gn_release_reason="rollback-version"
    gn_release_version="$version"
    return 0
  fi
  if [[ "$seen" =~ ^[1-9][0-9]*$ ]] && { [[ -z "$sequence" ]] || [[ "$sequence" -lt "$seen" ]]; }; then
    gn_release_reason="rollback-sequence"
    gn_release_version="$version"
    return 0
  fi
  gn_release_version="$version"
  if [[ -n "$sequence" ]]; then gn_release_sequence="$sequence"; fi
  if [[ "$signed" -eq 1 ]]; then
    gn_release_status="accepted"
    gn_release_reason="accepted"
    gn_release_signed=1
    if [[ -n "$sequence" ]]; then gn_release_remember=1; fi
  else
    gn_release_status="unsigned"
    gn_release_reason="unsigned"
  fi
}

gn_fetch_control() {
  local url="$1" output="$2" families family code left
  if [[ "$gn_address_policy" == "ipv6-first" ]]; then families="-6 -4"; else families="-4 -6"; fi
  for family in $families; do
    left="$(gn_budget_left)"
    if [[ "$left" -le 0 ]]; then return 1; fi
    if [[ "$left" -gt 20 ]]; then left=20; fi
    rm -f "$output"
    code="$(curl -sS --retry 0 --connect-timeout 8 --max-time "$left" "$family" -o "$output" -w '%{http_code}' "$url" || true)"
    if [[ "$code" == "200" && -s "$output" ]]; then
      printf '200'
      return 0
    fi
    if [[ "$code" == "404" ]]; then
      rm -f "$output"
      printf '404'
      return 0
    fi
  done
  return 1
}

gn_installed_version() {
  local bin="$app_root/game-navigator" version=""
  [[ -x "$bin" && ! -L "$bin" ]] || return 0
  version="$("$bin" --version 2>/dev/null | head -n 1 | tr -d '[:space:]' || true)"
  if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-beta\.[0-9]+)?$ ]]; then printf '%s' "$version"; fi
}

gn_seen_sequence() {
  local file="$data_root/release-sequence.txt" value=""
  [[ -f "$file" ]] || { printf '0'; return 0; }
  value="$(tr -d '[:space:]' < "$file" || true)"
  if [[ "$value" =~ ^[1-9][0-9]*$ ]]; then printf '%s' "$value"; else printf '0'; fi
}

gn_remember_sequence() {
  local value="$1" file="$data_root/release-sequence.txt"
  [[ "$value" =~ ^[1-9][0-9]*$ ]] || return 0
  printf '%s\n' "$value" > "$file.tmp"
  mv "$file.tmp" "$file"
  chmod 600 "$file"
}

gn_release_artifact_sha() {
  local name="$1" line count
  [[ -n "$gn_release_manifest_path" && -f "$gn_release_manifest_path" ]] || return 1
  count="$(grep -F "\"fileName\":\"$name\"" "$gn_release_manifest_path" | wc -l | tr -d ' ')"
  [[ "$count" -eq 1 ]] || return 1
  line="$(grep -F "\"fileName\":\"$name\"" "$gn_release_manifest_path")"
  [[ "$line" =~ \"sha256\":\"([0-9a-f]{64})\" ]] || return 1
  printf '%s' "${BASH_REMATCH[1]}"
}

gn_accept_release_manifest() {
  local manifest="$tmp/release-manifest.json" sig="$tmp/release-manifest.json.sig" manifest_code="" sig_code="" installed="" seen=""
  if [[ "$gn_release_judged" -eq 1 ]]; then
    [[ "$gn_release_status" != "rejected" ]]
    return
  fi
  gn_release_judged=1
  if ! manifest_code="$(gn_fetch_control "$base_url/downloads/release-manifest.json" "$manifest")"; then
    echo "The release list could not be read." >&2
    gn_release_status="rejected"
    return 1
  fi
  if [[ "$manifest_code" != "200" ]]; then
    if gn_signature_required; then
      gn_release_sentence signature-required >&2
      gn_release_status="rejected"
      return 1
    fi
    gn_release_status="unsigned"
    gn_release_sentence unsigned
    return 0
  fi
  if ! sig_code="$(gn_fetch_control "$base_url/downloads/release-manifest.json.sig" "$sig")"; then
    echo "The release list could not be read." >&2
    gn_release_status="rejected"
    return 1
  fi
  if [[ "$sig_code" != "200" ]]; then rm -f "$sig"; fi
  installed="$(gn_installed_version || true)"
  seen="$(gn_seen_sequence)"
  gn_release_manifest_path="$manifest"
  local require=0
  if gn_signature_required || gn_manifest_is_stable "$manifest"; then require=1; fi
  gn_judge_release_manifest "$manifest" "$sig" "$installed" "$seen" "$require"
  case "$gn_release_status" in
    rejected)
      gn_release_sentence "$gn_release_reason" >&2
      return 1
      ;;
    unsigned)
      gn_release_sentence unsigned
      return 0
      ;;
    accepted)
      if [[ "$gn_release_remember" -eq 1 ]]; then gn_remember_sequence "$gn_release_sequence"; fi
      return 0
      ;;
  esac
  return 1
}

verify_download() {
  local url="$1" output="$2" expected actual used=cdn package_url attempt status probe pinned=""
  gn_arm_package_budget
  gn_accept_release_manifest || return 1
  # Read the published hash first and pin it on the alias. A bare alias redirects
  # to the versioned object, which the edge may keep for a year after publish.
  # A release can switch after that read; a 404 means the pin is stale, so fetch
  # the hash once more, drop the partial, and retry. A second 404 uses origin.
  for attempt in 1 2; do
    rm -f "$output.sha256"
    fetch_download "$url.sha256" "$output.sha256" origin quiet
    expected="$(tr -d '[:space:]' < "$output.sha256" | tr '[:upper:]' '[:lower:]')"
    if [[ ! "$expected" =~ ^[0-9a-f]{64}$ ]]; then
      echo "Integrity verification failed for $url" >&2
      return 1
    fi
    if [[ "$gn_release_signed" -eq 1 ]]; then
      local pin_name=""
      case "$url" in
        */downloads/connector/*) pin_name="connector-${url##*/}.zip" ;;
        */skill/latest) pin_name="skill.zip" ;;
        */packs/bootstrap/latest) pin_name="bootstrap.zip" ;;
      esac
      if [[ -z "$pin_name" ]]; then
        gn_release_sentence bad-signature >&2
        return 1
      fi
      pinned="$(gn_release_artifact_sha "$pin_name" || true)"
      if [[ "$pinned" != "$expected" ]]; then
        gn_release_sentence bad-signature >&2
        return 1
      fi
    fi
    package_url="${url}?sha256=${expected}"
    if fetch_download "$package_url" "$output" cdn; then
      break
    fi
    probe="$(gn_budget_left)"
    if [[ "$probe" -le 0 ]]; then
      echo "The package download exceeded the time budget." >&2
      return 1
    fi
    if [[ "$probe" -gt 20 ]]; then probe=20; fi
    status="$(curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 8 --max-time "$probe" "$package_url" || true)"
    rm -f "$output" "$output".part "$output".headers "$output".mark*
    if [[ "$status" == "404" && "$attempt" -eq 1 ]]; then
      continue
    fi
    used=origin
    if ! fetch_download "${package_url}&direct=1" "$output" origin; then
      # A stall after the Skill archive is unpacked must not end the install.
      # The retry keeps the same deadline. ipv6-first tries IPv4, then IPv6.
      rm -f "$output" "$output".part "$output".headers "$output".mark*
      gn_pin_retry_family
      if ! fetch_download "${package_url}&direct=1" "$output" origin; then
        gn_force_family=""
        echo "The package download exceeded the time budget." >&2
        return 1
      fi
      gn_force_family=""
    fi
    break
  done
  local size package_cache="$gn_last_cache" package_colo="$gn_last_colo" package_network="$gn_last_network" package_speed="$gn_last_speed"
  if [[ "$(gn_budget_left)" -le 0 ]]; then
    echo "The package download exceeded the time budget." >&2
    return 1
  fi
  if [[ ! -f "$output" ]]; then
    echo "The package download exceeded the time budget." >&2
    return 1
  fi
  size="$(wc -c < "$output" | tr -d ' ')"
  actual="$(shasum -a 256 "$output" | awk '{print $1}')"
  if [[ "$actual" != "$expected" && "$used" == "cdn" ]]; then
    rm -f "$output" "$output".part "$output".headers "$output".mark*
    used=origin
    gn_pin_retry_family
    if ! fetch_download "${package_url}&direct=1" "$output" origin; then
      gn_force_family=""
      echo "The package download exceeded the time budget." >&2
      return 1
    fi
    gn_force_family=""
    size="$(wc -c < "$output" | tr -d ' ')"
    actual="$(shasum -a 256 "$output" | awk '{print $1}')"
    package_cache="$gn_last_cache"
    package_colo="$gn_last_colo"
    package_network="$gn_last_network"
    package_speed="$gn_last_speed"
  fi
  if [[ "$actual" != "$expected" ]]; then
    gn_journey_stage=verify; gn_journey_code=integrity
    echo "Integrity verification failed for $url" >&2
    return 1
  fi
  report_onboarding download-complete ok "$size" "$size" "$package_speed" "$used" "$package_cache" "$package_colo" 100 "$package_network" "$(gn_elapsed_ms)"
  rm -f "$output".mark*
}

replace_tree() {
  local staged="$1" target="$2"
  local backup="$target.previous"
  rm -rf "$backup"
  if [[ -e "$target" ]]; then mv "$target" "$backup"; fi
  if mv "$staged" "$target"; then
    rm -rf "$backup"
  else
    if [[ -e "$backup" ]]; then mv "$backup" "$target"; fi
    return 1
  fi
}

gn_sign_in_action() {
  local journey_json="$1"
  if printf '%s\n' "$journey_json" | grep -Eq '"signedIn"[[:space:]]*:[[:space:]]*true'; then
    printf 'ready'
    return 0
  fi
  if printf '%s\n' "$journey_json" | grep -Eq '"stage"[[:space:]]*:[[:space:]]*"account-check-unavailable"' \
    || printf '%s\n' "$journey_json" | grep -Eq '"authenticationState"[[:space:]]*:[[:space:]]*"unavailable"'; then
    printf 'later'
    return 0
  fi
  if ! printf '%s\n' "$journey_json" | grep -Eq '"stage"[[:space:]]*:[[:space:]]*"[A-Za-z0-9-]+"'; then
    printf 'later'
    return 0
  fi
  if printf '%s\n' "$journey_json" | grep -Eq '"stage"[[:space:]]*:[[:space:]]*"recognize-player"'; then
    printf 'begin'
    return 0
  fi
  printf 'keep'
}

finish_sign_in() {
  local why ready later lang="${LANG:-en}" journey_json login_json url login_id action
  case "$lang" in
    zh_TW*|zh_Hant*|zh-TW*|zh_HK*)
      why="登入是為了讓剛才發起的遊戲領航師登入使用這個帳號，以後才能連上正在玩遊戲的電腦。這一頁不需要密碼，也不會付款。如果網站已經登入，打開安全連結後確認，剛才發起的遊戲領航師登入將使用當前網站帳號，不必再登入一次。還沒登入就在該頁登入。如果這邊沒有打開瀏覽器，用你自己的手機或電腦打開這個連結就行，這不是登入失敗。確認之後回到剛才的對話，頁面不會自動跳回來。"
      ready="已經登入。若遊戲在這台電腦或另一台 Windows，這一輪就繼續連接；還用不到現場時，就接著原來的問題。"
      later="帳號服務暫時連不上。保留現有登入，不要重新發起。請稍後再試。"
      ;;
    zh*)
      why="登录是为了让刚才发起的游戏领航师登录使用这个账号，以后才能连上正在玩游戏的电脑。这一页不需要密码，也不会付款。如果网站已经登录，打开安全链接后确认，刚才发起的游戏领航师登录将使用当前网站账号，不必再登录一次。还没登录就在该页登录。如果这边没有打开浏览器，用你自己的手机或电脑打开这个链接就行，这不是登录失败。确认之后回到刚才的对话，页面不会自动跳回来。"
      ready="已经登录。若游戏在这台电脑或另一台 Windows，这一轮就继续连接；还用不到现场时，就接着原来的问题。"
      later="账号服务暂时连不上。保留现有登录，不要重新发起。请稍后再试。"
      ;;
    ja*)
      why="ログインは、先ほど始めたゲームナビゲーターのログインにこのアカウントを使わせ、あとからゲームをしているパソコンへつなげるためです。このページはパスワードも支払いも要りません。サイトにログイン済みなら、安全なリンクを開いて確認すると、先ほど始めたゲームナビゲーターのログインが今のアカウントを使います。もう一度ログインする必要はありません。未ログインなら、そのページでログインします。こちらでブラウザが開かなくても失敗ではありません。お使いのスマホかパソコンでリンクを開いてください。確認したら、さっきの会話に戻ってください。ページは自動では戻りません。"
      ready="アカウントはログイン済みです。ゲームがこのパソコンか別の Windows なら、このまま接続を続けてください。まだ画面が要らないなら、元の質問を続けてください。"
      later="アカウントサービスに一時的につながりません。今のログインを残します。新しく始めないでください。しばらくしてからもう一度試してください。"
      ;;
    ko*)
      why="로그인은 방금 시작한 게임 내비게이터 로그인이 이 계정을 사용하게 하고, 나중에 게임을 하는 컴퓨터와 연결하기 위한 것입니다. 이 페이지는 비밀번호도 결제도 요구하지 않습니다. 웹사이트에 이미 로그인되어 있으면 보안 링크를 열고 확인하면, 방금 시작한 게임 내비게이터 로그인이 현재 계정을 사용합니다. 다시 로그인하지 않아도 됩니다. 로그인되어 있지 않으면 그 페이지에서 로그인하세요. 이쪽에서 브라우저가 열리지 않아도 실패한 것이 아닙니다. 본인 휴대폰이나 컴퓨터에서 링크를 여세요. 확인한 뒤에는 방금 대화로 돌아오세요. 페이지가 자동으로 돌아가진 않습니다."
      ready="계정은 이미 로그인되어 있습니다. 게임이 이 컴퓨터인지 다른 Windows 인지 알고 있다면 이번 대화에서 연결을 이어가세요. 아직 화면이 필요 없으면 원래 질문을 계속하세요."
      later="계정 서비스에 일시적으로 연결되지 않습니다. 현재 로그인을 유지합니다. 새로 시작하지 마세요. 잠시 후 다시 시도하세요."
      ;;
    de*)
      why="Die Anmeldung lässt die gerade gestartete Game-Navigator-Anmeldung dieses Konto verwenden, damit sie später den Computer verbinden kann, auf dem das Spiel läuft. Diese Seite verlangt kein Passwort und keine Zahlung. Wenn die Website schon angemeldet ist, öffne den sicheren Link und bestätige, dass die gerade gestartete Game-Navigator-Anmeldung dieses Konto verwendet. Melde dich nicht noch einmal an. Ohne Anmeldung meldest du dich auf dieser Seite an. Wenn hier kein Browser aufgeht, öffne den Link auf deinem eigenen Telefon oder Computer. Das ist keine fehlgeschlagene Anmeldung. Komm nach dem Bestätigen in diesen Chat zurück. Die Seite springt nicht von selbst zurück."
      ready="Das Konto ist bereits angemeldet. Wenn das Spiel auf diesem Computer oder einem anderen Windows läuft, verbinde in diesem Gespräch weiter. Sonst setze die ursprüngliche Frage fort."
      later="Der Kontodienst ist vorübergehend nicht erreichbar. Behalte die bestehende Anmeldung. Starte keine neue. Versuche es später erneut."
      ;;
    fr*)
      why="La connexion permet à la connexion Game Navigator que vous venez de commencer d’utiliser ce compte, pour joindre plus tard l’ordinateur où le jeu tourne. Cette page ne demande pas de mot de passe et n’encaisse aucun paiement. Si le site est déjà connecté, ouvrez le lien sécurisé et confirmez pour que la connexion Game Navigator que vous venez de commencer utilise ce compte. Ne vous reconnectez pas. Sinon, connectez-vous sur cette page. Si aucun navigateur ne s’ouvre ici, ouvrez le lien sur votre propre téléphone ou ordinateur. Ce n’est pas un échec. Après la confirmation, revenez à cette conversation. La page n’y revient pas toute seule."
      ready="Le compte est déjà connecté. Si le jeu est sur cet ordinateur ou un autre Windows, continuez la connexion dans cet échange. Sinon, poursuivez la question d’origine."
      later="Le service de compte est temporairement injoignable. Conservez la connexion actuelle. N’en commencez pas une nouvelle. Réessayez plus tard."
      ;;
    *)
      why="Sign-in lets the Game Navigator sign-in you just started use this account, so it can later connect the computer where the game runs. This page does not ask for a password and does not take payment. If the website is already signed in, open the secure link and confirm to use that account for the Game Navigator sign-in you just started. Do not sign in again. If it is not signed in, sign in on that page. If no browser opens here, open the link on your own phone or computer. That is not a failed sign-in. After you confirm, come back to this chat. The page does not jump back by itself."
      ready="The account is already signed in. If the game is on this computer or another Windows PC, continue the connection in this turn. If the live screen is not needed yet, continue the original question."
      later="The account service is temporarily unreachable. Keep the existing sign-in. Do not start another one. Try again later."
      ;;
  esac
  echo
  journey_json="$("$app_root/game-navigator" journey --pretty 2>/dev/null || true)"
  action="$(gn_sign_in_action "$journey_json")"
  case "$action" in
    ready)
      printf '%s\n' "$ready"
      return 0
      ;;
    later)
      printf '%s\n' "$later"
      printf '%s\n' "AGENT: Do not run login --begin. Keep the existing sign-in and try again later."
      return 0
      ;;
    keep)
      printf '%s\n' "AGENT: Do not run login --begin. Continue from the journey result."
      return 0
      ;;
  esac
  login_json="$("$app_root/game-navigator" login --begin --open --pretty 2>/dev/null || true)"
  url="$(printf '%s\n' "$login_json" | sed -n 's/^[[:space:]]*"loginUrl"[[:space:]]*:[[:space:]]*"\(https:\/\/[^"]*\)".*/\1/p' | head -n 1)"
  login_id="$(printf '%s\n' "$login_json" | sed -n 's/^[[:space:]]*"loginId"[[:space:]]*:[[:space:]]*"\(login_[0-9a-f][0-9a-f]*\)".*/\1/p' | head -n 1)"
  printf '%s\n' "$why"
  if [[ -n "$url" && -n "$login_id" ]]; then
    printf '%s\n' "$url"
    printf '%s\n' "AGENT: Do not run login --begin again. Show the player only the https link above and the reason sentence in their language. Do not show any id. Then run now: $(shell_quote "$app_root/game-navigator") login --wait --id $login_id. pending reuses this id. Begin again only when it is expired or missing. On upgrade-required, update Game Navigator and begin once more. Do not read or copy a session token, and do not claim the sign-in without the wait secret. A network error is not expiry. Do not ask the player to report completion. If this host cannot wake itself, the next turn waits on this same id. browserOpened false is not a failed sign-in: the player opens the https link on their own phone or computer. A wait of 180 seconds, or 300 at most, is not the 15-minute expiry. If the player says it is authorized, or the program restarts and the local key remains, wait on this same id. The success page only points back to this chat. It does not jump back and is not a token to copy."
  else
    printf '%s\n' "AGENT: Run: $(shell_quote "$app_root/game-navigator") login --begin --open --pretty. Show the player only the https link and why sign-in is needed. Do not show any id. Then run: $(shell_quote "$app_root/game-navigator") login --wait --id LOGIN_ID"
  fi
}

if [[ "${GN_INSTALL_LIBRARY:-}" == 1 ]]; then
  if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then
    return 0
  fi
  exit 0
fi
report_onboarding script-start start 0 0 0 script "" "" 0
gn_status_line skill
verify_download "$base_url/skill/latest" "$tmp/skill.zip"
mkdir "$tmp/skill"
gn_journey_stage=extract; gn_journey_code=unknown
unzip -oq "$tmp/skill.zip" -d "$tmp/skill"
test -f "$tmp/skill/SKILL.md"
report_onboarding extract ok 0 0 0 script "" "" 0
replace_tree "$tmp/skill" "$skill_root"

gn_status_line catalog
verify_download "$base_url/packs/bootstrap/latest" "$tmp/packs.zip"
mkdir "$tmp/packs"
gn_journey_stage=extract; gn_journey_code=unknown
unzip -oq "$tmp/packs.zip" -d "$tmp/packs"
test -f "$tmp/packs/devices/rog-ally/manifest.yaml"
replace_tree "$tmp/packs/devices" "$pack_root/devices"

install_skill_copy() {
  local dest="$1"
  local stage="$tmp/agent-$(basename "$(dirname "$dest")")"
  mkdir -p "$stage" "$(dirname "$dest")"
  cp -R "$skill_root/." "$stage/"
  replace_tree "$stage" "$dest"
}

# Keep one vendor-neutral Agent Skills copy, then mirror it into detected vendor homes.
# WorkBuddy's user-skill location is also installed explicitly so the same package works
# without asking users to move files by hand.
install_skill_copy "$HOME/.agents/skills/game-navigator"
install_skill_copy "$HOME/.workbuddy/skills/game-navigator"
if [[ -d "$HOME/.claude" ]]; then install_skill_copy "$HOME/.claude/skills/game-navigator"; fi
if [[ -d "$HOME/.cursor" ]]; then install_skill_copy "$HOME/.cursor/skills/game-navigator"; fi
if [[ -d "$HOME/.codex" ]]; then install_skill_copy "$HOME/.codex/skills/game-navigator"; fi
if [[ -n "${GAMENAVIGATOR_SKILL_DIRS:-}" ]]; then
  IFS=':' read -r -a extra_skill_dirs <<< "$GAMENAVIGATOR_SKILL_DIRS"
  for extra_dir in "${extra_skill_dirs[@]}"; do
    [[ -z "$extra_dir" ]] || install_skill_copy "${extra_dir%/}/game-navigator"
  done
fi

connector_url="$base_url/downloads/connector/$rid"
verify_download "$connector_url" "$tmp/connector.zip"
mkdir "$tmp/connector"
gn_journey_stage=extract; gn_journey_code=unknown
unzip -oq "$tmp/connector.zip" -d "$tmp/connector"
test -x "$tmp/connector/game-navigator"
test -f "$tmp/connector/navigator-runtime.pl"
test -x /usr/bin/perl
connector_hash="$(shasum -a 256 "$tmp/connector.zip" | awk '{print $1}')"
/usr/bin/perl "$tmp/connector/navigator-runtime.pl" publish "$data_root" "$tmp/connector" "$connector_hash"
"$app_root/game-navigator" init --data-dir "$data_root" --server "$base_url"
report_onboarding install ok 0 0 0 script "" "" 100
# Keep selected and rollback versions; running old versions hold matching leases.
# Unknown/modified trees and the pre-coordinator app/current are never swept.
/usr/bin/perl "$app_root/navigator-runtime.pl" cleanup "$data_root"

echo
gn_status_line installed
entry="$app_root/game-navigator"
quoted="$(shell_quote "$entry")"
gn_completion_notice
echo "AGENT: NEXT: Stay in this conversation. Use the https link already printed below. Do not run login --begin again when that link exists. Run: $quoted journey only when no link was printed. Only then, if sign-in is still required, run once: $quoted login --begin --open --pretty. As soon as the link is shown, run login --wait --id with that id. Do not ask the player to report that sign-in is finished. pending reuses the same id. Begin again only when the id is expired or missing. A network error is not expiry. If this host cannot wake itself, the next turn waits on the same id. Do not promise that it will resume by itself. browserOpened false is not a failed sign-in. The player opens the https link on their own phone or computer. A wait of 180 seconds, or 300 at most, is not the 15-minute expiry. If the player says it is authorized, or the program restarts and the local key remains, continue the same sign-in. The success page only points back to this chat. It does not jump back and is not a token to copy. If the installer stops before this line, retry the official installer once; if that retry is also used up, tell the player. Do not stop after install."
echo "进阶 · Grok Bot：先通过 Grok Bot 自己的流程把 $skill_root/SKILL.md 注册为私有 Skill；若要连接家里的游戏端，还必须让两端预先处在 Tailscale 等可信私网中。不要把游戏端口直接暴露到公网。"
finish_sign_in
