#!/bin/bash

# --- Configuration ---
SERVICE_NAME="well-svc-alert"
SERVICE_USER="wellsvc"       # Recommended: Dedicated user
SERVICE_GROUP="wellsvc"      # Recommended: Dedicated group
APP_DIR="/opt/well_service/alert" # Directory for this specific service
ENV_FILE_PATH="/etc/default/${SERVICE_NAME}" # Path for credentials file
SCRIPT_SOURCE="./well-svc-alert.py"        # Source script
SERVICE_FILE_SOURCE="./well-svc-alert.service" # Source systemd unit file

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

echo "Starting Well Service Alert Setup..."

# --- Dependency Installation ---
echo "Updating package list..."
apt-get update

echo "Installing Python3, Pip, PostgreSQL client dev headers, Redis server & Python clients..."
# Install system packages where possible
# build-essential & python3-dev often needed for pip installs compiling C extensions
apt-get install -y python3 python3-pip python3-dev libpq-dev \
                   redis-server python3-redis python3-psycopg2 \
                   build-essential

# Verify Redis Python client install method if system package isn't preferred
# apt-get install -y python3 python3-pip python3-dev libpq-dev redis-server build-essential
# pip3 install redis psycopg2-binary

# Ensure Redis is enabled and started (optional, Systemd `Requires` handles it for the service)
# systemctl enable redis-server.service
# systemctl start redis-server.service

# --- Create Service User ---
echo "Checking/Creating service user '$SERVICE_USER' and group '$SERVICE_GROUP'..."
if ! getent group "$SERVICE_GROUP" > /dev/null; then
    groupadd --system "$SERVICE_GROUP"
    echo "Group '$SERVICE_GROUP' created."
fi
if ! id "$SERVICE_USER" > /dev/null; then
    useradd --system --gid "$SERVICE_GROUP" --home "$(dirname $APP_DIR)" --no-create-home --shell /bin/false "$SERVICE_USER"
    echo "System user '$SERVICE_USER' created and added to group '$SERVICE_GROUP'."
else
    echo "User '$SERVICE_USER' already exists."
    # Optionally add existing user to group if not already member
    # usermod -a -G "$SERVICE_GROUP" "$SERVICE_USER"
fi

# --- Create Application Directory ---
echo "Creating application directory '$APP_DIR'..."
mkdir -p "$APP_DIR"
if [ ! -d "$APP_DIR" ]; then
    echo "ERROR: Failed to create directory $APP_DIR"
    exit 1
fi

# --- Copy Application Files ---
echo "Copying service script..."
cp "$SCRIPT_SOURCE" "$APP_DIR/well-svc-alert.py"
if [ $? -ne 0 ]; then echo "ERROR: Failed to copy script."; exit 1; fi

# --- Set Permissions ---
echo "Setting permissions for '$APP_DIR'..."
chown -R "$SERVICE_USER":"$SERVICE_GROUP" "$APP_DIR"
# Owner: rwx, Group: rx, Other: ---
chmod -R 750 "$APP_DIR"
chmod +x "$APP_DIR/well-svc-alert.py"

# --- Create Environment File ---
echo "Creating environment file at '$ENV_FILE_PATH'..."
if [ -f "$ENV_FILE_PATH" ]; then
    echo "WARN: Environment file '$ENV_FILE_PATH' already exists. Backing up to ${ENV_FILE_PATH}.bak"
    cp "$ENV_FILE_PATH" "${ENV_FILE_PATH}.bak"
fi
cat > "$ENV_FILE_PATH" << EOF
# Environment variables for the ${SERVICE_NAME} service
# --- PLEASE FILL IN YOUR ACTUAL DATABASE CREDENTIALS ---
DB_NAME=your_database_name
DB_USER=your_database_user
DB_PASSWORD=your_secret_password
DB_HOST=localhost
DB_PORT=5432

# --- Optional Redis Configuration (Defaults are usually fine) ---
# REDIS_HOST=localhost
# REDIS_PORT=6379
# REDIS_DB=0
# REDIS_PASSWORD=your_redis_password_if_any
EOF
if [ $? -ne 0 ]; then echo "ERROR: Failed to create environment file."; exit 1; fi

# --- Set Environment File Permissions ---
echo "Setting permissions for '$ENV_FILE_PATH' (readable by root and $SERVICE_GROUP only)"
chown root:"$SERVICE_GROUP" "$ENV_FILE_PATH"
chmod 640 "$ENV_FILE_PATH" # Owner(root): rw, Group(wellsvc): r, Other: ---

# --- Install Systemd Service ---
echo "Copying Systemd service file..."
cp "$SERVICE_FILE_SOURCE" "/etc/systemd/system/${SERVICE_NAME}.service"
if [ $? -ne 0 ]; then echo "ERROR: Failed to copy systemd file."; exit 1; fi

# --- Update Paths/User in Systemd File ---
echo "Updating configuration in /etc/systemd/system/${SERVICE_NAME}.service ..."
ESCAPED_APP_DIR=$(printf '%s\n' "$APP_DIR" | sed 's:/:\\/:g')
# Use placeholders like {{USER}}, {{GROUP}}, {{WORKDIR}}, {{EXECSTART}}, {{ENVFILE}} in the source .service file
# Or use the sed commands carefully like below:
sed -i "s/^User=.*/User=$SERVICE_USER/" "/etc/systemd/system/${SERVICE_NAME}.service"
sed -i "s/^Group=.*/Group=$SERVICE_GROUP/" "/etc/systemd/system/${SERVICE_NAME}.service"
sed -i "s:^WorkingDirectory=.*:WorkingDirectory=$ESCAPED_APP_DIR:" "/etc/systemd/system/${SERVICE_NAME}.service"
sed -i "s:^ExecStart=.*:ExecStart=/usr/bin/python3 $ESCAPED_APP_DIR/well-svc-alert.py:" "/etc/systemd/system/${SERVICE_NAME}.service"
sed -i "s:^EnvironmentFile=.*:EnvironmentFile=$ENV_FILE_PATH:" "/etc/systemd/system/${SERVICE_NAME}.service"


# --- Configure Systemd ---
echo "Reloading Systemd daemon..."
systemctl daemon-reload

echo "Enabling service '$SERVICE_NAME' to start on boot..."
systemctl enable "${SERVICE_NAME}.service"

# Don't start immediately - user needs to edit the ENV_FILE_PATH first!
# systemctl start "${SERVICE_NAME}.service"

# --- Final Instructions ---
echo "Setup presque terminé!"
echo ""
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo "!! ACTION REQUISE : Modifiez le fichier d'environnement     !!"
echo "!! avec vos informations d'identification de base de données:"
echo "!! sudo nano ${ENV_FILE_PATH}"
echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
echo ""
echo "Après avoir modifié le fichier, démarrez le service avec :"
echo "sudo systemctl start ${SERVICE_NAME}.service"
echo ""
echo "Pour vérifier l'état du service:"
echo "sudo systemctl status ${SERVICE_NAME}.service --no-pager"
echo ""
echo "Pour consulter les journaux:"
echo "sudo journalctl -u ${SERVICE_NAME}.service -f"
echo ""
echo "Pour arrêter le service:"
echo "sudo systemctl stop ${SERVICE_NAME}.service"
echo ""
echo "Pour désactiver le démarrage automatique:"
echo "sudo systemctl disable ${SERVICE_NAME}.service"
echo "---"

exit 0