#!/bin/bash
#
# Cratus RustDesk One-Liner Install Script
#   Usage: curl -sL https://rustdesk.cratustech.com/install.sh | sudo bash
#   Custom password: curl -sL https://rustdesk.cratustech.com/install.sh | sudo bash -s -- -p YOUR_PASSWORD
#

set -e

RUSTDESK_VERSION="1.4.5"
RUSTDESK_SERVER="rustdesk.cratustech.com"
RUSTDESK_KEY="sK5LWiELZa4bfbdFC98j7lvUqleeb6i0OC7w2agECzs="
DEFAULT_PASSWORD="Pass4rustdesk@202510"
RUSTDESK_BASE_URL="https://github.com/rustdesk/rustdesk/releases/download/${RUSTDESK_VERSION}"
DOWNLOAD_DIR="/tmp/cratus-rustdesk"

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
RED='\033[0;31m'
NC='\033[0m'
BOLD='\033[1m'
DIM='\033[2m'

# Print step header
step() {
    local current=$1
    local total=$2
    local msg=$3
    echo ""
    echo -e "${BOLD}[${current}/${total}]${NC} ${YELLOW}${msg}${NC}"
}

# Print success line
ok() {
    echo -e "  ${GREEN}✓${NC} $1"
}

# Print info line
info() {
    echo -e "  ${DIM}→${NC} $1"
}

# Parse arguments
PASSWORD="$DEFAULT_PASSWORD"
while getopts "p:" opt; do
    case $opt in
        p) PASSWORD="$OPTARG" ;;
        *) echo "Usage: $0 [-p password]"; exit 1 ;;
    esac
done

# Check root
if [ "$(id -u)" != "0" ]; then
    echo -e "${RED}Error: This script must be run as root (use sudo).${NC}"
    exit 1
fi

echo ""
echo -e "${BOLD}╔═══════════════════════════════════════╗${NC}"
echo -e "${BOLD}║     Cratus RustDesk Installer v1.1    ║${NC}"
echo -e "${BOLD}╚═══════════════════════════════════════╝${NC}"

# Detect architecture
ARCH=$(uname -m)
case "$ARCH" in
    x86_64)
        DEB="rustdesk-${RUSTDESK_VERSION}-x86_64.deb"
        ;;
    aarch64|arm64)
        DEB="rustdesk-${RUSTDESK_VERSION}-aarch64.deb"
        ;;
    armv7l|armhf)
        DEB="rustdesk-${RUSTDESK_VERSION}-armhf.deb"
        ;;
    *)
        echo -e "${RED}Error: Unsupported architecture: $ARCH${NC}"
        exit 1
        ;;
esac

echo -e "  Platform: ${CYAN}${ARCH}${NC} | RustDesk: ${CYAN}v${RUSTDESK_VERSION}${NC}"

# Step 1 - Dependencies (verbose so user can see progress)
step 1 6 "Installing dependencies"
info "Updating package lists..."
apt-get update -q 2>&1 | tail -1
info "Installing packages (this may take a few minutes)..."
DEBIAN_FRONTEND=noninteractive apt-get install -y \
    xserver-xorg-video-dummy \
    xorg \
    lightdm \
    openbox \
    pulseaudio \
    libxcb-randr0 \
    libxdo3 \
    libxfixes3 \
    libxcb-shape0 \
    libxcb-xfixes0 \
    libgtk-3-0 \
    libgdk-pixbuf2.0-0 \
    libasound2 \
    curl 2>&1 | grep -E "^(Get:|Hit:|Unpacking|Setting up|is already)" | while read -r line; do
        printf "\r  ${DIM}  %s${NC}%*s" "${line:0:60}" 20 ""
    done
printf "\r%*s\r" 80 ""
ok "Dependencies installed"

# Step 2 - Download
step 2 6 "Downloading RustDesk"
mkdir -p "$DOWNLOAD_DIR"
info "Downloading ${DEB}..."
curl -L --progress-bar -o "${DOWNLOAD_DIR}/${DEB}" "${RUSTDESK_BASE_URL}/${DEB}" 2>&1

if [ ! -f "${DOWNLOAD_DIR}/${DEB}" ]; then
    echo -e "  ${RED}✗${NC} Download failed."
    exit 1
fi
ok "Downloaded $(du -h "${DOWNLOAD_DIR}/${DEB}" | cut -f1)"

# Step 3 - Install
step 3 6 "Installing RustDesk"
info "Installing .deb package..."
apt-get install -y "${DOWNLOAD_DIR}/${DEB}" 2>&1 | grep -E "^(Unpacking|Setting up)" || true
apt-get --fix-broken install -y > /dev/null 2>&1

if ! command -v rustdesk &> /dev/null; then
    echo -e "  ${RED}✗${NC} RustDesk installation failed."
    exit 2
fi
ok "RustDesk installed"

# Step 4 - Headless display
step 4 6 "Configuring headless display"
mkdir -p /etc/X11/xorg.conf.d
cat > /etc/X11/xorg.conf.d/10-headless.conf << 'XORGEOF'
Section "Monitor"
    Identifier "dummy_monitor"
    HorizSync 28.0-80.0
    VertRefresh 48.0-75.0
    Modeline "1920x1080" 172.80 1920 2040 2248 2576 1080 1081 1084 1118
EndSection

Section "Device"
    Identifier "dummy_card"
    VideoRam 256000
    Driver "dummy"
EndSection

Section "Screen"
    Identifier "dummy_screen"
    Device "dummy_card"
    Monitor "dummy_monitor"
    SubSection "Display"
        Depth 24
        Modes "1920x1080"
    EndSubSection
EndSection
XORGEOF

systemctl start lightdm.service 2>/dev/null || true
ok "Xorg dummy display configured"
sleep 3

# Step 5 - Server config
step 5 6 "Configuring server connection"
RUSTDESK_CONFIG="rendezvous_server = '${RUSTDESK_SERVER}'
nat_type = 1
serial = 0
unlock_pin = ''
trusted_devices = ''

[options]
custom-rendezvous-server = '${RUSTDESK_SERVER}'
allow-linux-headless = 'Y'
relay-server = '${RUSTDESK_SERVER}'
av1-test = 'N'
key = '${RUSTDESK_KEY}'"

RUSTDESK_TOML="${RUSTDESK_SERVER} = true"

# Write config for root
mkdir -p /root/.config/rustdesk
echo "$RUSTDESK_CONFIG" > /root/.config/rustdesk/RustDesk2.toml
echo "$RUSTDESK_TOML" > /root/.config/rustdesk/RustDesk.toml

# Write config for all users
USER_COUNT=0
for USER_HOME in /home/*; do
    if [ -d "$USER_HOME" ]; then
        USERNAME=$(basename "$USER_HOME")
        CONFIG_DIR="$USER_HOME/.config/rustdesk"
        mkdir -p "$CONFIG_DIR"
        echo "$RUSTDESK_CONFIG" > "$CONFIG_DIR/RustDesk2.toml"
        echo "$RUSTDESK_TOML" > "$CONFIG_DIR/RustDesk.toml"
        chown -R "$USERNAME:$USERNAME" "$CONFIG_DIR"
        USER_COUNT=$((USER_COUNT + 1))
    fi
done
ok "Server: ${CYAN}${RUSTDESK_SERVER}${NC}"
ok "Configured for $((USER_COUNT + 1)) user(s)"

# Step 6 - Start service
step 6 6 "Starting service"
systemctl daemon-reload
systemctl enable rustdesk.service > /dev/null 2>&1
systemctl restart rustdesk
ok "RustDesk service enabled and started"
info "Waiting for service to initialize..."
sleep 5

# Set password
rustdesk --password "$PASSWORD"
ok "Password set"

# Get RustDesk ID
RUSTDESK_ID=$(rustdesk --get-id 2>/dev/null || echo "unknown")

echo ""
echo -e "${GREEN}╔═══════════════════════════════════════╗${NC}"
echo -e "${GREEN}║      Installation Complete!           ║${NC}"
echo -e "${GREEN}╠═══════════════════════════════════════╣${NC}"
echo -e "${GREEN}║${NC}  ID:       ${BOLD}${RUSTDESK_ID}${NC}"
echo -e "${GREEN}║${NC}  Password: ${BOLD}${PASSWORD}${NC}"
echo -e "${GREEN}║${NC}  Server:   ${BOLD}${RUSTDESK_SERVER}${NC}"
echo -e "${GREEN}╚═══════════════════════════════════════╝${NC}"
echo ""

# Cleanup
rm -rf "$DOWNLOAD_DIR"
