#!/bin/sh
# Crashdock installer/upgrader — single-pipe usage:
#   curl -fsSL https://<stable>/crashdock-install.sh | sudo sh
#   curl -fsSL https://<stable>/crashdock-install.sh | sudo sh -s -- --force
#
# One command, no follow-up steps. Handles fresh installs, upgrades, and
# fleet -> crashdock migration:
#   - downloads + checksum-verifies the crashdock 0.4.0 binary for this arch
#   - stages it atomically at /usr/local/bin/crashdock (ETXTBSY-safe)
#   - migration: an existing fleet install (fleet.service and/or
#     /usr/local/bin/fleet) is stopped, its data dir moved
#     /fleet-data -> /crashdock-data, crashdock.service installed from the
#     old unit's flags, /meshfleet forwarding kept and /crashdock added;
#     any health-check failure rolls back to the fleet service
#   - fresh install: runs `crashdock --install --endpoint /crashdock`
#     (service unit, data dir, /crashdock reverse-proxy forwarding,
#     enroll key, starts service)
#   - upgrade: preserves /crashdock-data and the controller identity;
#     restarts the service
#   - ensures the server's own subnet can reach the controller UI
#     (user-overridable; never clobbers a hand-edited file)
set -eu

# --force: skip the "already at this version" short-circuit and reinstall.
FORCE=0
for arg in "$@"; do
  case "$arg" in
    --force|-f) FORCE=1 ;;
  esac
done

CRASHDOCK_VERSION="0.4.0"
URL_AARCH64="https://crashproof.press/projects/crashdock/releases/crashdock-0.4.0-aarch64-linux-musl"
URL_X86_64="https://crashproof.press/projects/crashdock/releases/crashdock-0.4.0-x86_64-linux-musl"
SHA_AARCH64="4924d7451048d75179ccbb40dd30e2aaa84a168eb0c0578df326b5454832750e"
SHA_X86_64="caa5eea141087421d77e7580fab859b00f55b0fac32b814a32cbf9b8101834ec"
INSTALL_PATH="/usr/local/bin/crashdock"
UNIT="crashdock.service"
OLD_INSTALL_PATH="/usr/local/bin/fleet"
OLD_UNIT="fleet.service"
OLD_DATA_DEFAULT="/fleet-data"
NEW_DATA_DIR="/crashdock-data"
SUBNET_CONF_NAME="crashdock-subnet-access.conf"

log() { echo "[crashdock-install] $*"; }
fail() { echo "[crashdock-install] ERROR: $*" >&2; exit 1; }

# Must run as root (systemd unit + /usr/local/bin writes).
[ "$(id -u)" = "0" ] || fail "run as root (e.g. curl ... | sudo sh)"

# Detect architecture.
ARCH="$(uname -m)"
case "$ARCH" in
  x86_64)  BIN_URL="$URL_X86_64";  EXPECT_SHA="$SHA_X86_64" ;;
  aarch64) BIN_URL="$URL_AARCH64"; EXPECT_SHA="$SHA_AARCH64" ;;
  *) fail "unsupported architecture: $ARCH" ;;
esac
case "$BIN_URL" in __URL_*|"") fail "download URL not set for $ARCH" ;; esac
case "$EXPECT_SHA" in __SHA_*|"") fail "checksum not set for $ARCH" ;; esac

# If the installed binary already reports this version, only ensure the
# service is healthy — don't re-download. (--force skips this check.)
if [ "$FORCE" -eq 0 ] && [ -x "$INSTALL_PATH" ]; then
  INSTALLED_VER="$("$INSTALL_PATH" --version 2>/dev/null | awk '{print $2}')" || INSTALLED_VER=""
  if [ "$INSTALLED_VER" = "$CRASHDOCK_VERSION" ]; then
    log "crashdock $CRASHDOCK_VERSION already installed at $INSTALL_PATH"
    if command -v systemctl >/dev/null 2>&1 && systemctl is-active --quiet "$UNIT" 2>/dev/null; then
      log "service $UNIT is active; nothing to do"
      exit 0
    fi
    log "service $UNIT not active; continuing to (re)start it"
  fi
fi

# Download to temp.
TMP_BIN="$(mktemp /tmp/crashdock-install.XXXXXX)"
trap 'rm -f "$TMP_BIN"' EXIT
# Download with retry: transient network corruption happens; retry the
# download (up to 3 attempts) when the checksum does not match.
attempt=1
while [ "$attempt" -le 3 ]; do
  log "downloading crashdock $CRASHDOCK_VERSION ($ARCH)... (attempt $attempt/3)"
  if curl -fsSL "$BIN_URL" -o "$TMP_BIN"; then
    log "verifying checksum..."
    if echo "$EXPECT_SHA  $TMP_BIN" | sha256sum -c - >/dev/null 2>&1; then
      log "checksum OK"
      break
    fi
    log "WARNING: checksum mismatch on attempt $attempt; retrying..."
  else
    log "WARNING: download failed on attempt $attempt; retrying..."
  fi
  attempt=$((attempt + 1))
  [ "$attempt" -le 3 ] && sleep 2
done
[ "$attempt" -gt 3 ] && fail "download/checksum failed after 3 attempts \u2014 refusing to install"
chmod +x "$TMP_BIN"

# Stage the binary: copy aside + rename into place (atomic; works while
# the old binary is still executing — no ETXTBSY).
log "staging $INSTALL_PATH..."
cp "$TMP_BIN" "$INSTALL_PATH.new" || fail "copy failed"
mv "$INSTALL_PATH.new" "$INSTALL_PATH" || fail "rename failed"
log "staged: $("$INSTALL_PATH" --version)"

HAS_SYSTEMD=0
command -v systemctl >/dev/null 2>&1 && HAS_SYSTEMD=1

# --- fleet -> crashdock migration ---------------------------------------
# Detected when the old unit file or the old binary exists and this host is
# not already running the crashdock service.
OLD_UNIT_PATH="/etc/systemd/system/$OLD_UNIT"
UNIT_PATH="/etc/systemd/system/$UNIT"
MIGRATED=0
if [ "$HAS_SYSTEMD" -eq 1 ] && { [ -f "$OLD_UNIT_PATH" ] || [ -x "$OLD_INSTALL_PATH" ]; } \
   && ! systemctl is-active --quiet "$UNIT" 2>/dev/null; then
  MIGRATED=1
  log "existing fleet install detected; migrating to crashdock..."

  # Data dir from the old service's cmdline (never `pgrep -f fleet`).
  OLD_DATA_DIR=""
  if systemctl is-active --quiet "$OLD_UNIT" 2>/dev/null; then
    OLD_PID="$(systemctl show "$OLD_UNIT" -p MainPID --value 2>/dev/null)" || OLD_PID=""
    if [ -n "$OLD_PID" ] && [ "$OLD_PID" != "0" ]; then
      OLD_DATA_DIR="$(tr '\0' '\n' < "/proc/$OLD_PID/cmdline" 2>/dev/null | grep -A1 '^--data-dir$' | tail -1)"
      if [ -z "$OLD_DATA_DIR" ]; then
        OLD_DATA_DIR="$(tr '\0' '\n' < "/proc/$OLD_PID/cmdline" 2>/dev/null | grep '^--data-dir=' | cut -d= -f2)"
      fi
    fi
  fi
  [ -n "$OLD_DATA_DIR" ] || OLD_DATA_DIR="$OLD_DATA_DEFAULT"
  log "old data dir: $OLD_DATA_DIR"

  rollback() {
    log "ROLLBACK: restoring fleet service..."
    systemctl stop "$UNIT" 2>/dev/null || true
    systemctl disable "$UNIT" 2>/dev/null || true
    if [ "$DATA_MOVED" = "1" ]; then
      mv "$NEW_DATA_DIR" "$OLD_DATA_DIR" || log "WARNING: could not move data dir back; do it manually"
    fi
    systemctl enable "$OLD_UNIT" 2>/dev/null || true
    systemctl start "$OLD_UNIT" 2>/dev/null || true
    fail "migration failed ($1); fleet service restored"
  }

  DATA_MOVED=0
  # 1. Stop + disable the old service (unit file kept for rollback).
  log "stopping $OLD_UNIT..."
  systemctl stop "$OLD_UNIT" 2>/dev/null || log "WARNING: stop $OLD_UNIT failed (may not have been running)"
  systemctl disable "$OLD_UNIT" 2>/dev/null || true

  # 2. Move the data dir (same filesystem: atomic rename). Identity
  #    (controller.key, device keys, enrollment) moves with it.
  if [ -d "$NEW_DATA_DIR" ] && [ ! -d "$OLD_DATA_DIR" ]; then
    log "$NEW_DATA_DIR already exists; skipping data move"
  elif [ -d "$OLD_DATA_DIR" ]; then
    [ -e "$NEW_DATA_DIR" ] && rollback "$NEW_DATA_DIR already exists; refusing to clobber"
    log "moving $OLD_DATA_DIR -> $NEW_DATA_DIR..."
    mv "$OLD_DATA_DIR" "$NEW_DATA_DIR" || rollback "data dir move failed"
    DATA_MOVED=1
  else
    rollback "no data dir found at $OLD_DATA_DIR"
  fi
  [ -f "$NEW_DATA_DIR/controller.key" ] || rollback "identity missing: $NEW_DATA_DIR/controller.key"

  # 3. Build the new unit from the old one's flags (binary path, data dir,
  #    description and managed marker updated). The old unit file is kept
  #    on disk (disabled) for rollback.
  if [ -f "$OLD_UNIT_PATH" ]; then
    log "writing $UNIT_PATH from $OLD_UNIT_PATH..."
    cp "$OLD_UNIT_PATH" "/root/$OLD_UNIT.bak-$(date +%Y%m%d%H%M%S)" || rollback "could not back up old unit"
    sed -e "s|$OLD_INSTALL_PATH|$INSTALL_PATH|g" \
        -e "s|$OLD_DATA_DIR|$NEW_DATA_DIR|g" \
        -e "s|^Description=.*|Description=Crashdock unified node (controller+agent)|" \
        -e "s|Managed by fleet install|Managed by crashdock install|" \
        -e "s|re-run \`fleet install\`|re-run \`crashdock install\`|g" \
        "$OLD_UNIT_PATH" > "$UNIT_PATH" || rollback "unit transform failed"
    grep -q "Managed by crashdock install" "$UNIT_PATH" || rollback "managed marker missing in new unit"
    grep -q "$INSTALL_PATH" "$UNIT_PATH" || rollback "new binary path missing in new unit"
  else
    rollback "old unit $OLD_UNIT_PATH not found; cannot derive service flags"
  fi

  # 4. Start the new service.
  log "reloading systemd and starting $UNIT..."
  systemctl daemon-reload
  systemctl enable "$UNIT" || rollback "enable $UNIT failed"
  systemctl start "$UNIT" || rollback "start $UNIT failed"
  sleep 3
  systemctl is-active --quiet "$UNIT" || rollback "service did not stay active"
  NEW_PID="$(systemctl show "$UNIT" -p MainPID --value)"
  { [ -n "$NEW_PID" ] && [ "$NEW_PID" != "0" ]; } || rollback "no MainPID for $UNIT"
  log "service running (PID $NEW_PID)"
  [ -f "$NEW_DATA_DIR/controller.key" ] || rollback "identity missing after start"
  log "identity preserved: $NEW_DATA_DIR/controller.key"

  # 5. Forwarding: /meshfleet stays exactly as-is (enrolled agents depend
  #    on it); add /crashdock as the renamed product path. Apache site
  #    configs are backed up first; /meshfleet presence is re-verified
  #    after.
  APACHE_BAK="/root/apache-conf.bak-$(date +%Y%m%d%H%M%S)"
  mkdir -p "$APACHE_BAK"
  APACHE_TOUCHED=0
  for d in /etc/apache2/sites-enabled /etc/httpd/conf.d /etc/apache2/conf-enabled; do
    if [ -d "$d" ]; then
      for f in "$d"/*; do
        if [ -f "$f" ] && grep -q "fleet-forwarding" "$f" 2>/dev/null; then
          cp "$f" "$APACHE_BAK/" && APACHE_TOUCHED=1
        fi
      done
    fi
  done
  [ "$APACHE_TOUCHED" = "1" ] && log "apache configs backed up to $APACHE_BAK"
  ENROLL_FLAG=""
  if [ -f "$NEW_DATA_DIR/remote-enroll.key" ]; then
    ENROLL_FLAG="--enroll-proxy"
    log "enroll key found; requesting --enroll-proxy for /crashdock"
  fi
  if "$INSTALL_PATH" enable-forwarding --endpoint /crashdock --data-dir "$NEW_DATA_DIR" $ENROLL_FLAG; then
    log "/crashdock forwarding installed"
  else
    log "WARNING: enable-forwarding --endpoint /crashdock failed; /meshfleet is untouched — run it manually"
  fi
  # Verify /meshfleet survived.
  MESHFLEET_OK=0
  for d in /etc/apache2/sites-enabled /etc/httpd/conf.d /etc/apache2/conf-enabled; do
    if [ -d "$d" ]; then
      for f in "$d"/*; do
        if [ -f "$f" ] && grep -q "location /meshfleet/" "$f" 2>/dev/null; then MESHFLEET_OK=1; fi
      done
    fi
  done
  [ "$MESHFLEET_OK" = "1" ] || { log "WARNING: /meshfleet forwarding not found after enable-forwarding; restoring apache backup"; cp "$APACHE_BAK"/* /etc/apache2/sites-enabled/ 2>/dev/null || true; }

  # 6. Same-subnet UI access for the new endpoint (old conf left in place).
  #    (ensure_subnet_access defined below; called here for /crashdock.)
  log "migration complete: fleet -> crashdock $CRASHDOCK_VERSION"
fi

# --- same-subnet UI access (Apache) -------------------------------------
# Allows the server's own subnet to reach the controller UI at the given
# endpoint by default; the file documents how to override it. Never
# overwrites a file the user has hand-edited: only writes when missing,
# or when the content is exactly what a previous installer run wrote.

# Detect the server's primary subnet from the default-route interface.
detect_subnet() {
  local src_ip
  src_ip="$(ip route get 1.1.1.1 2>/dev/null | grep -o 'src [0-9.]*' | awk '{print $2}')" || true
  [ -n "$src_ip" ] || return 0
  ip -o -f inet addr show 2>/dev/null | grep -w "$src_ip" | grep -o 'inet [0-9./]*' | awk '{print $2}' | head -1
}

# Find an Apache conf dir across distros.
apache_conf_dir() {
  for d in /etc/apache2/conf.d /etc/httpd/conf.d /etc/apache2/conf-available; do
    [ -d "$d" ] && { echo "$d"; return 0; }
  done
  return 1
}

# Render the managed file content for a given endpoint+subnet.
subnet_conf_body() {
  local endpoint="$1" subnet="$2"
  cat <<EOF
# $SUBNET_CONF_NAME — managed by crashdock-install.sh.
# Allows the server's local subnet ($subnet) to reach the Crashdock controller UI.
# To override: edit or delete this file, then reload Apache
#   apachectl graceful   (or: httpd -k graceful)
# The installer only rewrites this file when it is missing or still holds
# installer-written content; hand edits are left alone.
<Location $endpoint/>
    Require ip $subnet
</Location>
EOF
}

ensure_subnet_access() {
  local endpoint="${1:-/crashdock}"
  local conf_dir conf_file subnet want cur
  conf_dir="$(apache_conf_dir)" || { log "no Apache conf dir found; skipping subnet access rules"; return 0; }
  conf_file="$conf_dir/$SUBNET_CONF_NAME"
  subnet="$(detect_subnet)" || subnet=""
  if [ -z "$subnet" ]; then
    log "could not detect subnet; skipping subnet access rules"
    return 0
  fi
  want="$(subnet_conf_body "$endpoint" "$subnet")"
  if [ -f "$conf_file" ]; then
    cur="$(cat "$conf_file")"
    # If the file holds installer content for a *different* subnet (e.g.
    # the server moved networks), refresh it; if the user hand-edited it,
    # leave it alone.
    case "$cur" in
      *"$SUBNET_CONF_NAME — managed by crashdock-install.sh."*)
        if [ "$cur" = "$want" ]; then
          log "subnet access already configured for $subnet"
          return 0
        fi
        log "refreshing $conf_file for subnet $subnet"
        ;;
      *)
        log "$conf_file looks hand-edited; leaving it alone"
        return 0
        ;;
    esac
  else
    log "allowing subnet $subnet to reach $endpoint/ (override: edit $conf_file)"
  fi
  printf '%s\n' "$want" > "$conf_file" || fail "could not write $conf_file"

  # Reload Apache if it's running. Exact-name match only — never `pgrep -f`.
  local reloaded=0
  if pgrep -x apache2 >/dev/null 2>&1 || pgrep -x httpd >/dev/null 2>&1; then
    if command -v apachectl >/dev/null 2>&1; then
      if apachectl graceful 2>&1; then reloaded=1; else log "WARNING: apachectl graceful failed; run it manually"; fi
    elif command -v httpd >/dev/null 2>&1; then
      if httpd -k graceful 2>&1; then reloaded=1; else log "WARNING: httpd -k graceful failed; run it manually"; fi
    else
      log "WARNING: apache running but no apachectl/httpd found; reload manually"
    fi
    [ "$reloaded" = "1" ] && log "apache reloaded"
  else
    log "apache not running; rules take effect on next start"
  fi
}

# --- fresh install vs upgrade (non-migration) ---------------------------
if [ "$MIGRATED" -eq 1 ]; then
  log "migration path handled the service; skipping upgrade/fresh-install block"
elif [ "$HAS_SYSTEMD" -eq 1 ] && [ -f "$UNIT_PATH" ]; then
  if systemctl is-active --quiet "$UNIT" 2>/dev/null; then
    # --- upgrade path: keep data dir + identity, restart service ---
    log "reloading systemd and restarting $UNIT..."
    systemctl daemon-reload
    systemctl restart "$UNIT"
    sleep 3
    NEW_PID="$(systemctl show "$UNIT" -p MainPID --value)"
    [ -n "$NEW_PID" ] && [ "$NEW_PID" != "0" ] || fail "service did not start; see: systemctl status $UNIT"
    log "service running (PID $NEW_PID)"
    [ -f "$NEW_DATA_DIR/controller.key" ] || fail "data dir identity missing: $NEW_DATA_DIR/controller.key"
    log "identity preserved: $NEW_DATA_DIR/controller.key"
  fi
elif [ ! -f "$OLD_UNIT_PATH" ]; then
  # --- fresh install: let the binary do the full one-shot setup ---
  # (service unit, data dir, /crashdock forwarding, enroll key, start).
  log "no existing install; running one-shot install..."
  "$INSTALL_PATH" --install --endpoint /crashdock || fail "crashdock --install failed"
  log "fresh install complete"
fi

ensure_subnet_access "/crashdock"

log "done: crashdock $CRASHDOCK_VERSION"
