#!/bin/bash
# Arts Agent — Linux Installer
# One-liner: curl -s http://192.168.1.207/install/linux | bash -s -- <API_KEY>
# (c) Adrian Ranta. All rights reserved. Unauthorised use, reproduction and or distribution is strictly prohibited.

set -euo pipefail

ARTS_API_KEY="${1:-}"
ARTS_SERVER="${2:-http://192.168.1.207}"

if [ -z "$ARTS_API_KEY" ]; then
  echo "Usage: $0 <API_KEY> [ARTS_SERVER]" >&2
  exit 1
fi

echo "Installing Arts Agent..."

mkdir -p /etc/arts /opt/arts

cat > /etc/arts/agent.conf <<EOF
ARTS_SERVER=${ARTS_SERVER}
ARTS_API_KEY=${ARTS_API_KEY}
EOF
chmod 600 /etc/arts/agent.conf

curl -s "${ARTS_SERVER}/agents/linux/arts-agent.sh" -o /opt/arts/arts-agent.sh
chmod +x /opt/arts/arts-agent.sh

# Create systemd timer for periodic check-ins
cat > /etc/systemd/system/arts-agent.service <<EOF
[Unit]
Description=Arts Discovery Agent
After=network-online.target

[Service]
Type=oneshot
ExecStart=/opt/arts/arts-agent.sh
EnvironmentFile=/etc/arts/agent.conf
EOF

cat > /etc/systemd/system/arts-agent.timer <<EOF
[Unit]
Description=Arts Agent Check-in Timer

[Timer]
OnBootSec=60
OnUnitActiveSec=3600
RandomizedDelaySec=120

[Install]
WantedBy=timers.target
EOF

systemctl daemon-reload
systemctl enable arts-agent.timer
systemctl start arts-agent.timer

echo "Arts Agent installed. First check-in in 60 seconds."
echo "Timer: systemctl status arts-agent.timer"
echo "Manual run: systemctl start arts-agent.service"
