#!/bin/bash
# Installation script for Dangerous Pi systemd service

set -e

echo "Installing Dangerous Pi systemd service..."

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    echo "Error: This script must be run as root (use sudo)"
    exit 1
fi

# Variables
SERVICE_NAME="dangerous-pi"
SERVICE_FILE="dangerous-pi.service"
INSTALL_DIR="/opt/dangerous-pi"
SYSTEMD_DIR="/etc/systemd/system"

# Create installation directory if it doesn't exist
if [ ! -d "$INSTALL_DIR" ]; then
    echo "Creating installation directory: $INSTALL_DIR"
    mkdir -p "$INSTALL_DIR"
fi

# Copy service file to systemd directory
echo "Installing systemd service unit..."
cp "$(dirname "$0")/$SERVICE_FILE" "$SYSTEMD_DIR/"
chmod 644 "$SYSTEMD_DIR/$SERVICE_FILE"

# Create .env file if it doesn't exist
if [ ! -f "$INSTALL_DIR/.env" ]; then
    echo "Creating environment configuration file..."
    cp "$(dirname "$0")/dangerous-pi.env.example" "$INSTALL_DIR/.env"
    chown pi:pi "$INSTALL_DIR/.env"
    chmod 600 "$INSTALL_DIR/.env"
    echo "NOTE: Please edit $INSTALL_DIR/.env to configure your installation"
fi

# Create data and logs directories
echo "Creating data and logs directories..."
mkdir -p "$INSTALL_DIR/data"
mkdir -p "$INSTALL_DIR/logs"
chown -R pi:pi "$INSTALL_DIR/data" "$INSTALL_DIR/logs"
chmod 755 "$INSTALL_DIR/data" "$INSTALL_DIR/logs"

# Add pi user to required groups for hardware access
echo "Adding pi user to hardware access groups..."
usermod -a -G i2c,bluetooth,gpio,dialout pi || true

# Reload systemd daemon
echo "Reloading systemd daemon..."
systemctl daemon-reload

# Enable service to start on boot
echo "Enabling $SERVICE_NAME service..."
systemctl enable "$SERVICE_NAME.service"

echo ""
echo "✅ Installation complete!"
echo ""
echo "Next steps:"
echo "  1. Edit configuration: sudo nano $INSTALL_DIR/.env"
echo "  2. Start the service: sudo systemctl start $SERVICE_NAME"
echo "  3. Check status: sudo systemctl status $SERVICE_NAME"
echo "  4. View logs: sudo journalctl -u $SERVICE_NAME -f"
echo ""
