#!/usr/bin/env bash
# Install AIOR Connect agent binary on Linux (amd64). License is provisioned after desktop sign-in.
set -euo pipefail

VERSION="${AIORCONNECT_VERSION:-0.5.1}"
INSTALL_DIR="${AIORCONNECT_INSTALL_DIR:-${HOME}/.local/share/aior-connect}"
BIN_DIR="${HOME}/.local/bin"
CONFIG_DIR="${HOME}/.aiorconnect"
CONFIG_FILE="${CONFIG_DIR}/agent.json"
RELAY_URL="${AIORCONNECT_RELAY_URL:-wss://relay.aiorconnect.com/ws}"
LICENSE_API="${AIORCONNECT_LICENSE_API:-https://aiorconnect.com/api/v1/license/verify}"
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
DEVICE_ID="${AIORCONNECT_DEVICE_ID:-$(hostname -s | tr '[:upper:]' '[:lower:]')-linux}"
DEVICE_NAME="${AIORCONNECT_DEVICE_NAME:-$(hostname)}"

mkdir -p "$INSTALL_DIR" "$BIN_DIR" "$CONFIG_DIR"
cp -f "${SCRIPT_DIR}/AICN-service" "${INSTALL_DIR}/AICN-service"
chmod 755 "${INSTALL_DIR}/AICN-service"
ln -sf "${INSTALL_DIR}/AICN-service" "${BIN_DIR}/aiorconnect-agent"

LICENSE_KEY="${AIORCONNECT_LICENSE:-}"
if [[ -z "$LICENSE_KEY" ]]; then
  echo "OK: AIOR Connect agent binary installed."
  echo "  Sign in with the desktop app to provision a free license, or set AIORCONNECT_LICENSE for headless use."
  echo "  Guide: https://aiorconnect.com/get-started"
  exit 0
fi

cat > "$CONFIG_FILE" <<JSON
{
  "version": "${VERSION}",
  "device_id": "${DEVICE_ID}",
  "device_name": "${DEVICE_NAME}",
  "license_key": "${LICENSE_KEY}",
  "license_api": "${LICENSE_API}",
  "relay_url": "${RELAY_URL}"
}
JSON

UNIT_DIR="${HOME}/.config/systemd/user"
UNIT_FILE="${UNIT_DIR}/aior-connect-agent.service"
mkdir -p "$UNIT_DIR"
cat > "$UNIT_FILE" <<UNIT
[Unit]
Description=AIOR Connect Agent
After=network-online.target

[Service]
ExecStart=${INSTALL_DIR}/AICN-service -config ${CONFIG_FILE}
Restart=always
RestartSec=5

[Install]
WantedBy=default.target
UNIT

systemctl --user daemon-reload
systemctl --user enable --now aior-connect-agent.service

echo "OK: AIOR Connect agent installed and started"
echo "  Logs: journalctl --user -u aior-connect-agent.service -f"
