#!/bin/bash

# Script to set up sudoers rules for queue management
# This allows the web user to manage queue services without password

# Determine the web user (typically www-data)
WEB_USER=${1:-www-data}
SERVICE_NAME="multiportal-queue"

echo "Setting up sudoers rules for $WEB_USER to manage $SERVICE_NAME services..."

# Create a sudoers file for queue management
SUDOERS_FILE="/etc/sudoers.d/multiportal-queue"

# Create the sudoers rules
cat > /tmp/multiportal-queue-sudoers << EOF
# Allow $WEB_USER to manage multiportal-queue services without password
# Using explicit paths and supporting wildcard patterns with \\* 
$WEB_USER ALL=(ALL) NOPASSWD: /usr/bin/systemctl start ${SERVICE_NAME}@*.service
$WEB_USER ALL=(ALL) NOPASSWD: /usr/bin/systemctl stop ${SERVICE_NAME}@*.service
$WEB_USER ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart ${SERVICE_NAME}@*.service
$WEB_USER ALL=(ALL) NOPASSWD: /usr/bin/systemctl status ${SERVICE_NAME}@*.service
$WEB_USER ALL=(ALL) NOPASSWD: /usr/bin/systemctl status ${SERVICE_NAME}@* --no-pager
$WEB_USER ALL=(ALL) NOPASSWD: /usr/bin/systemctl enable ${SERVICE_NAME}@*.service
$WEB_USER ALL=(ALL) NOPASSWD: /usr/bin/systemctl disable ${SERVICE_NAME}@*.service
$WEB_USER ALL=(ALL) NOPASSWD: /usr/bin/systemctl daemon-reload
$WEB_USER ALL=(ALL) NOPASSWD: /usr/bin/systemctl is-active ${SERVICE_NAME}@*.service
$WEB_USER ALL=(ALL) NOPASSWD: /usr/bin/systemctl list-units ${SERVICE_NAME}@*.service
EOF

# Validate the sudoers file
if visudo -c -f /tmp/multiportal-queue-sudoers; then
    # If valid, move it to sudoers.d
    sudo cp /tmp/multiportal-queue-sudoers "$SUDOERS_FILE"
    sudo chmod 0440 "$SUDOERS_FILE"
    echo "Sudoers rules successfully installed to $SUDOERS_FILE"
    echo ""
    echo "The $WEB_USER user can now manage queue services without password."
    echo ""
    echo "Test with: sudo -u $WEB_USER systemctl status ${SERVICE_NAME}@*.service"
else
    echo "Error: Invalid sudoers syntax. File not installed."
    exit 1
fi

# Clean up
rm -f /tmp/multiportal-queue-sudoers

echo ""
echo "Note: These permissions allow $WEB_USER to:"
echo "  - Start/Stop/Restart queue workers"
echo "  - Check queue worker status"
echo "  - Enable/Disable queue workers"
echo "  - Reload systemd daemon"
echo ""
echo "For security, only ${SERVICE_NAME}@*.service can be managed."