#!/bin/bash
set -e

GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

INSTALL_DIR="${HOME}/rmm-server"

echo ""
echo "  RMM Server Installer"
echo "  ===================="
echo ""

if ! command -v docker &> /dev/null; then
    echo -e "${YELLOW}Docker not found. Installing...${NC}"
    curl -fsSL https://get.docker.com | sh
    sudo usermod -aG docker "$USER" 2>/dev/null || true
fi

if ! docker compose version &> /dev/null 2>&1 && ! docker-compose version &> /dev/null 2>&1; then
    echo -e "${YELLOW}Installing Docker Compose plugin...${NC}"
    sudo apt-get install -y docker-compose-plugin 2>/dev/null || true
fi

if [ -z "$SOURCE_URL" ]; then
    echo "Enter the URL of your Replit/RMM app (e.g. https://xxxx.replit.dev):"
    read -r BASE_URL
    BASE_URL="${BASE_URL%/}"
    SOURCE_URL="$BASE_URL/downloads/rmm-source.tar.gz"
fi

echo ""
echo -e "${GREEN}Downloading from: $SOURCE_URL${NC}"
mkdir -p "$INSTALL_DIR"
wget -q --show-progress -O /tmp/rmm-source.tar.gz "$SOURCE_URL"
tar -xzf /tmp/rmm-source.tar.gz -C "$INSTALL_DIR"
rm /tmp/rmm-source.tar.gz

cd "$INSTALL_DIR"
chmod +x setup.sh

echo ""
echo -e "${GREEN}Files ready. Starting setup...${NC}"
echo ""

./setup.sh
