#!/bin/bash
# 실습 #20 ② — Wazuh agent 설치 + manager 등록
# 사용: bash setup_02_agent_enroll.sh <manager-ip> [agent-name]
# - apt 저장소 방식 (운영 표준)
# - 자동 등록 (auto-enrollment, 1515 포트)
# - manager 측에서 agent_control -l 로 Active 확인
set -e

MGR="${1:-}"
AGENT_NAME="${2:-$(hostname)}"

if [ -z "$MGR" ]; then
    echo "사용: bash $0 <manager-ip> [agent-name]"
    echo "예  : bash $0 192.168.56.10 web-01"
    exit 1
fi

# 1) Wazuh apt 저장소
if [ ! -f /etc/apt/sources.list.d/wazuh.list ]; then
    curl -s https://packages.wazuh.com/key/GPG-KEY-WAZUH | \
        sudo gpg --no-default-keyring --keyring gnupg-ring:/usr/share/keyrings/wazuh.gpg --import
    sudo chmod 644 /usr/share/keyrings/wazuh.gpg
    echo "deb [signed-by=/usr/share/keyrings/wazuh.gpg] https://packages.wazuh.com/4.x/apt/ stable main" | \
        sudo tee /etc/apt/sources.list.d/wazuh.list >/dev/null
    sudo apt update
fi

# 2) agent 설치 (WAZUH_MANAGER · WAZUH_AGENT_NAME 환경변수가 자동 등록 트리거)
WAZUH_MANAGER="$MGR" WAZUH_AGENT_NAME="$AGENT_NAME" \
    sudo -E apt install -y wazuh-agent

# 3) 시작
sudo systemctl daemon-reload
sudo systemctl enable --now wazuh-agent
sleep 5

# 4) 상태
echo
echo "=== agent 상태 ==="
sudo systemctl is-active wazuh-agent
sudo tail -20 /var/ossec/logs/ossec.log | grep -iE "connected|enroll|started" || \
    sudo tail -20 /var/ossec/logs/ossec.log

# 5) manager 측 확인 안내
cat <<EOF

=== manager 측에서 등록 확인 ===
  sudo /var/ossec/bin/agent_control -l
  # ID: 001, Name: $AGENT_NAME, IP: any, Status: Active

=== 통신 포트 ===
  1514/tcp+udp : agent → manager 이벤트 전송
  1515/tcp     : 자동 등록
  → 양쪽 머신 방화벽에서 열려 있어야 함

=== 수동 키 등록 (자동 등록이 막힌 환경) ===
  # manager 측
  sudo /var/ossec/bin/manage_agents
  # → A) Add, ID 자동, name = $AGENT_NAME, IP any
  # → E) Extract key for $AGENT_NAME → key 출력
  # agent 측
  sudo /var/ossec/bin/manage_agents
  # → I) Import key, 위의 key 붙여넣기
  sudo systemctl restart wazuh-agent
EOF
