#!/bin/bash
set -e

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

echo ""
echo "  RMM Server Updater"
echo "  ==================="
echo ""

INSTALL_DIR="$(cd "$(dirname "$0")" && pwd)"

if [ ! -f "$INSTALL_DIR/docker-compose.yml" ]; then
    echo -e "${RED}Error: Run this script from your rmm-server install directory.${NC}"
    exit 1
fi

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

echo ""
echo -e "${GREEN}[1/3] Downloading latest source...${NC}"
wget -q --show-progress -O /tmp/rmm-source-update.tar.gz "$SOURCE_URL"

echo -e "${GREEN}[2/3] Extracting update...${NC}"
tar -xzf /tmp/rmm-source-update.tar.gz -C "$INSTALL_DIR" --overwrite
rm /tmp/rmm-source-update.tar.gz
chmod +x "$INSTALL_DIR/setup.sh" "$INSTALL_DIR/update.sh" 2>/dev/null || true

echo -e "${GREEN}[3/3] Rebuilding and restarting containers...${NC}"
COMPOSE_CMD="docker compose"
if ! docker compose version &> /dev/null 2>&1; then
    COMPOSE_CMD="docker-compose"
fi

cd "$INSTALL_DIR"
$COMPOSE_CMD up -d --build

echo ""
echo "=================================================="
echo -e "${GREEN}  Update complete!${NC}"
echo "=================================================="
echo ""
