#!/bin/sh
# cogshift install bootstrap (RU-INSTALL-SCRIPT-011) — macOS and Linux.
#
#   curl -fsSL https://cogshift.io/install.sh | sh
#
# Thin and auditable on purpose: it reads the release manifest from the
# pinned artifact host dl.cogshift.org, picks this machine's target triple,
# downloads that artifact, VERIFIES its SHA-256 against the manifest BEFORE
# installing or running anything, and only then places the binary in
# ~/.local/bin. A mismatch — or a missing target for this platform — aborts
# with nothing on the system. On Linux a package manager (apt/pacman/dnf) is
# detected and preferred once native packages are published.
#
# The trust is in the checksum you verify, not in this script: read it first
# (curl -fsSL https://cogshift.io/install.sh | less) or use the per-platform
# download page at https://cogshift.io/download/.
set -eu

MANIFEST_HOST="${COGSHIFT_MANIFEST_HOST:-https://dl.cogshift.org}"
BIN_DIR="${COGSHIFT_BIN_DIR:-$HOME/.local/bin}"

say() { printf '%s\n' "$*" >&2; }
die() { say "install aborted: $*"; exit 1; }

have() { command -v "$1" >/dev/null 2>&1; }

fetch() {
    # A single downloader abstraction: curl first, wget as fallback.
    if have curl; then
        curl -fsSL "$1" -o "$2"
    elif have wget; then
        wget -qO "$2" "$1"
    else
        die "need curl or wget to download"
    fi
}

os_of() {
    case "$(uname -s)" in
        Darwin) echo "mac" ;;
        Linux) echo "linux" ;;
        *) echo "unknown" ;;
    esac
}

target_of() {
    # Cross-product done per-OS so an ARM Linux box never lands on a
    # darwin triple by name luck.
    case "$1:$(uname -m)" in
        mac:arm64 | mac:aarch64) echo "aarch64-apple-darwin" ;;
        linux:x86_64) echo "x86_64-unknown-linux-gnu" ;;
        *) echo "unsupported" ;;
    esac
}

OS="$(os_of)"
[ "$OS" = "unknown" ] && die "unsupported OS '$(uname -s)' — see https://cogshift.io/download/"
TARGET="$(target_of "$OS")"
[ "$TARGET" = "unsupported" ] && die "no build for $OS/$(uname -m) yet — see https://cogshift.io/download/"

if [ "$OS" = "linux" ]; then
    PM=""
    have apt-get && PM="apt"
    [ -z "$PM" ] && have pacman && PM="pacman"
    [ -z "$PM" ] && have dnf && PM="dnf"
    if [ -n "$PM" ]; then
        # RU-INSTALL-SCRIPT-011: prefer the native signed package so the OS
        # owns updates. The packages are not published yet, so say so and
        # fall back to the verified tarball — detection stays honest either way.
        say "note: $PM detected — a native package is the preferred install once published."
        say "      falling back to the verified tarball for now."
    fi
fi

WORK="$(mktemp -d)"
trap 'rm -rf "$WORK"' EXIT

say "reading the release manifest..."
fetch "${MANIFEST_HOST}/stable.json" "${WORK}/stable.json" ||
    die "could not download ${MANIFEST_HOST}/stable.json (no release published yet? see https://cogshift.io/download/)"

# Pull THIS platform's entry out of the manifest without assuming jq:
# flatten whitespace, locate the target key, take its url and sha256 values.
FLAT="$(tr -d '\n\r\t ' <"${WORK}/stable.json")"
case "$FLAT" in
    *"\"artifacts\""*) ;;
    *) die "manifest has no artifacts mapping — refusing to continue" ;;
esac
case "$FLAT" in
    *"\"${TARGET}\":"*) ;;
    *) die "the manifest has no build for ${TARGET} yet — see https://cogshift.io/download/" ;;
esac
SEGMENT="${FLAT#*\"${TARGET}\":}"
case "$SEGMENT" in
    *'"url":"'*) ;;
    *) die "manifest entry for ${TARGET} carries no url — refusing to continue" ;;
esac
ART_URL="${SEGMENT#*\"url\":\"}"
ART_URL="${ART_URL%%\"*}"
case "$SEGMENT" in
    *'"sha256":"'*) ;;
    *) die "manifest entry for ${TARGET} carries no sha256 — refusing to install unverified" ;;
esac
EXPECTED="${SEGMENT#*\"sha256\":\"}"
EXPECTED="${EXPECTED%%\"*}"

# Validate what we parsed before trusting it: url rides the SAME pinned
# host the manifest came from, checksum is exactly 64 lowercase hex.
case "$ART_URL" in
    "${MANIFEST_HOST}/"*) ;;
    *) die "artifact url does not ride the pinned host (${MANIFEST_HOST}) — refusing to continue" ;;
esac
[ -n "$EXPECTED" ] || die "checksum value unreadable — refusing to install"
[ "${#EXPECTED}" -eq 64 ] || die "checksum value is ${#EXPECTED} chars, not a SHA-256 — refusing to install"
NONHEX="$(printf '%s' "$EXPECTED" | tr -d '0123456789abcdef')"
[ -z "$NONHEX" ] || die "checksum value contains non-hexadecimal characters — refusing to install"

VERSION="$(printf '%s' "$FLAT" | sed 's/.*"version":"\([^"]*\)".*/\1/')"
ARTIFACT="${ART_URL##*/}"

say "downloading ${ARTIFACT} (version ${VERSION})..."
fetch "$ART_URL" "${WORK}/${ARTIFACT}" ||
    die "could not download ${ART_URL} — see https://cogshift.io/download/"

# Verify BEFORE anything is installed or run: the downloaded bytes must hash
# to exactly what the manifest published for this target.
if have sha256sum; then
    ACTUAL="$(sha256sum "${WORK}/${ARTIFACT}" | awk '{print tolower($1)}')"
elif have shasum; then
    ACTUAL="$(shasum -a 256 "${WORK}/${ARTIFACT}" | awk '{print tolower($1)}')"
else
    die "need sha256sum or shasum to verify the download — refusing to install unverified"
fi
if [ "$ACTUAL" != "$EXPECTED" ]; then
    die "SHA-256 MISMATCH:
  expected $EXPECTED
  actual   $ACTUAL
The download is not the artifact this release published. Nothing was installed.
Report it at https://cogshift.io/ or the project repository."
fi
say "checksum verified."

tar -C "$WORK" -xzf "${WORK}/${ARTIFACT}"
[ -f "${WORK}/argus-personal" ] || die "archive did not contain argus-personal"

mkdir -p "$BIN_DIR"
mv "${WORK}/argus-personal" "${BIN_DIR}/argus-personal"
chmod +x "${BIN_DIR}/argus-personal"

# Drop the install-method marker + the first local audit line
# (RU-UPDATE-BY-INSTALL-013 / RU-INSTALL-LOG-012). Machine-local only.
DATA_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/cogshift"
[ "$OS" = "mac" ] && DATA_DIR="$HOME/Library/Application Support/Cogshift"
mkdir -p "$DATA_DIR"
printf '{"method": "shim", "by": "install.sh", "at": %s}\n' "$(date +%s)" \
    >"${DATA_DIR}/.install-method"
printf '{"at": %s, "kind": "install", "from": null, "to": "%s", "source": "install.sh", "outcome": "ok"}\n' \
    "$(date +%s)" "$VERSION" >>"${DATA_DIR}/install.log"

say "installed: ${BIN_DIR}/argus-personal"
case ":$PATH:" in
    *":$BIN_DIR:"*) ;;
    *) say "note: add $BIN_DIR to your PATH to run 'argus-personal' from anywhere." ;;
esac
say "run it:    ${BIN_DIR}/argus-personal"
