#!/usr/bin/env sh
set -eu

DEFAULT_DOWNLOAD_BASE="https://github.com/m-nader90/hokio-releases/releases/latest/download"
DOWNLOAD_BASE="${HOKIO_DOWNLOAD_BASE_URL:-$DEFAULT_DOWNLOAD_BASE}"
INSTALL_DIR="${HOKIO_INSTALL_DIR:-/usr/local/bin}"
PORT=""
PRINT_PLATFORM=0

usage() {
  cat <<'EOF'
Install Hokio Agent on a supported Linux system.

Usage: install.sh [--port PORT] [--install-dir PATH] [--print-platform]

Without --port, the script installs the verified binary and prints the commands
needed to register the device. With --port, it also starts interactive device
registration. Automatic startup is enabled when a systemd user manager is
available; other init systems can run `hokio-agent connect` under their native
service supervisor.
EOF
}

while [ "$#" -gt 0 ]; do
  case "$1" in
    --port)
      [ "$#" -ge 2 ] || { printf '%s\n' "error: --port requires a value" >&2; exit 2; }
      PORT=$2
      shift 2
      ;;
    --install-dir)
      [ "$#" -ge 2 ] || { printf '%s\n' "error: --install-dir requires a value" >&2; exit 2; }
      INSTALL_DIR=$2
      shift 2
      ;;
    --print-platform)
      PRINT_PLATFORM=1
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      printf '%s\n' "error: unknown option: $1" >&2
      usage >&2
      exit 2
      ;;
  esac
done

if [ -n "$PORT" ]; then
  case "$PORT" in *[!0-9]*|'') printf '%s\n' "error: invalid port" >&2; exit 2 ;; esac
  [ "$PORT" -ge 1 ] && [ "$PORT" -le 65535 ] || {
    printf '%s\n' "error: port must be between 1 and 65535" >&2
    exit 2
  }
fi

case "$DOWNLOAD_BASE" in
  https://*) ;;
  *) printf '%s\n' "error: download URL must use HTTPS" >&2; exit 1 ;;
esac

case "$(uname -s)" in
  Linux) ;;
  *) printf '%s\n' "error: this installer supports Linux only" >&2; exit 1 ;;
esac

case "$(uname -m)" in
  x86_64|amd64) ARCHITECTURE=amd64 ;;
  aarch64|arm64) ARCHITECTURE=arm64 ;;
  *) printf '%s\n' "error: unsupported architecture: $(uname -m)" >&2; exit 1 ;;
esac

if [ -n "${HOKIO_LIBC:-}" ]; then
  case "$HOKIO_LIBC" in
    glibc|musl) LIBC=$HOKIO_LIBC ;;
    *) printf '%s\n' "error: HOKIO_LIBC must be glibc or musl" >&2; exit 1 ;;
  esac
elif command -v getconf >/dev/null 2>&1 && getconf GNU_LIBC_VERSION >/dev/null 2>&1; then
  LIBC=glibc
elif ldd --version 2>&1 | grep -qi musl; then
  LIBC=musl
elif ldd --version 2>&1 | grep -Eqi 'glibc|gnu libc'; then
  LIBC=glibc
elif find /lib /usr/lib -maxdepth 2 -name 'ld-musl-*.so.1' -print -quit 2>/dev/null | grep -q .; then
  LIBC=musl
else
  printf '%s\n' "error: could not detect glibc or musl; set HOKIO_LIBC explicitly" >&2
  exit 1
fi

if [ "$PRINT_PLATFORM" -eq 1 ]; then
  printf '%s\n' "${LIBC}-${ARCHITECTURE}"
  exit 0
fi

if command -v curl >/dev/null 2>&1; then
  download() { curl --proto '=https' --tlsv1.2 -fsSL "$1" -o "$2"; }
elif command -v wget >/dev/null 2>&1; then
  if wget --help 2>&1 | grep -q -- '--https-only'; then
    download() { wget --https-only -q "$1" -O "$2"; }
  else
    download() { wget -q "$1" -O "$2"; }
  fi
else
  printf '%s\n' "error: curl or wget is required" >&2
  exit 1
fi

ASSET_NAME="hokio-agent-linux-${LIBC}-${ARCHITECTURE}"
TEMP_DIR=$(mktemp -d "${TMPDIR:-/tmp}/hokio-install.XXXXXX")
trap 'rm -rf "$TEMP_DIR"' EXIT HUP INT TERM

download "$DOWNLOAD_BASE/$ASSET_NAME" "$TEMP_DIR/$ASSET_NAME"
download "$DOWNLOAD_BASE/$ASSET_NAME.sha256" "$TEMP_DIR/$ASSET_NAME.sha256"
(
  cd "$TEMP_DIR"
  sha256sum -c "$ASSET_NAME.sha256"
)

TARGET="$INSTALL_DIR/hokio-agent"
if [ "$(id -u)" -eq 0 ]; then
  mkdir -p "$INSTALL_DIR"
  install -m 0755 "$TEMP_DIR/$ASSET_NAME" "$TARGET"
elif mkdir -p "$INSTALL_DIR" 2>/dev/null && [ -w "$INSTALL_DIR" ]; then
  install -m 0755 "$TEMP_DIR/$ASSET_NAME" "$TARGET"
elif command -v sudo >/dev/null 2>&1; then
  sudo install -d -m 0755 "$INSTALL_DIR"
  sudo install -m 0755 "$TEMP_DIR/$ASSET_NAME" "$TARGET"
else
  INSTALL_DIR="$HOME/.local/bin"
  TARGET="$INSTALL_DIR/hokio-agent"
  mkdir -p "$INSTALL_DIR"
  install -m 0755 "$TEMP_DIR/$ASSET_NAME" "$TARGET"
  printf '%s\n' "Installed without sudo. Add $INSTALL_DIR to PATH if necessary."
fi

"$TARGET" --help >/dev/null
printf '%s\n' "Hokio Agent installed: $TARGET"

if [ -n "$PORT" ]; then
  "$TARGET" login --port "$PORT"
  if command -v systemctl >/dev/null 2>&1 && systemctl --user show-environment >/dev/null 2>&1; then
    "$TARGET" service install --start
  else
    printf '%s\n' "Device registered. No active systemd user manager was detected."
    printf '%s\n' "Run '$TARGET connect' with your distribution's service supervisor."
  fi
else
  printf '%s\n' "Next: hokio-agent login --port 5000"
  printf '%s\n' "Then: hokio-agent service install --start"
fi
