#!/bin/bash
set -e

# Configuration
SERVICE_NAME="envoy-logger"
INSTALL_DIR="/opt/${SERVICE_NAME}"
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"

echo "=== Installing Envoy Logger systemd Service ==="

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

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

# Create installation directory
echo "Creating installation directory: ${INSTALL_DIR}"
mkdir -p "${INSTALL_DIR}"

# Copy project files
echo "Copying project files..."
cp "${SCRIPT_DIR}/main.py" "${INSTALL_DIR}/"
cp "${SCRIPT_DIR}/dispenser_action.py" "${INSTALL_DIR}/"
cp "${SCRIPT_DIR}/f53_errors.py" "${INSTALL_DIR}/"
if [ -f "${SCRIPT_DIR}/pyproject.toml" ]; then
    cp "${SCRIPT_DIR}/pyproject.toml" "${INSTALL_DIR}/"
fi

# Create systemd service file
echo "Creating systemd service file: ${SERVICE_FILE}"
cat > "${SERVICE_FILE}" << 'EOF'
[Unit]
Description=Envoy Graylog Python Logger
[Service]
User=freedomgateway
WorkingDirectory=/opt/envoy-logger
ExecStart=python main.py
Restart=always
RestartSec=3
SyslogIdentifier=envoy-logger
EnvironmentFile=/etc/environment

[Install]
WantedBy=multi-user.target
EOF

chmod 644 "${SERVICE_FILE}"

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

# Enable and start the service
echo "Enabling ${SERVICE_NAME} service..."
systemctl enable "${SERVICE_NAME}.service"

echo "Starting ${SERVICE_NAME} service..."
systemctl start "${SERVICE_NAME}.service"

echo "Installation complete!"
echo
echo "Service status:"
systemctl status "${SERVICE_NAME}.service" --no-pager

echo
echo "Useful commands:"
echo "  View logs:       sudo journalctl -u ${SERVICE_NAME} -f"
echo "  Restart service: sudo systemctl restart ${SERVICE_NAME}"
echo "  Stop service:    sudo systemctl stop ${SERVICE_NAME}"
