# ================= TASK 1: Verify Wazuh manager <-> agent connectivity =================
source ~/lab.env

# ---------- 0. prerequisites ----------
sudo apt update && sudo apt install -y docker.io docker-compose-v2 git curl jq sshpass openssh-server iptables
sudo systemctl enable --now docker ssh
sudo usermod -aG docker $USER && newgrp docker

# ---------- 1. Wazuh server stack in Docker ----------
sudo sysctl -w vm.max_map_count=262144
echo 'vm.max_map_count=262144' | sudo tee /etc/sysctl.d/99-wazuh.conf

cd ~
git clone https://github.com/wazuh/wazuh-docker.git -b v$WAZUH_VERSION --depth=1
cd $WAZUH_DIR
docker compose -f generate-indexer-certs.yml run --rm generator
docker compose up -d

# wait 2-3 min, then re-load variables (MGR is detected now)
source ~/lab.env
docker compose ps
ss -ltnp | grep -E "443|1514|1515|55000|9200"

# ---------- 2. Wazuh agent on the Ubuntu device ----------
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
sudo apt update
sudo WAZUH_MANAGER="$MANAGER_IP" WAZUH_AGENT_NAME="$AGENT_NAME" apt install -y wazuh-agent=${WAZUH_VERSION}-1
sudo systemctl daemon-reload
sudo systemctl enable --now wazuh-agent

# ---------- 3. verify: manager side ----------
docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Ports}}'
docker exec $MGR /var/ossec/bin/wazuh-control status
docker exec $MGR /var/ossec/bin/agent_control -l
docker exec $MGR /var/ossec/bin/agent_control -i 001

# ---------- 4. verify: agent side ----------
sudo systemctl is-active wazuh-agent
sudo systemctl status wazuh-agent --no-pager | head -15
sudo grep -iE "connected to the server|Valid key received" /var/ossec/logs/ossec.log | tail -5
sudo grep -E "status|last_keepalive" /var/ossec/var/run/wazuh-agentd.state
sudo grep -A3 "<server>" /var/ossec/etc/ossec.conf
nc -zv $MANAGER_IP 1514; nc -zv $MANAGER_IP 1515

# ---------- 5. verify: REST API ----------
TOKEN=$(curl -sk -u $API_USER:"$API_PASS" -X POST "https://localhost:55000/security/user/authenticate?raw=true")
curl -sk -H "Authorization: Bearer $TOKEN" "https://localhost:55000/agents?pretty=true&select=id,name,ip,status,version"
curl -sk -H "Authorization: Bearer $TOKEN" "https://localhost:55000/agents/summary/status?pretty=true"

# ---------- 6. browser (screenshots) ----------
# https://localhost  (login: DASH_USER / DASH_PASS from lab.env)
# Agents -> ubuntu-server = Active ;  Server management -> Status = all running

# SAY: Agent enrolls via authd (1515) and keeps a keep-alive channel to remoted (1514).