#!/bin/bash

# Exit on any error
set -e

# Check if script is run as root
if [ "$EUID" -ne 0 ]; then
  echo "[-] Please run this script as root (e.g., sudo ./install.sh)"
  exit 1
fi

echo "[+] Starting installation for Media-Coding-Web Systemd Service..."

# Automatically get the absolute path of the directory containing this script
APP_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
echo "[+] Detected application directory: $APP_DIR"

# Ensure Node.js is installed
if ! command -v node >/dev/null 2>&1; then
    echo "[-] Error: Node.js is not installed. Please install Node.js first."
    exit 1
fi

NODE_PATH=$(command -v node)
echo "[+] Found Node.js at: $NODE_PATH"

# Run dependency installation if node_modules doesn't exist
cd "$APP_DIR"
if [ ! -d "node_modules" ]; then
    echo "[+] Installing node dependencies..."
    npm install
else
    echo "[+] node_modules already exists. Skipping npm install."
fi

# Ensure .env exists
if [ ! -f ".env" ]; then
    if [ -f ".env.example" ]; then
        echo "[+] Copying .env.example to .env..."
        cp .env.example .env
        echo "[!] Please verify your .env settings (redis, s3, etc) later."
    else
        echo "[-] Warning: Neither .env nor .env.example was found!"
    fi
fi

# Create SystemD service file
SERVICE_NAME="media-coding-web"
SERVICE_PATH="/etc/systemd/system/${SERVICE_NAME}.service"

echo "[+] Generating systemd service file at $SERVICE_PATH..."

cat > "$SERVICE_PATH" <<EOF
[Unit]
Description=S3 Media Transcoder Web Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=$APP_DIR
ExecStart=$NODE_PATH server.js
Restart=always
RestartSec=5
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target
EOF

# Reload and apply systemd
echo "[+] Reloading systemd daemon..."
systemctl daemon-reload

echo "[+] Enabling $SERVICE_NAME to start on boot..."
systemctl enable "$SERVICE_NAME.service"

echo "[+] Starting $SERVICE_NAME..."
systemctl restart "$SERVICE_NAME.service"

echo 
echo "=========================================================="
echo "[+] Install Complete & Service is Running!"
echo "=========================================================="
echo "- View real-time logs:     journalctl -fu $SERVICE_NAME"
echo "- Check service status:    systemctl status $SERVICE_NAME"
echo "- Stop service:            systemctl stop $SERVICE_NAME"
echo "- Modify config:           nano $APP_DIR/.env"
echo "=========================================================="
