#!/bin/bash

set -e

SCRIPT_URL="https://file.innovanok.com/inform_stat.sh"
SCRIPT_PATH="/usr/local/bin/inform_stat.sh"

SERVICE_FILE="/etc/systemd/system/inform_stat.service"
TIMER_FILE="/etc/systemd/system/inform_stat.timer"

echo "⬇️ Descargando script..."
curl -fsSL "$SCRIPT_URL" -o "$SCRIPT_PATH"

echo "🔑 Dando permisos..."
chmod +x "$SCRIPT_PATH"

echo "🧩 Creando systemd service..."

cat <<EOF > "$SERVICE_FILE"
[Unit]
Description=Inform Server Stats

[Service]
Type=oneshot
ExecStart=$SCRIPT_PATH
EOF

echo "⏱ Creando systemd timer (cada 15 segundos)..."

cat <<EOF > "$TIMER_FILE"
[Unit]
Description=Inform Server Stats every 15 seconds

[Timer]
OnUnitActiveSec=15s
AccuracySec=1s
Persistent=false

[Install]
WantedBy=timers.target
EOF

echo "🔄 Recargando systemd..."
systemctl daemon-reexec
systemctl daemon-reload

echo "▶️ Habilitando timer..."
systemctl enable --now inform_stat.timer

echo "✅ Instalación completada"

echo "📊 Estado del timer:"
systemctl list-timers | grep inform_stat

