#!/bin/bash
# Install Nuke telemetry monitoring as a systemd service
# This allows it to run automatically in the background

SERVICE_NAME="nuke-telemetry-monitor"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"
MONITOR_SCRIPT="$HOME/Documents/obsidian-vault/2-projects/Nuke-monitoring/monitor_nuke_telemetry.sh"

echo "=== Nuke Telemetry Monitor Service Installer ==="
echo ""
echo "This will install a background service that monitors Nuke telemetry"
echo "whenever Nuke is running. Logs will be saved automatically."
echo ""
read -p "Continue? (y/n): " confirm

if [ "$confirm" != "y" ]; then
    echo "Aborted."
    exit 0
fi

# Make monitor script executable
chmod +x "$MONITOR_SCRIPT"

# Create systemd service file
echo ""
echo "Creating systemd service..."
sudo tee "$SERVICE_FILE" > /dev/null << EOF
[Unit]
Description=Nuke Telemetry Monitor
After=network.target

[Service]
Type=simple
User=$USER
ExecStart=$MONITOR_SCRIPT
Restart=on-failure
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

echo "✓ Service file created: $SERVICE_FILE"

# Reload systemd
echo ""
echo "Reloading systemd..."
sudo systemctl daemon-reload
echo "✓ systemd reloaded"

# Enable and start service
echo ""
read -p "Start monitoring now? (y/n): " start_now

if [ "$start_now" = "y" ]; then
    sudo systemctl enable "$SERVICE_NAME"
    sudo systemctl start "$SERVICE_NAME"
    echo "✓ Service enabled and started"
    echo ""
    echo "Check status with:"
    echo "  sudo systemctl status $SERVICE_NAME"
    echo ""
    echo "View logs with:"
    echo "  sudo journalctl -u $SERVICE_NAME -f"
else
    echo "Service created but not started."
    echo ""
    echo "To start later:"
    echo "  sudo systemctl enable $SERVICE_NAME"
    echo "  sudo systemctl start $SERVICE_NAME"
fi

echo ""
echo "=== Service Management Commands ==="
echo "Start:   sudo systemctl start $SERVICE_NAME"
echo "Stop:    sudo systemctl stop $SERVICE_NAME"
echo "Restart: sudo systemctl restart $SERVICE_NAME"
echo "Status:  sudo systemctl status $SERVICE_NAME"
echo "Logs:    sudo journalctl -u $SERVICE_NAME -f"
echo "Disable: sudo systemctl disable $SERVICE_NAME"
echo ""
