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

set -e

SERVER_IP="${1:-monitrack.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

# --uninstall : 제거 모드 (서비스/유닛/폴더 삭제)
if [ "$1" = "--uninstall" ] || [ "$1" = "-u" ]; then
  SVC="loi-agent"; INSTALL_DIR="/opt/loi_agent"; UNIT="/etc/systemd/system/${SVC}.service"
  if command -v rpm >/dev/null 2>&1 && rpm -q loi-agent >/dev/null 2>&1; then rpm -e loi-agent || true
  elif command -v dpkg >/dev/null 2>&1 && dpkg -s loi-agent >/dev/null 2>&1; then dpkg -r loi-agent || true; fi
  systemctl stop "$SVC" 2>/dev/null || true
  systemctl disable "$SVC" 2>/dev/null || true
  rm -f "$UNIT"; systemctl daemon-reload 2>/dev/null || true
  rm -rf "$INSTALL_DIR"
  echo "[OK] 제거 완료 (서비스/폴더 삭제)."
  exit 0
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"
DEST="$INSTALL_DIR/loi_agent.py"
SRC="$(dirname "$0")/loi_agent.py"

FILE_URL="http://$SERVER_IP/downloads/loi_agent.py"
MD5_URL="http://$SERVER_IP/downloads/loi_agent.py.md5"

file_md5() { [ -f "$1" ] && md5sum "$1" 2>/dev/null | awk '{print $1}' | tr 'A-F' 'a-f'; }

remote_md5="$(curl -sSL --max-time 10 "$MD5_URL" 2>/dev/null | tr -d '[:space:]' | tr 'A-F' 'a-f')"

# 로컬 파일이 서버 최신본과 같으면 그것을 쓰고, 아니면(옛 버전이거나 없으면) 서버에서 새로 받는다.
if [ -f "$SRC" ] && [ -n "$remote_md5" ] && [ "$(file_md5 "$SRC")" = "$remote_md5" ]; then
  echo "[INFO] Local loi_agent.py is up to date (matches server)."
  cp -f "$SRC" "$DEST"
else
  echo "[INFO] Downloading latest loi_agent.py from $FILE_URL ..."
  if curl -sSL --max-time 60 "$FILE_URL" -o "$DEST" && [ -s "$DEST" ]; then
    echo "[INFO] Downloaded loi_agent.py (md5=$(file_md5 "$DEST"))"
  elif [ -f "$SRC" ]; then
    echo "[WARN] Download failed. Using local loi_agent.py (may be old)."
    cp -f "$SRC" "$DEST"
  else
    echo "[ERROR] Cannot obtain loi_agent.py (download failed and no local copy)."
    exit 1
  fi
fi

chmod +x "$DEST"

# 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 loi-agent
# 이미 실행 중이어도 새 코드로 확실히 재시작한다 (enable --now 는 재시작하지 않음)
systemctl restart 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"
