#!/bin/bash
# Gateway Type 3 - Install as systemd Service
# Installs the gateway as a systemd service for automatic startup
#
# Usage: sudo bash install-service.sh
# Output: RESULT:installed=true|false

set -e

# Get script directory and project directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(dirname "$SCRIPT_DIR")"

# If running from node_modules, find the actual install dir
if [[ "$PROJECT_DIR" == *"node_modules"* ]]; then
    # scripts -> langmart-gateway-type3 -> node_modules -> INSTALL_DIR
    INSTALL_DIR="$(cd "$PROJECT_DIR/../.." && pwd)"
else
    INSTALL_DIR="$PROJECT_DIR"
fi

# Configuration
SERVICE_NAME="langmart-gateway"
ENV_FILE="${INSTALL_DIR}/.env"

# Log function
log() {
    local level="${2:-INFO}"
    local timestamp=$(date +"%H:%M:%S")
    echo "[$level] $timestamp - $1"
}

log "=== Gateway Type 3 Install Service ==="
log "Install directory: $INSTALL_DIR"

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

# Check if systemd is available
if ! command -v systemctl &> /dev/null; then
    log "systemd not found - this script only supports systemd-based systems" "ERROR"
    echo "RESULT:installed=false"
    exit 1
fi

# Load .env to get configuration
if [ -f "$ENV_FILE" ]; then
    set -a
    source "$ENV_FILE"
    set +a
else
    log ".env file not found at $ENV_FILE" "ERROR"
    log "Create .env file with at least GATEWAY_API_KEY and MARKETPLACE_URL"
    echo "RESULT:installed=false"
    exit 1
fi

# Get the user who owns the install directory
INSTALL_USER=$(stat -c '%U' "$INSTALL_DIR")
INSTALL_GROUP=$(stat -c '%G' "$INSTALL_DIR")

# Find Node.js binary
if [ -f "$INSTALL_DIR/node/bin/node" ]; then
    NODE_BIN="$INSTALL_DIR/node/bin/node"
elif command -v node &> /dev/null; then
    NODE_BIN=$(which node)
else
    log "Node.js not found" "ERROR"
    echo "RESULT:installed=false"
    exit 1
fi

# Find entry file
if [ -f "$INSTALL_DIR/node_modules/langmart-gateway-type3/dist/index-server.js" ]; then
    ENTRY_FILE="$INSTALL_DIR/node_modules/langmart-gateway-type3/dist/index-server.js"
elif [ -f "$PROJECT_DIR/dist/index-server.js" ]; then
    ENTRY_FILE="$PROJECT_DIR/dist/index-server.js"
else
    log "Entry file not found" "ERROR"
    echo "RESULT:installed=false"
    exit 1
fi

log "Service name: $SERVICE_NAME"
log "Node.js: $NODE_BIN"
log "Entry file: $ENTRY_FILE"
log "Run as user: $INSTALL_USER"

# Check if service already exists
if systemctl list-unit-files | grep -q "^${SERVICE_NAME}.service"; then
    log "Service already exists, will be overwritten" "WARN"
    systemctl stop "$SERVICE_NAME" 2>/dev/null || true
    systemctl disable "$SERVICE_NAME" 2>/dev/null || true
fi

# Create systemd service file
SERVICE_FILE="/etc/systemd/system/${SERVICE_NAME}.service"

log "Creating service file: $SERVICE_FILE"

cat > "$SERVICE_FILE" << EOF
[Unit]
Description=LangMart Gateway Type 3
Documentation=https://github.com/langmart/gateway-type3
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$INSTALL_USER
Group=$INSTALL_GROUP
WorkingDirectory=$INSTALL_DIR
EnvironmentFile=$ENV_FILE
ExecStart=$NODE_BIN $ENTRY_FILE
Restart=on-failure
RestartSec=10
StandardOutput=append:$INSTALL_DIR/logs/gateway.log
StandardError=append:$INSTALL_DIR/logs/gateway.log

# Security hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=read-only
ReadWritePaths=$INSTALL_DIR

# Resource limits
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
EOF

# Create logs directory if not exists
mkdir -p "$INSTALL_DIR/logs"
chown "$INSTALL_USER:$INSTALL_GROUP" "$INSTALL_DIR/logs"

# Create service marker file
echo "systemd" > "$INSTALL_DIR/.service-mode"
chown "$INSTALL_USER:$INSTALL_GROUP" "$INSTALL_DIR/.service-mode"

# Reload systemd and enable service
log "Reloading systemd daemon..."
systemctl daemon-reload

log "Enabling service..."
systemctl enable "$SERVICE_NAME"

log "Service installed successfully" "SUCCESS"
log ""
log "Commands:"
log "  Start:   sudo systemctl start $SERVICE_NAME"
log "  Stop:    sudo systemctl stop $SERVICE_NAME"
log "  Status:  sudo systemctl status $SERVICE_NAME"
log "  Logs:    sudo journalctl -u $SERVICE_NAME -f"
log ""
log "Or use the gateway scripts:"
log "  bash $SCRIPT_DIR/start.sh"
log "  bash $SCRIPT_DIR/stop.sh"
log "  bash $SCRIPT_DIR/status.sh"

echo "RESULT:installed=true"
exit 0
