#!/bin/bash

# AutoKanban Systemd Service Setup Script
# Run this on the Raspberry Pi to enable autostart on boot

set -e

echo "🚀 Setting up AutoKanban service..."

# Check if running as regular user
if [ "$EUID" -eq 0 ]; then
   echo "❌ Please run as regular user (not sudo)"
   exit 1
fi

# Get the directory where this script is located
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
SERVICE_FILE="$SCRIPT_DIR/autokanban.service"

echo "📁 Working directory: $SCRIPT_DIR"

# Update the service file with actual paths
echo "🔧 Updating service file paths..."
sed -i "s|/home/pi/autokanban|$SCRIPT_DIR|g" "$SERVICE_FILE"
sed -i "s|User=pi|User=$USER|g" "$SERVICE_FILE"
sed -i "s|Group=pi|Group=$USER|g" "$SERVICE_FILE"

# Copy service file to systemd
echo "📋 Installing systemd service..."
sudo cp "$SERVICE_FILE" /etc/systemd/system/autokanban.service

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

# Enable the service
echo "✅ Enabling autokanban service..."
sudo systemctl enable autokanban.service

# Start the service
echo "▶️  Starting autokanban service..."
sudo systemctl start autokanban.service

# Show status
echo ""
echo "✨ Setup complete! Service status:"
sudo systemctl status autokanban.service --no-pager

echo ""
echo "📝 Useful commands:"
echo "  sudo systemctl status autokanban   - Check service status"
echo "  sudo systemctl stop autokanban     - Stop the service"
echo "  sudo systemctl start autokanban    - Start the service"
echo "  sudo systemctl restart autokanban  - Restart the service"
echo "  sudo journalctl -u autokanban -f   - View live logs"
echo "  sudo systemctl disable autokanban  - Disable autostart"
echo ""
echo "🌐 AutoKanban should now be running at http://$(hostname -I | awk '{print $1}'):8000"
