#!/bin/sh
# SSH Protector — Linux agent installer.
#
# Usage (as root):
#   curl -fsSL https://<panel>/download/installer | sudo sh
#   # or, standalone:
#   sudo ./install.sh --server https://<panel>
#
# After it installs, enroll this server with your account token:
#   sudo guard install --token <YOUR_TOKEN>
#
# The panel serves a copy of this script with --server pre-filled; when run
# standalone, pass --server (or set SSH_PROTECTOR_SERVER). The download base
# defaults to <server>/download/agent and can be overridden with --base.
set -eu

SERVER="${SSH_PROTECTOR_SERVER:-}"
BASE=""

while [ $# -gt 0 ]; do
  case "$1" in
    --server) SERVER="$2"; shift 2 ;;
    --server=*) SERVER="${1#*=}"; shift ;;
    --base) BASE="$2"; shift 2 ;;
    --base=*) BASE="${1#*=}"; shift ;;
    *) echo "unknown option: $1" >&2; exit 2 ;;
  esac
done

if [ "$(id -u)" -ne 0 ]; then
  echo "SSH Protector: please run as root (use sudo)." >&2
  exit 1
fi

if [ -z "$SERVER" ]; then
  SERVER="https://sshprotector.com"
fi
if [ -z "$BASE" ]; then
  BASE="$SERVER/download/agent"
fi

case "$(uname -m)" in
  x86_64|amd64)  ARCH=amd64 ;;
  aarch64|arm64) ARCH=arm64 ;;
  *) echo "SSH Protector: unsupported architecture $(uname -m)" >&2; exit 1 ;;
esac

BIN=/usr/local/bin/guard
TMP="$(mktemp)"
trap 'rm -f "$TMP"' EXIT

echo "SSH Protector — downloading agent ($ARCH)..."
if command -v curl >/dev/null 2>&1; then
  curl -fsSL "$BASE/guard-linux-$ARCH" -o "$TMP"
elif command -v wget >/dev/null 2>&1; then
  wget -qO "$TMP" "$BASE/guard-linux-$ARCH"
else
  echo "SSH Protector: need curl or wget to download the agent." >&2
  exit 1
fi

install -m 0755 "$TMP" "$BIN"

echo "SSH Protector — installing the protection service..."
"$BIN" install --server "$SERVER"

echo
echo "Done. Enroll this server with your account token:"
echo "  sudo guard install --token <YOUR_TOKEN>"
