#!/bin/bash

# Install Provisioning Platform systemd services
# Run as root: sudo ./install-services.sh

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SYSTEMD_DIR="/etc/systemd/system"

echo "Installing Provisioning Platform systemd services..."

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

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    echo "Error: Docker is not installed. Please install Docker first."
    exit 1
fi

# Check if docker-compose is installed
if ! command -v docker-compose &> /dev/null; then
    echo "Error: docker-compose is not installed. Please install docker-compose first."
    exit 1
fi

# Copy service files
echo "Copying service files to $SYSTEMD_DIR..."
cp -v "$SCRIPT_DIR/provisioning-platform.service" "$SYSTEMD_DIR/"
cp -v "$SCRIPT_DIR/provisioning-orchestrator.service" "$SYSTEMD_DIR/"
cp -v "$SCRIPT_DIR/provisioning-control-center.service" "$SYSTEMD_DIR/"

# Set correct permissions
echo "Setting permissions..."
chmod 644 "$SYSTEMD_DIR/provisioning-platform.service"
chmod 644 "$SYSTEMD_DIR/provisioning-orchestrator.service"
chmod 644 "$SYSTEMD_DIR/provisioning-control-center.service"

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

# Display status
echo ""
echo "Services installed successfully!"
echo ""
echo "Available commands:"
echo "  sudo systemctl enable provisioning-platform    # Enable auto-start on boot"
echo "  sudo systemctl start provisioning-platform     # Start all services"
echo "  sudo systemctl status provisioning-platform    # Check status"
echo "  sudo systemctl stop provisioning-platform      # Stop all services"
echo ""
echo "Individual services:"
echo "  sudo systemctl start provisioning-orchestrator"
echo "  sudo systemctl start provisioning-control-center"
echo ""
echo "To enable and start now:"
echo "  sudo systemctl enable --now provisioning-platform"
