#!/usr/bin/env bash
set -euo pipefail

url=""
host_name="$(hostname)"
host_alias=""
interval=300
while [[ $# -gt 0 ]]; do
  case "$1" in
    --url) url="${2:?缺少站点地址}"; shift 2 ;;
    --hostname) host_name="${2:?缺少主机名}"; shift 2 ;;
    --alias) host_alias="${2:?缺少别名}"; shift 2 ;;
    --interval) interval="${2:?缺少秒数}"; shift 2 ;;
    *) echo "用法：sudo bash install.sh --url https://example.pages.dev --hostname arm-01 --alias 客厅 --interval 300" >&2; exit 1 ;;
  esac
done
[[ $EUID -eq 0 ]] || { echo "请用 sudo 运行安装脚本。" >&2; exit 1; }
[[ "$interval" =~ ^[0-9]+$ ]] && (( interval >= 60 && interval <= 86400 )) || { echo "上传间隔必须为 60 到 86400 秒。" >&2; exit 1; }
for executable in python3 curl systemctl ss ip; do
  command -v "$executable" >/dev/null || { echo "缺少 $executable。请先运行：sudo apt-get install python3 curl ca-certificates iproute2" >&2; exit 1; }
done

temporary_dir="$(mktemp -d)"
trap 'rm -rf "$temporary_dir"' EXIT
# Validate all input before touching the installed configuration.
python3 - "$url" "$host_name" "$host_alias" "$temporary_dir/config.json" <<'PY'
import json, re, sys
from pathlib import Path
from urllib.parse import urlsplit
url, hostname, alias, output = sys.argv[1:]
parsed = urlsplit(url)
if parsed.scheme != 'https' or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in ('', '/'):
    sys.exit('请提供 HTTPS 站点根地址。')
if not re.fullmatch(r'[a-zA-Z0-9][a-zA-Z0-9._-]{0,252}', hostname):
    sys.exit('主机名格式无效。')
if not alias.strip() or len(alias) > 80 or re.search(r'[\x00-\x1f\x7f]', alias):
    sys.exit('请提供不超过 80 个字符的固定别名。')
Path(output).write_text(json.dumps({'url': url.rstrip('/'), 'hostname': hostname.lower(), 'alias': alias.strip()}, ensure_ascii=False) + '\n')
PY
url="${url%/}"
curl --fail --silent --show-error --proto '=https' --tlsv1.2 "$url/downloads/server-report.py" -o "$temporary_dir/server-report.py"
python3 -c 'import ast, pathlib, sys; ast.parse(pathlib.Path(sys.argv[1]).read_text())' "$temporary_dir/server-report.py"
install -d -m 0755 /opt/server-report
install -d -m 0755 /etc/server-report
install -m 0755 "$temporary_dir/server-report.py" /opt/server-report/server-report.py
install -m 0644 "$temporary_dir/config.json" /etc/server-report/config.json
cat > /etc/systemd/system/server-report.service <<'UNIT'
[Unit]
Description=Upload the latest server status sample
Wants=network-online.target
After=network-online.target

[Service]
Type=oneshot
ExecStart=/usr/bin/python3 /opt/server-report/server-report.py --config /etc/server-report/config.json
TimeoutStartSec=120
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ProtectHome=true
ProtectKernelTunables=true
ProtectControlGroups=true
MemoryMax=192M
UNIT
cat > /etc/systemd/system/server-report.timer <<UNIT
[Unit]
Description=Periodically upload server status

[Timer]
OnBootSec=90s
OnUnitActiveSec=${interval}s
RandomizedDelaySec=20s
Unit=server-report.service

[Install]
WantedBy=timers.target
UNIT
systemctl daemon-reload
systemctl enable --now server-report.timer
systemctl restart server-report.timer
systemctl start server-report.service
echo "已安装并完成首次上传。每 ${interval} 秒采样一次，另有最多 20 秒随机延迟。"
echo "查看定时器：systemctl status server-report.timer"
echo "查看上传日志：journalctl -u server-report.service -n 30 --no-pager"
