#!/bin/sh
set -eu

if [ "$(id -u)" -ne 0 ]; then
  echo "Run as root: sudo sh install.sh"
  exit 1
fi

command -v python3 >/dev/null || { echo "python3 is required"; exit 1; }
command -v openssl >/dev/null || { echo "openssl is required"; exit 1; }

INSTALL_DIR=/opt/server-monitor-agent
CONFIG_DIR=/etc/server-monitor-agent
DOWNLOAD_BASE=https://vmhub.ru/downloads
TOKEN="$(openssl rand -hex 32)"
HOSTNAME_VALUE="$(hostname -f 2>/dev/null || hostname)"

install -d -m 0755 "$INSTALL_DIR" "$CONFIG_DIR"
SCRIPT_SOURCE="$(dirname "$0")/server_monitor_agent.py"
if [ -f "$SCRIPT_SOURCE" ]; then
  install -m 0755 "$SCRIPT_SOURCE" "$INSTALL_DIR/server_monitor_agent.py"
elif command -v curl >/dev/null; then
  curl -fsSL "$DOWNLOAD_BASE/server_monitor_agent.py" -o "$INSTALL_DIR/server_monitor_agent.py"
  chmod 0755 "$INSTALL_DIR/server_monitor_agent.py"
elif command -v wget >/dev/null; then
  wget -qO "$INSTALL_DIR/server_monitor_agent.py" "$DOWNLOAD_BASE/server_monitor_agent.py"
  chmod 0755 "$INSTALL_DIR/server_monitor_agent.py"
else
  echo "curl or wget is required to download the agent"
  exit 1
fi

openssl req -x509 -newkey rsa:3072 -sha256 -nodes -days 825 \
  -keyout "$CONFIG_DIR/key.pem" -out "$CONFIG_DIR/cert.pem" \
  -subj "/CN=$HOSTNAME_VALUE" -addext "subjectAltName=DNS:$HOSTNAME_VALUE,DNS:$(hostname)" >/dev/null 2>&1
chmod 0600 "$CONFIG_DIR/key.pem"

cat > "$CONFIG_DIR/agent.env" <<EOF
SERVER_MONITOR_TOKEN=$TOKEN
SERVER_MONITOR_HOST=0.0.0.0
SERVER_MONITOR_PORT=9443
SERVER_MONITOR_CERT=$CONFIG_DIR/cert.pem
SERVER_MONITOR_KEY=$CONFIG_DIR/key.pem
SERVER_MONITOR_ALLOW_ACTIONS=1
EOF
chmod 0600 "$CONFIG_DIR/agent.env"

cat > /etc/systemd/system/server-monitor-agent.service <<EOF
[Unit]
Description=Server Monitor Agent
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
EnvironmentFile=$CONFIG_DIR/agent.env
ExecStart=/usr/bin/python3 $INSTALL_DIR/server_monitor_agent.py
Restart=on-failure
RestartSec=5
User=root
NoNewPrivileges=true
PrivateTmp=true
ProtectHome=true
ProtectSystem=strict
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable --now server-monitor-agent.service

echo
echo "Server Monitor Agent installed."
echo "Address: https://$HOSTNAME_VALUE:9443"
echo "Access token: $TOKEN"
echo "Save the token now; it is stored in $CONFIG_DIR/agent.env"
