#!/usr/bin/env bash

set -euo pipefail

BASE_URL="https://mirror.zwa7f.com/zwa7fagent"
CONFIG_DIR="/etc/zwa7fagent"
CONFIG_FILE="${CONFIG_DIR}/license.env"
LICENSE_KEY="${1:-${ZWA7F_LICENSE_KEY:-}}"
SERVER_IP="${2:-${ZWA7F_SERVER_IP:-}}"

if [[ "${EUID}" -ne 0 ]]; then
  echo "Run this installer as root." >&2
  exit 1
fi

if [[ -z "${LICENSE_KEY}" ]]; then
  echo "Usage: bash install.sh LICENSE_KEY [SERVER_IP]" >&2
  echo "Or set ZWA7F_LICENSE_KEY and optionally ZWA7F_SERVER_IP." >&2
  exit 1
fi

install -d -m 0755 "${CONFIG_DIR}"

curl -fsSL "${BASE_URL}/zwa7fagent" -o /usr/local/bin/zwa7fagent
chmod 0755 /usr/local/bin/zwa7fagent

curl -fsSL "${BASE_URL}/zwa7fagent.service" -o /etc/systemd/system/zwa7fagent.service
chmod 0644 /etc/systemd/system/zwa7fagent.service

umask 077
cat > "${CONFIG_FILE}" <<EOF
API_URL=https://zwa7f.com/api/client/licenses/validate
PRODUCT_KEY=zwa7fagent
LICENSE_KEY=${LICENSE_KEY}
SERVER_IP=${SERVER_IP}
EOF

systemctl daemon-reload

if ! /usr/local/bin/zwa7fagent; then
  echo "License validation failed; the service was not enabled." >&2
  exit 1
fi

systemctl enable --now zwa7fagent.service

echo "ZWA7F Server Agent installed and licensed successfully."
echo "Configuration: ${CONFIG_FILE}"
echo "Manual check: /usr/local/bin/zwa7fagent"
