#!/usr/bin/env bash
# SysOM OS-Ops CLI — quick installer (Linux / macOS).
#
# OSS layout this installer expects:
#   <base>/<arch_dir>/skill_cli/sysom-osops-<os_tag>-<version>-<arch>.tgz
#   <base>/<arch_dir>/skill_cli/checksums-<version>.sha256
# where
#   <base>      = https://sysom-prd-<region>.oss-<region>[-internal].aliyuncs.com/sysom_prd
#   <arch_dir>  = x86  (for amd64/x86_64)   or   aarch64  (for arm64/aarch64)
#   <os_tag>    = linux | macosx
#   <arch>      = amd64 | arm64              (binary name suffix inside the tgz)
#
# Download strategy (no environment variables required):
#   1. Probe Alibaba Cloud ECS metadata service at 100.100.100.200 (1s timeout)
#      to detect whether the host is running on ECS and get its region-id.
#   2. On ECS         -> try the region's internal OSS endpoint first:
#                        https://sysom-prd-${region}.oss-${region}-internal.aliyuncs.com/sysom_prd
#                        on failure, fall back to the public Hangzhou endpoint.
#   3. Non-ECS host   -> go straight to the public Hangzhou endpoint:
#                        https://sysom-prd-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/sysom_prd
#
# Override via HTTPS mirror and pin the package digest (the base should contain
# `x86/` and `aarch64/` subtrees):
#   SYSOM_OSOPS_BASE_URL=https://my.mirror/sysom_prd \
#   SYSOM_OSOPS_EXPECTED_DIGEST=<sha256> curl -fsSL ... | sudo -E bash
#
# Typical usage (requires write access to install dir, usually via sudo):
#   curl -fsSL https://sysom-prd-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/sysom_prd/skill_cli/install.sh \
#     | sudo bash
# Pin a version:
#   curl -fsSL ... | sudo bash -s -- -V 1.0.0-beta
# Skip checksum verification for dev/test only:
#   SYSOM_OSOPS_DEV_MODE=1 curl -fsSL ... | sudo -E bash -s -- -s

set -euo pipefail

show_help() {
	cat <<'EOF'
SysOM OS-Ops CLI installer (Linux / macOS)

  -h              Show this help and exit
  -V VERSION      Version to install (default: latest)
  -d DEST         Install directory for the binary (default: /usr/local/bin)
  -r REGION       Use the official internal OSS endpoint for REGION
  -s              Skip SHA256 verification (requires SYSOM_OSOPS_DEV_MODE=1)
  -f              Force install even if Rosetta translation is detected
  -S              Skip macOS ad-hoc codesign / quarantine strip (macOS only)

Environment:
  SYSOM_OSOPS_BASE_URL         Override HTTPS mirror base; requires SYSOM_OSOPS_EXPECTED_DIGEST
  SYSOM_OSOPS_SKIP_CHECKSUM    Set to 1 to skip SHA256 verification
  SYSOM_OSOPS_DEV_MODE         Set to 1 to allow dev/test checksum bypass
  SYSOM_OSOPS_EXPECTED_DIGEST  Service-pinned package SHA256; required with a custom mirror
  SYSOM_OSOPS_LOCK_TIMEOUT     Linux install-lock wait in seconds, 0-30 (default: 30)
  SYSOM_OSOPS_FORCE            Set to 1 to ignore Rosetta/arch warnings
  SYSOM_OSOPS_SKIP_CODESIGN    Set to 1 to skip macOS ad-hoc codesign (default: 0)
EOF
}

abort() {
	printf 'error: %s\n' "$@" >&2
	exit 1
}

warn() {
	printf 'warn: %s\n' "$@" >&2
}

info() {
	printf '%s\n' "$@"
}

extract_cli_version() {
	local bin="$1"
	local out versions count
	if [[ ! -x "$bin" ]]; then
		return 1
	fi
	if ! out="$("$bin" --version 2>/dev/null)"; then
		return 1
	fi
	versions="$(printf '%s\n' "$out" | awk '
		{
			for (i = 1; i <= NF; i++) {
				if ($i ~ /^[0-9]+([.][0-9]+)*([-+][0-9A-Za-z.-]+)?$/) {
					print $i
				}
			}
		}
	')"
	count="$(printf '%s\n' "$versions" | awk 'NF { count++ } END { print count + 0 }')"
	[[ "$count" = "1" ]] || return 1
	printf '%s\n' "$versions"
}

current_cli_path() {
	if [[ -x "${INSTALL_DIR}/${BINARY_NAME}" ]]; then
		printf '%s\n' "${INSTALL_DIR}/${BINARY_NAME}"
	elif check_cmd "$BINARY_NAME"; then
		command -v "$BINARY_NAME"
	fi
}

# Public fallback. Always reachable from any network with egress to aliyuncs.com.
PUBLIC_BASE_URL="https://sysom-prd-cn-hangzhou.oss-cn-hangzhou.aliyuncs.com/sysom_prd"
# ECS metadata service (stable-IP, no DNS needed). 1s budget so non-ECS hosts don't stall.
ECS_META_URL="http://100.100.100.200/latest/meta-data/region-id"
ECS_PROBE_TIMEOUT=1

: "${SYSOM_OSOPS_BASE_URL:=}"
: "${SYSOM_OSOPS_SKIP_CHECKSUM:=0}"
: "${SYSOM_OSOPS_DEV_MODE:=0}"
: "${SYSOM_OSOPS_EXPECTED_DIGEST:=}"
: "${SYSOM_OSOPS_LOCK_TIMEOUT:=30}"
: "${SYSOM_OSOPS_FORCE:=0}"
: "${SYSOM_OSOPS_SKIP_CODESIGN:=0}"

VERSION="latest"
INSTALL_DIR="/usr/local/bin"
REGION_OVERRIDE=""
REGION_OVERRIDE_SET=0
BINARY_NAME="sysom-osops"
SKIP_CHECKSUM="$SYSOM_OSOPS_SKIP_CHECKSUM"
DEV_MODE="$SYSOM_OSOPS_DEV_MODE"
POLICY_DIGEST="$(printf '%s' "${SYSOM_OSOPS_EXPECTED_DIGEST#sha256:}" | tr '[:upper:]' '[:lower:]')"
FORCE="$SYSOM_OSOPS_FORCE"
SKIP_CODESIGN="$SYSOM_OSOPS_SKIP_CODESIGN"

while getopts "hV:d:r:sfS" opt; do
	case "$opt" in
	h)
		show_help
		exit 0
		;;
	V) VERSION="$OPTARG" ;;
	d) INSTALL_DIR="$OPTARG" ;;
	r) REGION_OVERRIDE="$OPTARG"; REGION_OVERRIDE_SET=1 ;;
	s) SKIP_CHECKSUM=1 ;;
	f) FORCE=1 ;;
	S) SKIP_CODESIGN=1 ;;
	*)
		show_help
		exit 1
		;;
	esac
done

if [[ "$SKIP_CHECKSUM" = "1" && "$DEV_MODE" != "1" ]]; then
	abort "Checksum verification can only be skipped for dev/test; set SYSOM_OSOPS_DEV_MODE=1 explicitly."
fi
if [[ "$VERSION" != "latest" && ! "$VERSION" =~ ^[0-9]+([.][0-9]+)*([-+][0-9A-Za-z.-]+)?$ ]]; then
	abort "Invalid version: ${VERSION}."
fi
if [[ -n "$POLICY_DIGEST" && ! "$POLICY_DIGEST" =~ ^[0-9a-f]{64}$ ]]; then
	abort "SYSOM_OSOPS_EXPECTED_DIGEST must be a SHA256 digest."
fi
if [[ -n "$SYSOM_OSOPS_BASE_URL" ]]; then
	[[ "$SYSOM_OSOPS_BASE_URL" = https://* ]] || abort "Custom mirror must use HTTPS."
	[[ -n "$POLICY_DIGEST" ]] || abort "Custom mirror requires SYSOM_OSOPS_EXPECTED_DIGEST."
fi
if [[ "$REGION_OVERRIDE_SET" = "1" ]]; then
	if [[ ! "$REGION_OVERRIDE" =~ ^[a-z0-9]+(-[a-z0-9]+)*$ ]] || [[ ${#REGION_OVERRIDE} -gt 32 ]]; then
		abort "Invalid region: ${REGION_OVERRIDE}."
	fi
fi
if [[ "$REGION_OVERRIDE_SET" = "1" && -n "$SYSOM_OSOPS_BASE_URL" ]]; then
	abort "Region override cannot be combined with SYSOM_OSOPS_BASE_URL."
fi
if [[ ! "$SYSOM_OSOPS_LOCK_TIMEOUT" =~ ^([0-9]|[12][0-9]|30)$ ]]; then
	abort "SYSOM_OSOPS_LOCK_TIMEOUT must be an integer between 0 and 30."
fi

# ---------------------------------------------------------------------------
# 1) Preflight: required commands must exist before we do anything else.
# ---------------------------------------------------------------------------
check_cmd() {
	command -v "$1" >/dev/null 2>&1
}

missing=()
for cmd in curl tar uname install mktemp; do
	check_cmd "$cmd" || missing+=("$cmd")
done
# sha256sum on Linux, shasum on macOS — at least one is needed unless -s
if [[ "$SKIP_CHECKSUM" != "1" || -n "$POLICY_DIGEST" ]]; then
	if ! check_cmd sha256sum && ! check_cmd shasum; then
		missing+=("sha256sum|shasum")
	fi
fi

if ((${#missing[@]} > 0)); then
	hint=""
	if check_cmd apt-get; then
		hint="  sudo apt-get update && sudo apt-get install -y curl tar coreutils"
	elif check_cmd dnf; then
		hint="  sudo dnf install -y curl tar coreutils"
	elif check_cmd yum; then
		hint="  sudo yum install -y curl tar coreutils"
	elif check_cmd apk; then
		hint="  sudo apk add --no-cache curl tar coreutils"
	elif check_cmd brew; then
		hint="  brew install curl coreutils"
	fi
	msg="missing required commands: ${missing[*]}"
	[[ -n "$hint" ]] && msg="$msg"$'\n'"try:"$'\n'"$hint"
	abort "$msg"
fi

# ---------------------------------------------------------------------------
# 2) Detect OS / ARCH (with Rosetta awareness on Apple Silicon).
#    ARCH_DIR aligns with sysak's OSS layout: amd64→x86, arm64→aarch64.
# ---------------------------------------------------------------------------
OS="$(uname)"
UNAME_MACHINE="$(uname -m)"

case "$OS" in
Linux) OS_TAG="linux" ;;
Darwin) OS_TAG="macosx" ;;
*) abort "Unsupported operating system: ${OS}. On Windows, use scripts/install.ps1." ;;
esac

case "$UNAME_MACHINE" in
x86_64 | amd64) ARCH="amd64"; ARCH_DIR="x86" ;;
arm64 | aarch64) ARCH="arm64"; ARCH_DIR="aarch64" ;;
*) abort "Unsupported CPU architecture: ${UNAME_MACHINE}. Supported: amd64, arm64." ;;
esac

# Apple Silicon running an x86_64 shell under Rosetta: uname -m reports x86_64.
# Detect via sysctl.proc_translated and recommend installing the native arm64 build.
if [[ "$OS" = "Darwin" && "$ARCH" = "amd64" ]]; then
	translated="$(sysctl -n sysctl.proc_translated 2>/dev/null || echo 0)"
	if [[ "$translated" = "1" ]]; then
		if [[ "$FORCE" = "1" ]]; then
			warn "Rosetta translation detected; installing amd64 build (forced via -f / SYSOM_OSOPS_FORCE=1)."
		else
			abort "Rosetta translation detected: this shell runs under Intel emulation on Apple Silicon." \
				"Re-run from a native arm64 shell to get the native build, e.g.:" \
				"  arch -arm64 /bin/bash -c \"curl -fsSL <install.sh> | sudo bash\"" \
				"Or bypass this check with -f (or SYSOM_OSOPS_FORCE=1) to force the amd64 build."
		fi
	fi
fi

# ---------------------------------------------------------------------------
# 3) Resolve candidate URLs.
#    Order of probing:
#      a) SYSOM_OSOPS_BASE_URL (if user set)           -> user's mirror only
#      b) ECS region internal OSS (if metadata hits)   -> fast, no public egress
#      c) Public Hangzhou OSS                          -> universal fallback
#    Each base has "/sysom_prd" granularity; the final URL is built as
#        <base>/<ARCH_DIR>/skill_cli/<pkg>
# ---------------------------------------------------------------------------
detect_ecs_region() {
	# Probe ECS meta server. Anything other than a clean 2xx with a non-empty
	# alphanumeric region-id is treated as "not ECS".
	local region
	region="$(curl -fsSL --connect-timeout "$ECS_PROBE_TIMEOUT" --max-time "$ECS_PROBE_TIMEOUT" \
		"$ECS_META_URL" 2>/dev/null || true)"
	# Strip whitespace, reject obvious HTML error pages.
	region="$(printf '%s' "$region" | tr -d '[:space:]')"
	if [[ "$region" =~ ^[a-z0-9-]+$ && ${#region} -le 32 ]]; then
		printf '%s' "$region"
	fi
}

BASES=()
if [[ -n "$SYSOM_OSOPS_BASE_URL" ]]; then
	BASES+=("${SYSOM_OSOPS_BASE_URL%/}")
	info "Using user-supplied mirror: ${BASES[0]}"
elif [[ "$REGION_OVERRIDE_SET" = "1" ]]; then
	INTERNAL_BASE="https://sysom-prd-${REGION_OVERRIDE}.oss-${REGION_OVERRIDE}-internal.aliyuncs.com/sysom_prd"
	BASES+=("$INTERNAL_BASE")
	info "Using official internal endpoint for region ${REGION_OVERRIDE}: ${INTERNAL_BASE}"
else
	info "Probing ECS metadata service (${ECS_PROBE_TIMEOUT}s budget)..."
	REGION="$(detect_ecs_region || true)"
	if [[ -n "${REGION:-}" ]]; then
		INTERNAL_BASE="https://sysom-prd-${REGION}.oss-${REGION}-internal.aliyuncs.com/sysom_prd"
		info "ECS detected (region=${REGION}); preferring internal endpoint."
		BASES+=("$INTERNAL_BASE")
	else
		info "Non-ECS environment (or metadata unreachable); using public endpoint."
	fi
	BASES+=("$PUBLIC_BASE_URL")
fi

LATEST_VERSION_PATH="skill_cli/latest.version"

TMPDIR="$(mktemp -d)"
install_lock=""
lock_owned=0
lock_owner=""
lock_token=""
reclaim_lock=""
reclaim_owner=""

remove_owned_directory() {
	local path="$1" owner="$2" token="$3" current release_path
	current="$(cat "$path/owner" 2>/dev/null || true)"
	[[ "$current" = "$owner" ]] || return 0
	release_path="${path}.release.${token}"
	if mv "$path" "$release_path" 2>/dev/null \
		&& [[ "$(cat "$release_path/owner" 2>/dev/null || true)" = "$owner" ]]; then
		rm -rf "$release_path"
	fi
}

cleanup() {
	rm -rf "$TMPDIR"
	if [[ -n "$reclaim_lock" && -n "$reclaim_owner" ]]; then
		remove_owned_directory "$reclaim_lock" "$reclaim_owner" "$lock_token"
	fi
	if [[ "$OS_TAG" = "linux" && "$lock_owned" = "1" ]]; then
		exec 9>&-
	elif [[ "$lock_owned" = "1" ]]; then
		remove_owned_directory "$install_lock" "$lock_owner" "$lock_token"
	fi
}
trap cleanup EXIT
trap 'exit 130' INT
trap 'exit 143' TERM

info "Detected: ${OS_TAG}/${ARCH} (arch_dir=${ARCH_DIR})   version=${VERSION}"

if [[ ! -d "$INSTALL_DIR" ]]; then
	abort "Install directory does not exist: ${INSTALL_DIR}"
fi

if [[ ! -w "$INSTALL_DIR" ]]; then
	abort "Cannot write to ${INSTALL_DIR}. Re-run with a user that can write there (e.g. sudo)," \
		"or pass -d <writable-dir> (e.g. -d \"\$HOME/.local/bin\")."
fi

target="${INSTALL_DIR}/${BINARY_NAME}"

process_is_alive() {
	local pid="$1" visible
	if kill -0 "$pid" 2>/dev/null; then
		return 0
	fi
	if ! check_cmd ps; then
		return 0
	fi
	visible="$(ps -p "$pid" -o pid= 2>/dev/null || true)"
	[[ "$visible" =~ [0-9] ]]
}

acquire_install_lock() {
	local existing_owner existing_token lock_pid current_owner stale_path claim_pid
	[[ "$lock_owned" = "0" ]] || return 0
	install_lock="${INSTALL_DIR}/.${BINARY_NAME}.update.lock"
	if [[ "$OS_TAG" = "linux" ]]; then
		check_cmd flock || abort "flock is required to coordinate installation with sysom-osops update."
		exec 9>"$install_lock"
		if ! flock -w "$SYSOM_OSOPS_LOCK_TIMEOUT" 9; then
			exec 9>&-
			abort "Another installation is already updating ${target} after waiting ${SYSOM_OSOPS_LOCK_TIMEOUT}s."
		fi
		lock_owned=1
		return 0
	fi

	lock_owner="$$:${TMPDIR##*/}"
	lock_token="${lock_owner#*:}"
	if mkdir "$install_lock" 2>/dev/null; then
		printf '%s\n' "$lock_owner" > "$install_lock/owner"
		lock_owned=1
		return 0
	fi

	existing_owner="$(cat "$install_lock/owner" 2>/dev/null || true)"
	lock_pid="${existing_owner%%:*}"
	existing_token="${existing_owner#*:}"
	if [[ ! "$lock_pid" =~ ^[0-9]+$ || "$existing_token" = "$existing_owner" \
		|| ! "$existing_token" =~ ^[A-Za-z0-9._-]+$ ]]; then
		abort "Another installation is already updating ${target}."
	fi
	if process_is_alive "$lock_pid"; then
		abort "Another installation is already updating ${target}."
	fi

	reclaim_lock="${install_lock}.reclaim.${existing_token}"
	reclaim_owner="$lock_owner"
	if ! mkdir "$reclaim_lock" 2>/dev/null; then
		current_owner="$(cat "$reclaim_lock/owner" 2>/dev/null || true)"
		claim_pid="${current_owner%%:*}"
		if [[ ! "$claim_pid" =~ ^[0-9]+$ ]] || process_is_alive "$claim_pid"; then
			abort "Another installation is already updating ${target}."
		fi
		remove_owned_directory "$reclaim_lock" "$current_owner" "$lock_token"
		mkdir "$reclaim_lock" 2>/dev/null || abort "Another installation is already updating ${target}."
	fi
	printf '%s\n' "$reclaim_owner" > "$reclaim_lock/owner"

	current_owner="$(cat "$install_lock/owner" 2>/dev/null || true)"
	if [[ "$current_owner" != "$existing_owner" ]] || process_is_alive "$lock_pid"; then
		abort "Another installation is already updating ${target}."
	fi
	stale_path="${install_lock}.stale.${lock_token}"
	mv "$install_lock" "$stale_path" 2>/dev/null || abort "Another installation is already updating ${target}."
	if [[ "$(cat "$stale_path/owner" 2>/dev/null || true)" != "$existing_owner" ]]; then
		mv "$stale_path" "$install_lock" 2>/dev/null || true
		abort "Another installation is already updating ${target}."
	fi
	rm -rf "$stale_path"
	remove_owned_directory "$reclaim_lock" "$reclaim_owner" "$lock_token"
	reclaim_lock=""
	reclaim_owner=""
	mkdir "$install_lock" 2>/dev/null || abort "Another installation is already updating ${target}."
	printf '%s\n' "$lock_owner" > "$install_lock/owner"
	lock_owned=1
}

fetch_latest_version() {
	local base url version
	for base in "${BASES[@]}"; do
		url="${base}/${LATEST_VERSION_PATH}"
		version="$(curl -fsSL --connect-timeout 5 --max-time 10 "$url" 2>/dev/null || true)"
		version="$(printf '%s' "$version" | tr -d '[:space:]')"
		if [[ -z "$version" ]]; then
			warn "latest.version not found at ${url}; trying next..."
			continue
		fi
		if [[ ! "$version" =~ ^[0-9]+([.][0-9]+)*([-+][0-9A-Za-z.-]+)?$ ]]; then
			warn "Ignoring invalid latest.version from ${url}: ${version}"
			continue
		fi
		printf '%s\n' "$version"
		return 0
	done
	return 1
}

acquire_install_lock

if [[ "$VERSION" = "latest" ]]; then
	LATEST_VERSION="$(fetch_latest_version || true)"
	if [[ -n "$LATEST_VERSION" ]]; then
		info "Latest version: ${LATEST_VERSION}"
		current_path="$(current_cli_path || true)"
		current_version=""
		if [[ -n "$current_path" ]]; then
			current_version="$(extract_cli_version "$current_path" || true)"
		fi
		if [[ -n "$current_version" ]]; then
			info "Installed ${BINARY_NAME} version: ${current_version} (${current_path})"
			if [[ "$current_version" = "$LATEST_VERSION" ]]; then
				info "Installed ${BINARY_NAME} is already latest; skipping reinstall."
				exit 0
			fi
			info "Version mismatch; reinstalling ${BINARY_NAME}."
		fi
		VERSION="$LATEST_VERSION"
	else
		abort "Could not resolve latest.version from any candidate endpoint."
	fi
fi

PKG="${BINARY_NAME}-${OS_TAG}-${VERSION}-${ARCH}.tgz"
PKG_PATH="${ARCH_DIR}/skill_cli/${PKG}"
CHECKSUM_PATH="${ARCH_DIR}/skill_cli/checksums-${VERSION}.sha256"

# Try each base URL in order; first success wins.
download_pkg() {
	local out_pkg="$1"
	local base url http_code ok=0
	for base in "${BASES[@]}"; do
		url="${base}/${PKG_PATH}"
		info "Downloading ${url}"
		http_code="$(curl -fsSL --connect-timeout 5 -o "$out_pkg" -w '%{http_code}' "$url" 2>/dev/null || echo "000")"
		if [[ -s "$out_pkg" && "$http_code" =~ ^2 ]]; then
			ok=1
			BASE_USED="$base"
			break
		fi
		warn "Download failed from ${base} (HTTP ${http_code}); trying next..."
		rm -f "$out_pkg"
	done
	[[ "$ok" = "1" ]]
}

BASE_USED=""
if ! download_pkg "${TMPDIR}/${PKG}"; then
	abort "Failed to download ${PKG_PATH} from all candidate endpoints." \
		"Tried: ${BASES[*]}" \
		"Check:" \
		"  - version               → currently '${VERSION}' (try -V <version> or 'latest')" \
		"  - network / proxy reachability" \
		"  - set SYSOM_OSOPS_BASE_URL=<your-mirror> to override auto-detect"
fi
info "Using base URL: ${BASE_USED}"
CHECKSUM_URL="${BASE_USED}/${CHECKSUM_PATH}"

# ---------------------------------------------------------------------------
# 4) Verify SHA256.
# ---------------------------------------------------------------------------
if check_cmd sha256sum; then
	actual="$(sha256sum "${TMPDIR}/${PKG}" | awk '{print $1}')"
else
	actual="$(shasum -a 256 "${TMPDIR}/${PKG}" | awk '{print $1}')"
fi
if [[ "$SKIP_CHECKSUM" = "1" ]]; then
	warn "Skipping SHA256 verification (-s / SYSOM_OSOPS_SKIP_CHECKSUM=1)."
else
	curl -fsSL -o "${TMPDIR}/checksums.sha256" "$CHECKSUM_URL" 2>/dev/null \
		|| abort "Checksum file not found at ${CHECKSUM_URL}." \
			"Use SYSOM_OSOPS_SKIP_CHECKSUM=1 with SYSOM_OSOPS_DEV_MODE=1 only for dev/test."
	expected="$(awk -v f="${PKG}" '$2==f || $2=="*"f {print $1; exit}' "${TMPDIR}/checksums.sha256" || true)"
	[[ -n "$expected" ]] || abort "Checksum file does not contain an entry for ${PKG}."
	if [[ "$actual" != "$expected" ]]; then
		abort "SHA256 mismatch for ${PKG}" \
			"  expected: ${expected}" \
			"  actual:   ${actual}"
	fi
	info "SHA256 verified ✓"
fi
if [[ -n "$POLICY_DIGEST" && "$actual" != "$POLICY_DIGEST" ]]; then
	abort "Package does not match the service policy artifact digest" \
		"  expected: ${POLICY_DIGEST}" \
		"  actual:   ${actual}"
fi

# ---------------------------------------------------------------------------
# 5) Extract & install.
# ---------------------------------------------------------------------------
tar xzf "${TMPDIR}/${PKG}" -C "$TMPDIR"

if [[ ! -f "${TMPDIR}/${BINARY_NAME}" ]]; then
	abort "Expected ${BINARY_NAME} inside archive, not found after extract."
fi

chmod 0755 "${TMPDIR}/${BINARY_NAME}"

if [[ "$OS_TAG" = "macosx" && "$SKIP_CODESIGN" != "1" ]]; then
	if check_cmd xattr; then
		xattr -d com.apple.quarantine "${TMPDIR}/${BINARY_NAME}" 2>/dev/null || true
	fi
	if check_cmd codesign; then
		if codesign --sign - --force --timestamp=none --options=runtime \
			"${TMPDIR}/${BINARY_NAME}" >/dev/null 2>&1 \
			|| codesign --sign - --force --timestamp=none \
				"${TMPDIR}/${BINARY_NAME}" >/dev/null 2>&1; then
			info "Applied ad-hoc signature to candidate binary"
		else
			warn "ad-hoc codesign failed; candidate version validation will determine whether installation can continue."
		fi
	else
		warn "codesign not found. Install Xcode Command Line Tools to enable ad-hoc signing:" \
			"  xcode-select --install"
	fi
fi

staged="$(mktemp "${INSTALL_DIR}/.${BINARY_NAME}.new.XXXXXX")"
backup="$(mktemp "${INSTALL_DIR}/.${BINARY_NAME}.backup.XXXXXX")"
rm -f "$staged"
rm -f "$backup"
install -m 0755 "${TMPDIR}/${BINARY_NAME}" "$staged"
candidate_version="$(extract_cli_version "$staged" || true)"
if [[ -z "$candidate_version" || "$candidate_version" != "$VERSION" ]]; then
	rm -f "$staged"
	abort "Candidate binary failed version validation: expected ${VERSION}, got ${candidate_version:-no valid version output}."
fi

rollback_install() {
	local failure="$1" restored_version rollback_staged
	rm -f "$staged"
	if [[ ! -e "$backup" ]]; then
		rm -f "$target"
		abort "${failure}; unusable installation removed; no previous installation was available."
	fi
	rollback_staged="$(mktemp "${INSTALL_DIR}/.${BINARY_NAME}.rollback.XXXXXX")"
	rm -f "$rollback_staged"
	if install -m 0755 "$backup" "$rollback_staged" && mv "$rollback_staged" "$target"; then
		restored_version="$(extract_cli_version "$target" || true)"
		if [[ -x "$target" && -n "$restored_version" ]]; then
			rm -f "$backup"
			abort "${failure}; previous installation was restored and verified."
		fi
	fi
	rm -f "$rollback_staged"
	abort "${failure}; rollback failed. Backup retained at: ${backup}"
}

if [[ -e "$target" ]]; then
	if ! install -m 0755 "$target" "$backup"; then
		rm -f "$staged"
		abort "Could not back up existing binary: ${target}"
	fi
fi
if ! mv "$staged" "$target"; then
	rollback_install "Could not replace ${target}"
fi

installed_version="$(extract_cli_version "$target" || true)"
if [[ "$installed_version" != "$VERSION" ]]; then
	rollback_install "Installed binary failed version validation"
fi
rm -f "$backup"

# ---------------------------------------------------------------------------
# 5a) Linux-only PATH visibility fallback.
#     Some minimal non-login shells do not include /usr/local/bin in PATH even
#     though that is the default install location. On Linux, make the default
#     install discoverable through /usr/bin when needed. macOS is excluded
#     because /usr/bin is SIP-protected.
# ---------------------------------------------------------------------------
	if [[ "$OS_TAG" = "linux" ]]; then
		hash -r 2>/dev/null || true
		if [[ "$INSTALL_DIR" = "/usr/local/bin" ]] \
			&& [[ -d /usr/bin && -w /usr/bin ]]; then
			ln -sf "${INSTALL_DIR}/${BINARY_NAME}" "/usr/bin/${BINARY_NAME}"
			hash -r 2>/dev/null || true
			info "Linked /usr/bin/${BINARY_NAME} -> ${INSTALL_DIR}/${BINARY_NAME}"
		fi
fi

info "Installed $target"

# Friendly PATH hint if install dir is not in PATH.
hash -r 2>/dev/null || true
if ! command -v "$BINARY_NAME" >/dev/null 2>&1; then
	warn "${INSTALL_DIR} is not in your PATH. Add it to your shell rc, e.g.:"
	warn "  echo 'export PATH=\"${INSTALL_DIR}:\$PATH\"' >> ~/.bashrc"
fi
