#!/bin/sh
# install-om.sh — Signed installer for om (Layer 2 Agent Control Plane)
# Served at https://get.om.network:
#   curl -fsSL https://get.om.network | sh
#   curl -fsSL https://get.om.network | sh -s -- --init
#   curl -fsSL https://get.om.network | sh -s -- --no-sandbox
#
# Installs om, omd, om-desk, bundled Bun, and MCP server into ~/.local/opt/om
# (and links ~/.local/bin/om) or system /usr via --system on Linux.
# On Linux, enables om-agent-sandbox by default unless --no-sandbox is passed.
# Refuses unverified downloads unless --allow-unsigned-dev is explicitly given.
set -eu
umask 022

OM_RELEASE_BASE_URL=${OM_RELEASE_BASE_URL:-https://release.om.network/om}
OM_APT_BASE_URL=${OM_APT_BASE_URL:-https://apt.onlymemes.com}
OM_KEY_FINGERPRINT=${OM_KEY_FINGERPRINT:-CE2FFD00E819213AF1A8394909055E4A462FA854}
OM_ARCHIVE_KEYRING=${OM_ARCHIVE_KEYRING:-}
OM_MINISIGN_PUBKEY=${OM_MINISIGN_PUBKEY:-}

VERSION="latest"
PREFIX="${HOME:-/tmp}/.local/opt/om"
BIN_DIR="${HOME:-/tmp}/.local/bin"
SYSTEM_INSTALL=0
SANDBOX=1
RUN_INIT=0
SPEND_OM=""
ALLOW_UNSIGNED_DEV=0
DRY_RUN=0
PRINT_PLATFORM=0
KEYRING_PATH="$OM_ARCHIVE_KEYRING"

say() {
  printf 'install-om: %s\n' "$*"
}

warn() {
  printf 'install-om: warning: %s\n' "$*" >&2
}

die() {
  printf 'install-om: error: %s\n' "$*" >&2
  exit 1
}

usage() {
  cat <<'EOF'
Usage: install-om.sh [OPTIONS]

Install the om Layer 2 Agent Control Plane (om, omd, om-desk, bundled Bun + MCP).

Options:
  --version <ver>        Release version to install (default: latest)
  --prefix <dir>         Install prefix (default: ~/.local/opt/om)
  --bin-dir <dir>        Symlink bin directory (default: ~/.local/bin)
  --system               Install system-wide on Linux via apt (/usr/bin)
  --no-sandbox           Opt out of Linux om-agent-sandbox (default-on on Linux)
  --init                 Run `om init --mcp` automatically after install
  --spend-om <amount>    Forward 24h OM spend allowance to `om init --mcp`
  --keyring <file>       Path to pinned OpenPGP keyring for SHA256SUMS.asc verification
  --allow-unsigned-dev   Allow local/unsigned dev archives (still checks SHA256SUMS)
  --dry-run              Print planned actions without modifying the system
  --print-platform       Print detected OS/arch target and exit
  -h, --help             Show this help message

Environment:
  OM_RELEASE_BASE_URL    Release mirror base URL (default: https://release.om.network/om)
  OM_APT_BASE_URL        APT repository base URL (default: https://apt.onlymemes.com)
  OM_KEY_FINGERPRINT     Pinned archive signing key fingerprint
  OM_ARCHIVE_KEYRING     Default OpenPGP keyring path
  OM_MINISIGN_PUBKEY     Optional minisign public key string/file
EOF
}

while [ $# -gt 0 ]; do
  case "$1" in
    --version)
      [ $# -ge 2 ] || die "--version requires a value"
      VERSION=$2
      shift 2
      ;;
    --version=*)
      VERSION=${1#--version=}
      shift
      ;;
    --prefix)
      [ $# -ge 2 ] || die "--prefix requires a path"
      PREFIX=$2
      shift 2
      ;;
    --prefix=*)
      PREFIX=${1#--prefix=}
      shift
      ;;
    --bin-dir)
      [ $# -ge 2 ] || die "--bin-dir requires a path"
      BIN_DIR=$2
      shift 2
      ;;
    --bin-dir=*)
      BIN_DIR=${1#--bin-dir=}
      shift
      ;;
    --system)
      SYSTEM_INSTALL=1
      shift
      ;;
    --no-sandbox)
      SANDBOX=0
      shift
      ;;
    --sandbox)
      SANDBOX=1
      shift
      ;;
    --init)
      RUN_INIT=1
      shift
      ;;
    --spend-om)
      [ $# -ge 2 ] || die "--spend-om requires an OM amount"
      SPEND_OM=$2
      shift 2
      ;;
    --spend-om=*)
      SPEND_OM=${1#--spend-om=}
      shift
      ;;
    --keyring)
      [ $# -ge 2 ] || die "--keyring requires a file path"
      KEYRING_PATH=$2
      shift 2
      ;;
    --keyring=*)
      KEYRING_PATH=${1#--keyring=}
      shift
      ;;
    --allow-unsigned-dev)
      ALLOW_UNSIGNED_DEV=1
      shift
      ;;
    --dry-run)
      DRY_RUN=1
      shift
      ;;
    --print-platform)
      PRINT_PLATFORM=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      die "unknown argument: $1 (try --help)"
      ;;
  esac
done

detect_platform() {
  raw_os=${OM_TEST_UNAME_S:-$(uname -s)}
  raw_arch=${OM_TEST_UNAME_M:-$(uname -m)}

  case "$raw_os" in
    Darwin) OS="darwin" ;;
    Linux)  OS="linux" ;;
    *)      die "unsupported operating system: $raw_os (supported: Darwin, Linux)" ;;
  esac

  case "$raw_arch" in
    arm64|aarch64) ARCH="arm64" ;;
    x86_64|amd64)  ARCH="x86_64" ;;
    *)             die "unsupported architecture: $raw_arch (supported: arm64, x86_64)" ;;
  esac

  case "$OS:$ARCH" in
    darwin:arm64)  TARGET="darwin-arm64" ;;
    darwin:x86_64) TARGET="darwin-x64" ;;
    linux:x86_64)  TARGET="linux-x64" ;;
    linux:arm64)   TARGET="linux-arm64" ;;
    *)             die "unsupported target combination: $OS/$ARCH" ;;
  esac
}

validate_base_url() {
  case "$OM_RELEASE_BASE_URL" in
    https://*)
      return 0
      ;;
    file://*|/*)
      if [ "$ALLOW_UNSIGNED_DEV" != 1 ]; then
        die "non-HTTPS release URL '$OM_RELEASE_BASE_URL' refused without --allow-unsigned-dev"
      fi
      return 0
      ;;
    *)
      die "release URL must use https:// (got '$OM_RELEASE_BASE_URL')"
      ;;
  esac
}

fetch_file() {
  src=$1
  dest=$2
  case "$src" in
    https://*)
      if command -v curl >/dev/null 2>&1; then
        curl -fsSL --proto '=https' --tlsv1.2 --retry 2 -o "$dest" "$src"
      elif command -v wget >/dev/null 2>&1; then
        wget --https-only --secure-protocol=TLSv1_2 -qO "$dest" "$src"
      else
        die "neither curl nor wget is installed"
      fi
      ;;
    file://*)
      local_path=${src#file://}
      [ -f "$local_path" ] || return 1
      cp -- "$local_path" "$dest"
      ;;
    /*)
      [ -f "$src" ] || return 1
      cp -- "$src" "$dest"
      ;;
    *)
      die "refusing non-HTTPS URL: $src"
      ;;
  esac
}

compute_sha256() {
  file=$1
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$file" | awk '{ print $1 }'
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$file" | awk '{ print $1 }'
  elif command -v openssl >/dev/null 2>&1; then
    openssl dgst -sha256 "$file" | awk '{ print $NF }'
  else
    die "no SHA-256 tool found (need sha256sum, shasum, or openssl)"
  fi
}

verify_signature() {
  sums_file=$1
  sig_file=$2
  minisig_file=$3

  if [ "$ALLOW_UNSIGNED_DEV" = 1 ]; then
    warn "skipping signature verification (--allow-unsigned-dev); SHA256SUMS will still be enforced"
    return 0
  fi

  # Prefer minisign if a minisign pubkey and .minisig are present.
  if [ -n "$OM_MINISIGN_PUBKEY" ] && [ -f "$minisig_file" ]; then
    command -v minisign >/dev/null 2>&1 || die "minisign is required to verify $minisig_file (or pass --allow-unsigned-dev for local dev)"
    if [ -f "$OM_MINISIGN_PUBKEY" ]; then
      minisign -Vm "$sums_file" -p "$OM_MINISIGN_PUBKEY" -x "$minisig_file" >/dev/null 2>&1 \
        || die "minisign signature verification FAILED for SHA256SUMS"
    else
      minisign -Vm "$sums_file" -P "$OM_MINISIGN_PUBKEY" -x "$minisig_file" >/dev/null 2>&1 \
        || die "minisign signature verification FAILED for SHA256SUMS"
    fi
    say "verified SHA256SUMS via minisign"
    return 0
  fi

  [ -f "$sig_file" ] || die "missing signature file SHA256SUMS.asc; refusing unverified download (use --allow-unsigned-dev for local dev only)"

  if [ -z "$KEYRING_PATH" ]; then
    for candidate in \
      /usr/share/keyrings/om-archive-keyring.gpg \
      /etc/apt/keyrings/om-archive-keyring.gpg \
      "${HOME:-/nonexistent}/.config/om/archive-keyring.gpg"; do
      if [ -f "$candidate" ]; then
        KEYRING_PATH=$candidate
        break
      fi
    done
  fi

  if [ -z "$KEYRING_PATH" ] || [ ! -f "$KEYRING_PATH" ]; then
    die "archive keyring not found (expected pinned fingerprint $OM_KEY_FINGERPRINT); pass --keyring <path> or --allow-unsigned-dev for local dev"
  fi

  if command -v gpg >/dev/null 2>&1; then
    if ! gpg --batch --show-keys --with-colons "$KEYRING_PATH" 2>/dev/null | grep -q "fpr:::::::::${OM_KEY_FINGERPRINT}:"; then
      die "keyring '$KEYRING_PATH' does not contain pinned fingerprint $OM_KEY_FINGERPRINT"
    fi
  fi

  if command -v gpgv >/dev/null 2>&1; then
    gpgv --keyring "$KEYRING_PATH" "$sig_file" "$sums_file" >/dev/null 2>&1 \
      || die "OpenPGP signature verification FAILED (gpgv) for SHA256SUMS"
    say "verified SHA256SUMS.asc via gpgv (pinned fingerprint $OM_KEY_FINGERPRINT)"
    return 0
  elif command -v gpg >/dev/null 2>&1; then
    gpg --batch --no-default-keyring --keyring "$KEYRING_PATH" --verify "$sig_file" "$sums_file" >/dev/null 2>&1 \
      || die "OpenPGP signature verification FAILED (gpg) for SHA256SUMS"
    say "verified SHA256SUMS.asc via gpg (pinned fingerprint $OM_KEY_FINGERPRINT)"
    return 0
  else
    die "neither gpgv nor gpg is installed to verify SHA256SUMS.asc; refusing unverified download (use --allow-unsigned-dev for local dev only)"
  fi
}

verify_checksum() {
  sums_file=$1
  archive_name=$2
  archive_file=$3

  expected=$(awk -v f="$archive_name" '
    $2 == f || $2 == ("*" f) || $2 == ("./" f) { print $1; exit }
  ' "$sums_file")
  [ -n "$expected" ] || die "archive '$archive_name' not listed in SHA256SUMS"
  actual=$(compute_sha256 "$archive_file")
  if [ "$actual" != "$expected" ]; then
    die "SHA-256 mismatch for $archive_name (expected $expected, got $actual)"
  fi
  say "verified SHA-256 for $archive_name"
}

resolve_archive_name() {
  sums_file=$1
  manifest_file=$2
  target=$3

  if [ -f "$manifest_file" ]; then
    # Extract archive filename for target from manifest.json if present.
    found=$(awk -v t="$target" '
      /"name"[[:space:]]*:/ {
        line = $0
        sub(/^.*"name"[[:space:]]*:[[:space:]]*"/, "", line)
        sub(/".*$/, "", line)
        if (index(line, t) > 0 && line ~ /\.tar\.gz$/) {
          print line
          exit
        }
      }
    ' "$manifest_file")
    if [ -n "$found" ]; then
      printf '%s\n' "$found"
      return 0
    fi
  fi

  found=$(awk -v t="$target" '
    {
      name = $2
      sub(/^\*/, "", name)
      sub(/^\.\//, "", name)
      if (index(name, t) > 0 && name ~ /\.tar\.gz$/) {
        print name
        exit
      }
    }
  ' "$sums_file")
  if [ -n "$found" ]; then
    printf '%s\n' "$found"
    return 0
  fi

  die "no tarball found for target '$target' in release manifest or SHA256SUMS"
}

detect_platform

if [ "$PRINT_PLATFORM" = 1 ]; then
  printf 'os=%s arch=%s target=%s\n' "$OS" "$ARCH" "$TARGET"
  exit 0
fi

validate_base_url

RELEASE_URL="${OM_RELEASE_BASE_URL%/}/${VERSION}"

if [ "$DRY_RUN" = 1 ]; then
  say "dry-run: os=$OS arch=$ARCH target=$TARGET"
  say "dry-run: release_url=$RELEASE_URL"
  if [ "$SYSTEM_INSTALL" = 1 ]; then
    say "dry-run: mode=system (apt /usr/bin)"
  else
    say "dry-run: prefix=$PREFIX bin_dir=$BIN_DIR"
  fi
  if [ "$ALLOW_UNSIGNED_DEV" = 1 ]; then
    say "dry-run: signature_verification=bypassed (--allow-unsigned-dev)"
  else
    say "dry-run: signature_verification=required (pinned fingerprint $OM_KEY_FINGERPRINT)"
  fi
  if [ "$OS" = "linux" ]; then
    if [ "$SANDBOX" = 1 ]; then
      say "dry-run: linux_agent_sandbox=enabled (default-on; pass --no-sandbox to opt out)"
    else
      say "dry-run: linux_agent_sandbox=disabled (--no-sandbox)"
    fi
  fi
  if [ "$RUN_INIT" = 1 ]; then
    say "dry-run: post_install=om init --mcp"
  fi
  exit 0
fi

if [ "$SYSTEM_INSTALL" = 1 ]; then
  [ "$OS" = "linux" ] || die "--system is supported on Linux only (macOS uses ~/.local/opt/om or Homebrew: brew install omnet/tap/om)"
  [ "$(id -u)" = 0 ] || die "--system requires root (re-run with sudo)"
  command -v apt-get >/dev/null 2>&1 || die "--system requires apt-get on Debian/Ubuntu"
  say "installing system packages via apt-get"
  apt-get update -q
  if [ "$SANDBOX" = 1 ]; then
    say "Linux om-agent-sandbox is enabled by default (pass --no-sandbox to opt out)"
    DEBIAN_FRONTEND=noninteractive apt-get install -y onlymemes-om om-agent-sandbox
  else
    say "Linux om-agent-sandbox disabled (--no-sandbox)"
    DEBIAN_FRONTEND=noninteractive apt-get install -y onlymemes-om
  fi
  if command -v om-setup >/dev/null 2>&1; then
    if [ "$SANDBOX" = 1 ]; then
      om-setup
    else
      om-setup --no-sandbox
    fi
  fi
  say "installed system om package (/usr/bin/om)"
  say "next: run 'om init --mcp'"
  exit 0
fi

WORK=$(mktemp -d "${TMPDIR:-/tmp}/install-om.XXXXXX")
cleanup() {
  rm -rf -- "$WORK"
}
trap cleanup EXIT INT TERM

say "detected $OS/$ARCH ($TARGET)"
say "fetching release metadata from $RELEASE_URL"

fetch_file "$RELEASE_URL/SHA256SUMS" "$WORK/SHA256SUMS" \
  || die "failed to download $RELEASE_URL/SHA256SUMS"

# manifest.json is optional if SHA256SUMS lists the tarball directly.
fetch_file "$RELEASE_URL/manifest.json" "$WORK/manifest.json" 2>/dev/null || true
fetch_file "$RELEASE_URL/SHA256SUMS.asc" "$WORK/SHA256SUMS.asc" 2>/dev/null || true
fetch_file "$RELEASE_URL/SHA256SUMS.minisig" "$WORK/SHA256SUMS.minisig" 2>/dev/null || true

verify_signature "$WORK/SHA256SUMS" "$WORK/SHA256SUMS.asc" "$WORK/SHA256SUMS.minisig"

ARCHIVE_NAME=$(resolve_archive_name "$WORK/SHA256SUMS" "$WORK/manifest.json" "$TARGET")
case "$ARCHIVE_NAME" in
  */*|*..*) die "invalid archive name in manifest/SHA256SUMS: $ARCHIVE_NAME" ;;
esac

say "downloading $ARCHIVE_NAME"
fetch_file "$RELEASE_URL/$ARCHIVE_NAME" "$WORK/$ARCHIVE_NAME" \
  || die "failed to download $RELEASE_URL/$ARCHIVE_NAME"

verify_checksum "$WORK/SHA256SUMS" "$ARCHIVE_NAME" "$WORK/$ARCHIVE_NAME"

mkdir -p "$WORK/extract"
tar -xzf "$WORK/$ARCHIVE_NAME" -C "$WORK/extract"

# Support both top-level prefix directory inside tarball and flat layout.
SRC_ROOT=""
if [ -x "$WORK/extract/bin/om" ]; then
  SRC_ROOT="$WORK/extract"
else
  for d in "$WORK/extract"/*; do
    if [ -d "$d" ] && [ -x "$d/bin/om" ]; then
      SRC_ROOT="$d"
      break
    fi
  done
fi
[ -n "$SRC_ROOT" ] || die "archive '$ARCHIVE_NAME' does not contain bin/om"

mkdir -p "$(dirname "$PREFIX")" "$BIN_DIR"
STAGE="${PREFIX}.stage.$$"
rm -rf -- "$STAGE"
mkdir -p "$STAGE"
cp -R "$SRC_ROOT"/. "$STAGE"/

# Atomic swap into $PREFIX.
if [ -e "$PREFIX" ]; then
  OLD="${PREFIX}.old.$$"
  rm -rf -- "$OLD"
  mv "$PREFIX" "$OLD"
  mv "$STAGE" "$PREFIX"
  rm -rf -- "$OLD"
else
  mv "$STAGE" "$PREFIX"
fi

# Link CLI/daemon binaries into $BIN_DIR.
for bin_name in om omd om-desk om-setup; do
  if [ -e "$PREFIX/bin/$bin_name" ]; then
    ln -sf "$PREFIX/bin/$bin_name" "$BIN_DIR/$bin_name"
  fi
done

say "installed om into $PREFIX (linked in $BIN_DIR)"

# Linux default-on om-agent-sandbox handling.
if [ "$OS" = "linux" ]; then
  if [ "$SANDBOX" = 1 ]; then
    say "Linux om-agent-sandbox is enabled by default (pass --no-sandbox to opt out)"
    if [ "$(id -u)" = 0 ]; then
      if command -v om-setup >/dev/null 2>&1; then
        om-setup
      elif [ -x /usr/sbin/om-setup ]; then
        /usr/sbin/om-setup
      elif [ -x /usr/lib/onlymemes-agent-sandbox/om-agent-user.sh ]; then
        /usr/lib/onlymemes-agent-sandbox/om-agent-user.sh apply --profile host --yes --no-start
      else
        say "note: install om-agent-sandbox and run 'sudo om-setup' to activate om-agent isolation"
      fi
    else
      say "to enable kernel/user om-agent-sandbox isolation on Linux, run: sudo om-setup"
    fi
  else
    say "Linux om-agent-sandbox disabled (--no-sandbox)"
  fi
fi

# PATH guidance if BIN_DIR is not on PATH.
case ":${PATH:-}:" in
  *":$BIN_DIR:"*) ;;
  *)
    say "add $BIN_DIR to your PATH:"
    # shellcheck disable=SC2016
    printf '  export PATH="%s:$PATH"\n' "$BIN_DIR"
    ;;
esac

run_init_cmd() {
  set -- "$BIN_DIR/om" init --mcp
  if [ -n "$SPEND_OM" ]; then
    set -- "$@" --spend-om "$SPEND_OM"
  fi
  if [ "$SANDBOX" = 0 ]; then
    set -- "$@" --no-sandbox
  fi
  say "running: $*"
  "$@"
}

if [ "$RUN_INIT" = 1 ]; then
  run_init_cmd
elif [ -t 0 ] && [ -t 1 ]; then
  printf "Run 'om init --mcp' now to initialize your identity and configure MCP clients? [Y/n] "
  IFS= read -r answer || answer="n"
  case "$answer" in
    ""|[Yy]|[Yy][Ee][Ss])
      run_init_cmd
      ;;
    *)
      say "next: run 'om init --mcp' when ready"
      ;;
  esac
else
  say "next: run 'om init --mcp'"
fi
