#!/usr/bin/env bash
# Install the LNS CLI (lns).
#
#   curl -fsSL https://get.lns.run | bash
#   curl -fsSL https://get.lns.run | VERSION=0.1.0 bash
#
# INSTALL_DIR     target directory (default: ~/.local/bin)
# VERSION         specific release (default: latest)
# CDN_BASE        override CDN origin (default: https://get.lns.run)
# LNS_NO_SERVICE  set to 1 to skip starting + enabling the login auto-start service
# APPARMOR_DIR    where Linux AppArmor profiles go (default: /etc/apparmor.d)

set -euo pipefail

CDN_BASE="${CDN_BASE:-https://get.lns.run}"
APPARMOR_DIR="${APPARMOR_DIR:-/etc/apparmor.d}"
BINARY_NAME="lns"
SERVICE_BINARY_NAME="lns-service"
MANIFEST_NAME="lns-latest.json"

LNS_INSTALL_VERSION="0.9.0"

# Sent on every CDN request to correlate install volume and detect stale curl|sh pipelines.
USER_AGENT="lns-install/${LNS_INSTALL_VERSION} (os=$(uname -s); arch=$(uname -m); kernel=$(uname -s)/$(uname -r); shell=$(basename "${SHELL:-unknown}"); method=install-script)"

if [ -t 1 ] && command -v tput >/dev/null 2>&1 && [ "$(tput colors 2>/dev/null || echo 0)" -ge 8 ]; then
  BOLD=$(tput bold)
  RED=$(tput setaf 1)
  GREEN=$(tput setaf 2)
  YELLOW=$(tput setaf 3)
  RESET=$(tput sgr0)
else
  BOLD="" RED="" GREEN="" YELLOW="" RESET=""
fi

info()  { printf "%s[info]%s  %s\n" "$GREEN" "$RESET" "$1"; }
warn()  { printf "%s[warn]%s  %s\n" "$YELLOW" "$RESET" "$1" >&2; }
error() { printf "%s[error]%s %s\n" "$RED" "$RESET" "$1" >&2; exit 1; }

# Opt out via LNS_NO_SERVICE=1 (the curl|bash path has no argv) or --no-service.
NO_SERVICE="${LNS_NO_SERVICE:-}"
for arg in "$@"; do
  case "$arg" in
    --no-service) NO_SERVICE=1 ;;
  esac
done

download() {
  local url="$1" dest="$2"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL -A "$USER_AGENT" -o "$dest" "$url"
  elif command -v wget >/dev/null 2>&1; then
    wget --user-agent="$USER_AGENT" -q -O "$dest" "$url"
  else
    error "Either curl or wget is required."
  fi
}

fetch() {
  local url="$1"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL -A "$USER_AGENT" "$url"
  elif command -v wget >/dev/null 2>&1; then
    wget --user-agent="$USER_AGENT" -qO- "$url"
  else
    error "Either curl or wget is required."
  fi
}

apparmor_profile() {
  local name="$1" binary="$2"
  printf 'abi <abi/4.0>,\ninclude <tunables/global>\n\nprofile %s %s{,.avx2} flags=(unconfined) {\n  userns,\n}\n' "$name" "$binary"
}

only_root_can_change() {
  local path stat_out
  for path in "$1" "$(dirname "$1")"; do
    stat_out=$(stat -c '%u %a' "$path" 2>/dev/null) || return 1
    [ "${stat_out% *}" = 0 ] || return 1
    (( (8#${stat_out#* } & 8#022) == 0 )) || return 1
  done
}

allow_user_namespaces() {
  local name="$1" binary="$2" consequence="$3" profile wanted other staged
  [ -n "$binary" ] || return 0
  binary=$(readlink -f "$binary")
  if ! only_root_can_change "$binary"; then
    warn "${binary} is not owned by root, or other users can change it, so a profile for it would let any of your programs create user namespaces. Install it in a directory that only root can change, such as /usr/bin, and run this installer again. ${consequence} until then."
    return 0
  fi
  profile="${APPARMOR_DIR}/${name}"
  wanted=$(apparmor_profile "$name" "$binary")
  if [ -f "$profile" ] && [ "$(cat "$profile")" = "$wanted" ]; then
    return 0
  fi
  other=$(grep -rlsF -- "$binary" "$APPARMOR_DIR" | grep -vxF -- "$profile" | head -n 1 || true)
  if [ -n "$other" ]; then
    grep -qs '^[[:space:]]*userns,' "$other" && return 0
    warn "The AppArmor profile ${other} confines ${binary} and does not allow user namespaces. ${consequence} until it allows them."
    return 0
  fi
  info "This system lets a program create user namespaces only under an AppArmor profile. ${binary} needs them to sandbox itself."
  info "Adding the AppArmor profile ${name} (requires sudo)..."
  staged=$(mktemp)
  printf '%s\n' "$wanted" > "$staged"
  # The profile lands only once it loads, so a profile that failed to load is retried by the next install.
  if sudo apparmor_parser -r "$staged" && sudo install -m 0644 "$staged" "$profile"; then
    info "Added the AppArmor profile ${name}."
  else
    warn "Could not add the AppArmor profile for ${binary}. ${consequence} until it is added. Run this installer again to retry."
  fi
  rm -f "$staged"
}

detect_os() {
  local os
  os=$(uname -s | tr '[:upper:]' '[:lower:]')
  case "$os" in
    darwin) echo "darwin" ;;
    linux)  echo "linux" ;;
    *)      error "Unsupported operating system: $os" ;;
  esac
}

detect_arch() {
  # Darwin reports `arm64`; rewrite to `aarch64` to match Rust target_arch and tarball filenames.
  local arch
  arch=$(uname -m)
  case "$arch" in
    x86_64|amd64)  echo "x86_64" ;;
    arm64|aarch64) echo "aarch64" ;;
    *)             error "Unsupported architecture: $arch" ;;
  esac
}

OS=$(detect_os)
ARCH=$(detect_arch)
PLATFORM="${OS}-${ARCH}"

# Reject Intel Macs early — libkrun requires Apple Silicon; the binary would install but fail on first run.
if [ "$OS" = "darwin" ] && [ "$ARCH" != "aarch64" ]; then
  error "lns requires Apple Silicon (M-series) on macOS — Intel Macs cannot host the guest VM."
fi

if [ -n "${VERSION:-}" ]; then
  VERSION="${VERSION#v}"
else
  info "Resolving latest version..."
  MANIFEST=$(fetch "${CDN_BASE}/${MANIFEST_NAME}") || \
    error "Failed to fetch ${CDN_BASE}/${MANIFEST_NAME}"
  # Prefer jq; the awk fallback guards against a value literally equal to "version"
  # being mistaken for the key, and strips \r in case a proxy rewrites line endings.
  if command -v jq >/dev/null 2>&1; then
    VERSION=$(printf '%s' "$MANIFEST" | jq -r '.version // empty')
  else
    VERSION=$(printf '%s\n' "$MANIFEST" | tr -d '\r' | \
      awk -F'"' '{ for (i=1; i<NF; i++) if ($i == "version" && $(i+1) ~ /^[[:space:]]*:[[:space:]]*$/) { print $(i+2); exit } }')
  fi
  [ -n "$VERSION" ] || error "Could not parse version from manifest."
fi

info "Installing ${BOLD}${BINARY_NAME} ${VERSION}${RESET} for ${PLATFORM}"

ASSET_NAME="lns-${VERSION}-${PLATFORM}.tar.gz"
ASSET_URL="${CDN_BASE}/${ASSET_NAME}"
CHECKSUM_URL="${ASSET_URL}.sha256"

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

info "Downloading ${ASSET_NAME}..."
download "$ASSET_URL" "${TMPDIR_INSTALL}/${ASSET_NAME}" || \
  error "Failed to download ${ASSET_URL}"

info "Verifying checksum..."
download "$CHECKSUM_URL" "${TMPDIR_INSTALL}/${ASSET_NAME}.sha256" || \
  error "Failed to download ${CHECKSUM_URL}"

EXPECTED=$(awk '{print $1}' "${TMPDIR_INSTALL}/${ASSET_NAME}.sha256")
[ -n "$EXPECTED" ] || error "Checksum file at ${CHECKSUM_URL} is empty or malformed."

if command -v sha256sum >/dev/null 2>&1; then
  ACTUAL=$(sha256sum "${TMPDIR_INSTALL}/${ASSET_NAME}" | awk '{print $1}')
elif command -v shasum >/dev/null 2>&1; then
  ACTUAL=$(shasum -a 256 "${TMPDIR_INSTALL}/${ASSET_NAME}" | awk '{print $1}')
else
  error "Neither sha256sum nor shasum is available — cannot verify download integrity. Install GNU coreutils or perl-shasum and retry."
fi

[ "$ACTUAL" = "$EXPECTED" ] || error "Checksum mismatch!
  Expected: ${EXPECTED}
  Got:      ${ACTUAL}"
info "Checksum OK."

INSTALL_DIR="${INSTALL_DIR:-${HOME}/.local/bin}"
INSTALL_DIR="${INSTALL_DIR%/}"

tar xzf "${TMPDIR_INSTALL}/${ASSET_NAME}" -C "${TMPDIR_INSTALL}"
[ -f "${TMPDIR_INSTALL}/${BINARY_NAME}" ] || \
  error "Tarball ${ASSET_NAME} did not contain ${BINARY_NAME} at the top level."

HAS_SERVICE=true
if [ ! -f "${TMPDIR_INSTALL}/${SERVICE_BINARY_NAME}" ]; then
  warn "Tarball does not contain ${SERVICE_BINARY_NAME} (older release?). Skipping service binary."
  HAS_SERVICE=false
fi

if [ ! -d "${INSTALL_DIR}" ]; then
  if ! mkdir -p "${INSTALL_DIR}" 2>/dev/null; then
    info "Creating ${INSTALL_DIR} (requires sudo)..."
    sudo mkdir -p "${INSTALL_DIR}" || error "Failed to create install directory ${INSTALL_DIR} with sudo."
  fi
fi

if ! install -m 0755 "${TMPDIR_INSTALL}/${BINARY_NAME}" "${INSTALL_DIR}/${BINARY_NAME}" 2>/dev/null; then
  info "Installing to ${INSTALL_DIR} (requires sudo)..."
  sudo install -m 0755 "${TMPDIR_INSTALL}/${BINARY_NAME}" "${INSTALL_DIR}/${BINARY_NAME}" || \
    error "Failed to install ${BINARY_NAME} to ${INSTALL_DIR} with sudo."
fi

if [ "$HAS_SERVICE" = true ]; then
  if ! install -m 0755 "${TMPDIR_INSTALL}/${SERVICE_BINARY_NAME}" "${INSTALL_DIR}/${SERVICE_BINARY_NAME}" 2>/dev/null; then
    info "Installing ${SERVICE_BINARY_NAME} to ${INSTALL_DIR} (requires sudo)..."
    sudo install -m 0755 "${TMPDIR_INSTALL}/${SERVICE_BINARY_NAME}" "${INSTALL_DIR}/${SERVICE_BINARY_NAME}" || \
      error "Failed to install ${SERVICE_BINARY_NAME} to ${INSTALL_DIR} with sudo."
  fi
  info "Installed ${BOLD}${BINARY_NAME}${RESET} and ${BOLD}${SERVICE_BINARY_NAME}${RESET} to ${INSTALL_DIR}/"
else
  info "Installed ${BOLD}${BINARY_NAME}${RESET} to ${INSTALL_DIR}/${BINARY_NAME}"
fi

case ":${PATH}:" in
  *":${INSTALL_DIR}:"*) ;;
  *)
    CURRENT_SHELL=$(basename "${SHELL:-/bin/sh}")
    case "$CURRENT_SHELL" in
      fish)
        SNIPPET="fish_add_path ${INSTALL_DIR}"
        RC_FILE="~/.config/fish/config.fish"
        ;;
      zsh)
        SNIPPET="export PATH=\"${INSTALL_DIR}:\$PATH\""
        RC_FILE="~/.zshrc"
        ;;
      *)
        SNIPPET="export PATH=\"${INSTALL_DIR}:\$PATH\""
        RC_FILE="~/.bashrc"
        ;;
    esac
    echo ""
    warn "${INSTALL_DIR} is not in your PATH. Add this to ${RC_FILE}:"
    echo ""
    echo "    ${SNIPPET}"
    echo ""
    echo "  Or to use ${BINARY_NAME} in this shell right now, run that same line."
    echo ""
    ;;
esac

# Warn (not error): the binary is still useful for `lns audit`, `lns --help`, etc. without KVM.
if [ "$OS" = "linux" ] && [ ! -e /dev/kvm ]; then
  warn "/dev/kvm is not available. \`${BINARY_NAME} run\` will fail to launch a guest VM."
  echo "  Check that:"
  echo "    - the kernel supports KVM (modprobe kvm_intel | kvm_amd)"
  echo "    - hardware virtualisation is enabled in BIOS/UEFI"
  echo "    - your user can access /dev/kvm (usually: sudo usermod -aG kvm \$USER)"
  echo ""
fi

# On Linux lns drives an out-of-process cloud-hypervisor + virtiofsd + passt; probe PATH (honoring the
# LNS_*_BIN overrides) so users get a clear pointer instead of a run-time "not found on PATH" error.
if [ "$OS" = "linux" ]; then
  find_virtiofsd() {
    if [ -n "${LNS_VIRTIOFSD_BIN:-}" ] && [ -x "${LNS_VIRTIOFSD_BIN}" ]; then
      printf '%s\n' "${LNS_VIRTIOFSD_BIN}"
      return
    fi
    if command -v virtiofsd >/dev/null 2>&1; then
      command -v virtiofsd
      return
    fi
    for dir in /usr/libexec /usr/lib/virtiofsd /usr/lib/qemu; do
      if [ -x "$dir/virtiofsd" ]; then
        printf '%s\n' "$dir/virtiofsd"
        return
      fi
    done
    return 1
  }

  MISSING_VMM=""
  if [ -z "${LNS_CLOUD_HYPERVISOR_BIN:-}" ] && ! command -v cloud-hypervisor >/dev/null 2>&1; then
    MISSING_VMM="${MISSING_VMM} cloud-hypervisor"
  fi
  VIRTIOFSD_PATH="$(find_virtiofsd || true)"
  if [ -z "$VIRTIOFSD_PATH" ]; then
    MISSING_VMM="${MISSING_VMM} virtiofsd"
  fi
  PASST_PATH="${LNS_PASST_BIN:-$(command -v passt || true)}"
  if [ -z "$PASST_PATH" ]; then
    MISSING_VMM="${MISSING_VMM} passt"
  fi
  if [ -n "$MISSING_VMM" ]; then
    warn "The microVM runtime is not on PATH. \`${BINARY_NAME} run\` needs cloud-hypervisor, virtiofsd and passt."
    echo "  Missing:${MISSING_VMM}"
    echo "  Install them from your distro or a static build, or point lns at existing binaries with"
    echo "    LNS_CLOUD_HYPERVISOR_BIN=/path/to/cloud-hypervisor LNS_VIRTIOFSD_BIN=/path/to/virtiofsd LNS_PASST_BIN=/path/to/passt"
    echo ""
  fi
  if [ -n "$VIRTIOFSD_PATH" ] && ! "$VIRTIOFSD_PATH" --help 2>&1 | grep -q -- "--readonly"; then
    warn "virtiofsd at ${VIRTIOFSD_PATH} does not support read-only shares. \`${BINARY_NAME} run\` requires --readonly support."
    echo "  Install a newer virtiofsd or set LNS_VIRTIOFSD_BIN=/path/to/virtiofsd."
    echo ""
  fi
  if [ -n "$PASST_PATH" ] && ! "$PASST_PATH" --help 2>&1 | grep -q -- "--vhost-user"; then
    warn "passt at ${PASST_PATH} does not support vhost-user. \`${BINARY_NAME} run\` needs it to give the guest a network."
    echo "  Install a newer passt or set LNS_PASST_BIN=/path/to/passt."
    echo ""
  fi

  # Ubuntu 23.10+ lets a program create a user namespace only under an AppArmor profile that allows it.
  if [ "$(sysctl -n kernel.apparmor_restrict_unprivileged_userns 2>/dev/null || echo 0)" = 1 ]; then
    allow_user_namespaces lns-passt "$PASST_PATH" "Guests have no network"
    allow_user_namespaces lns-virtiofsd "$VIRTIOFSD_PATH" "Runs that bind a host directory fail"
  fi
fi

if [ "$HAS_SERVICE" = true ] && [ -z "$NO_SERVICE" ]; then
  info "Starting the LNS service and enabling login auto-start..."
  # The `if` guard keeps `set -e` from aborting the install if the binary is unrunnable.
  if "${INSTALL_DIR}/${BINARY_NAME}" service enable; then
    SERVICE_ENABLED=true
  else
    SERVICE_ENABLED=false
    warn "Could not enable the background service automatically. Start it yourself with: ${BINARY_NAME} service enable"
  fi
else
  SERVICE_ENABLED=false
fi

"${INSTALL_DIR}/${BINARY_NAME}" --version

echo ""
if [ "$SERVICE_ENABLED" = true ]; then
  echo "${BOLD}▸ Service:${RESET}  running now and on every login (stop: ${BINARY_NAME} service stop · remove auto-start: ${BINARY_NAME} service disable)"
elif [ "$HAS_SERVICE" = true ] && [ -n "$NO_SERVICE" ]; then
  echo "${BOLD}▸ Service:${RESET}  skipped (LNS_NO_SERVICE/--no-service). Start it with: ${BINARY_NAME} service enable"
fi
echo "${BOLD}▸ Try it:${RESET}   ${BINARY_NAME} run -- echo hello from inside a microVM"
echo "${BOLD}▸ Help:${RESET}     ${BINARY_NAME} --help"
