#!/bin/bash
# LOI Zabbix Linux Agent Auto-Installer for systemd

set -e

SERVER_IP="${1:-loizabbix.loict.co.kr}"
AGENT_NAME="${2:-$(hostname)}"

echo "======================================================"
echo "  LOI Zabbix Linux Agent Installer"
echo "======================================================"
echo "Server IP  : $SERVER_IP"
echo "Agent Name : $AGENT_NAME"
echo "======================================================"

# Check root
if [ "$EUID" -ne 0 ]; then
  echo "[ERROR] Please run this script with sudo or as root."
  exit 1
fi

# Check Python 3
if ! command -v python3 &> /dev/null; then
  echo "[INFO] Python 3 not found. Installing python3..."
  if command -v apt-get &> /dev/null; then
    apt-get update && apt-get install -y python3
  elif command -v dnf &> /dev/null; then
    dnf install -y python3
  elif command -v yum &> /dev/null; then
    yum install -y python3
  elif command -v apk &> /dev/null; then
    apk add python3
  else
    echo "[ERROR] Package manager not supported. Please install python3 manually."
    exit 1
  fi
fi

INSTALL_DIR="/opt/loi_agent"
mkdir -p "$INSTALL_DIR"

SCRIPT_SRC="$(dirname "$0")/loi_agent.py"
if [ -f "$SCRIPT_SRC" ]; then
  cp "$SCRIPT_SRC" "$INSTALL_DIR/loi_agent.py"
else
  echo "[INFO] Downloading latest loi_agent.py from http://$SERVER_IP/downloads/loi_agent.py..."
  curl -sSL "http://$SERVER_IP/downloads/loi_agent.py" -o "$INSTALL_DIR/loi_agent.py"
fi

chmod +x "$INSTALL_DIR/loi_agent.py"

# Write config
cat <<EOF > "$INSTALL_DIR/agent_config.json"
{
  "server_ip": "$SERVER_IP",
  "agent_name": "$AGENT_NAME"
}
EOF

# Create systemd service
cat <<EOF > /etc/systemd/system/loi-agent.service
[Unit]
Description=LOI Zabbix Monitoring Agent
After=network.target

[Service]
Type=simple
WorkingDirectory=$INSTALL_DIR
ExecStart=/usr/bin/env python3 $INSTALL_DIR/loi_agent.py -server $SERVER_IP -name $AGENT_NAME
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now loi-agent

echo ""
echo "[SUCCESS] LOI Zabbix Agent has been successfully installed and started as a systemd service!"
echo "Check status anytime with: systemctl status loi-agent"
echo "View real-time logs with: journalctl -u loi-agent -f"
