#!/bin/bash

# Ensure script is run as root
if [ "$EUID" -ne 0 ]; then
  echo "Error: Please run as root (use sudo)"
  exit 1
fi

echo "============================================================"
echo "    Uzumaru Global Ping - Worker Deployment Script"
echo "============================================================"
echo ""

echo "Installing nexttrace dependency..."
curl nxtrace.org/nt | bash
echo ""

# Define the installation directory
INSTALL_DIR="/opt/Uzumaru-Global-Ping"
mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR" || exit

# Detect CPU Architecture and set download URL
ARCH=$(uname -m)
if [ "$ARCH" = "x86_64" ] || [ "$ARCH" = "amd64" ]; then
    DOWNLOAD_URL="http://107.189.30.191:5671/Uzumaru-Global-Ping/worker-linux-amd64/worker"
    echo "Detected architecture: amd64"
elif [ "$ARCH" = "aarch64" ] || [ "$ARCH" = "arm64" ]; then
    DOWNLOAD_URL="http://107.189.30.191:5671/Uzumaru-Global-Ping/worker-linux-arm64/worker"
    echo "Detected architecture: arm64"
else
    echo "Error: Unsupported architecture $ARCH"
    exit 1
fi

API_TOKEN="1145141919810@@@"

# Extract filename from URL
FILENAME=$(basename "$DOWNLOAD_URL")
# Strip query parameters if any
FILENAME="${FILENAME%%\?*}"
if [ -z "$FILENAME" ] || [ "$FILENAME" == "download" ]; then
    FILENAME="worker"
fi

echo "Downloading worker binary to $INSTALL_DIR/$FILENAME..."
curl -L -o "$FILENAME" "$DOWNLOAD_URL"
if [ $? -ne 0 ]; then
    echo "Error: Failed to download the file. Please check the URL."
    exit 1
fi

chmod +x "$FILENAME"

echo ""
echo "--- Configuration ---"
read -p "Node Name (e.g., DPNET-Bursa): " NODE_NAME
read -p "Location (e.g., TR): " NODE_LOCATION

read -p "Master URL [default: https://ping-api.osccc.de:443]: " MASTER_URL
MASTER_URL=${MASTER_URL:-https://ping-api.osccc.de:443}

echo "Fetching your public IP..."
PUBLIC_IP=$(curl -s https://ipinfo.io/ip)
echo "Your public IP appears to be: $PUBLIC_IP"
read -p "Worker Host [default: $PUBLIC_IP]: " WORKER_HOST
WORKER_HOST=${WORKER_HOST:-$PUBLIC_IP}

read -p "Worker Port [default: 7892]: " WORKER_PORT
WORKER_PORT=${WORKER_PORT:-7892}

# Verify inputs
if [ -z "$NODE_NAME" ] || [ -z "$NODE_LOCATION" ] || [ -z "$WORKER_HOST" ]; then
    echo "Error: Node Name, Location, and Worker Host are required."
    exit 1
fi

# Detect Init System (systemd vs OpenRC)
if command -v systemctl >/dev/null 2>&1; then
    INIT_SYSTEM="systemd"
elif command -v rc-update >/dev/null 2>&1; then
    INIT_SYSTEM="openrc"
else
    echo "Error: Neither systemd nor OpenRC found. Unsupported OS."
    exit 1
fi

echo ""
echo "Detected Init System: $INIT_SYSTEM"

if [ "$INIT_SYSTEM" = "systemd" ]; then
    # Create systemd service file (Debian, Ubuntu, CentOS, etc.)
    SERVICE_FILE="/etc/systemd/system/uzumaru-ping-worker.service"
    echo "Creating systemd service at $SERVICE_FILE..."

    cat <<EOF > "$SERVICE_FILE"
[Unit]
Description=Uzumaru Ping Worker Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=$INSTALL_DIR
ExecStart=$INSTALL_DIR/$FILENAME --name "$NODE_NAME" --location "$NODE_LOCATION" --master "$MASTER_URL" --host "$WORKER_HOST" --port $WORKER_PORT --token "$API_TOKEN"
Restart=always
RestartSec=5
LimitNOFILE=65536

[Install]
WantedBy=multi-user.target
EOF

    # Reload systemd and enable/start the service
    echo "Reloading systemd daemon..."
    systemctl daemon-reload
    echo "Enabling service to start on boot..."
    systemctl enable uzumaru-ping-worker.service
    echo "Starting/Restarting the service..."
    systemctl restart uzumaru-ping-worker.service

    echo ""
    echo "Useful Commands:"
    echo "  Check Status: systemctl status uzumaru-ping-worker"
    echo "  View Logs:    journalctl -u uzumaru-ping-worker -f"

elif [ "$INIT_SYSTEM" = "openrc" ]; then
    # Create OpenRC service file (Alpine Linux)
    SERVICE_FILE="/etc/init.d/uzumaru-ping-worker"
    echo "Creating OpenRC service at $SERVICE_FILE..."

    cat <<EOF > "$SERVICE_FILE"
#!/sbin/openrc-run

name="Uzumaru Ping Worker"
description="Uzumaru Global Ping Worker Service"
command="$INSTALL_DIR/$FILENAME"
command_args="--name \\"$NODE_NAME\\" --location \\"$NODE_LOCATION\\" --master \\"$MASTER_URL\\" --host \\"$WORKER_HOST\\" --port $WORKER_PORT --token \\"$API_TOKEN\\""
command_background=true
pidfile="/run/uzumaru-ping-worker.pid"
directory="$INSTALL_DIR"
output_log="/var/log/uzumaru-ping-worker.log"
error_log="/var/log/uzumaru-ping-worker.log"

depend() {
    need net
}
EOF

    chmod +x "$SERVICE_FILE"
    
    echo "Enabling service to start on boot..."
    rc-update add uzumaru-ping-worker default
    
    echo "Starting/Restarting the service..."
    rc-service uzumaru-ping-worker restart

    echo ""
    echo "Useful Commands:"
    echo "  Check Status: rc-service uzumaru-ping-worker status"
    echo "  View Logs:    tail -f /var/log/uzumaru-ping-worker.log"
fi

echo "============================================================"
echo "Deployment successful!"
echo "Service is now running and enabled on boot."
echo "============================================================"
