#!/usr/bin/env bash
#
# Discourse One-Line Installer
#
# Usage:
#   wget -qO- https://raw.githubusercontent.com/discourse/discourse_docker/main/install-discourse | sudo bash
#
# Or with options:
#   wget -qO- ... | sudo bash -s -- --skip-rebuild
#

set -e

# Configuration
INSTALL_DIR="${DISCOURSE_INSTALL_DIR:-/var/discourse}"
REPO_URL="https://github.com/discourse/discourse_docker.git"
BRANCH="${DISCOURSE_BRANCH:-main}"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
BOLD='\033[1m'
NC='\033[0m'

log_info() {
    echo -e "${GREEN}→${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}!${NC} $1"
}

log_error() {
    echo -e "${RED}✗${NC} $1"
}

log_step() {
    echo -e "${BLUE}${BOLD}==>${NC}${BOLD} $1${NC}"
}

# Check if running as root
check_root() {
    if [[ $EUID -ne 0 ]]; then
        log_error "This script must be run as root."
        echo
        echo "Please run with sudo:"
        echo "  wget -qO- https://raw.githubusercontent.com/discourse/discourse_docker/main/install-discourse | sudo bash"
        exit 1
    fi
}

# Download a URL to stdout (works with wget or curl)
fetch() {
    if command -v wget &> /dev/null; then
        wget -qO- "$1"
    elif command -v curl &> /dev/null; then
        curl -fsSL "$1"
    else
        log_error "Neither wget nor curl found. Please install one and re-run."
        exit 1
    fi
}

# Install Docker if not present
install_docker() {
    if command -v docker &> /dev/null; then
        log_info "Docker is already installed"
        return 0
    fi

    log_step "Installing Docker"
    fetch https://get.docker.com | sh

    systemctl start docker
    systemctl enable docker

    log_info "Docker installed successfully"
}

# Install git if not present
install_git() {
    if command -v git &> /dev/null; then
        return 0
    fi

    log_info "Installing git..."

    if command -v apt-get &> /dev/null; then
        apt-get update -qq && apt-get install -y -qq git
    elif command -v dnf &> /dev/null; then
        dnf -y install git
    elif command -v yum &> /dev/null; then
        yum -y install git
    else
        log_error "Could not install git. Please install git manually and re-run."
        exit 1
    fi
}

# Clone or update the repository
setup_repo() {
    log_step "Setting up Discourse Docker"

    if [[ -d "$INSTALL_DIR/.git" ]]; then
        log_info "Existing installation found at $INSTALL_DIR"
        log_info "Updating repository..."
        cd "$INSTALL_DIR"
        git fetch origin
        git reset --hard "origin/$BRANCH"
    else
        if [[ -d "$INSTALL_DIR" ]] && [[ "$(ls -A "$INSTALL_DIR")" ]]; then
            log_warn "$INSTALL_DIR exists and is not empty"
            log_info "Backing up to ${INSTALL_DIR}.backup.$(date +%Y%m%d%H%M%S)"
            mv "$INSTALL_DIR" "${INSTALL_DIR}.backup.$(date +%Y%m%d%H%M%S)"
        fi

        log_info "Cloning discourse_docker to $INSTALL_DIR..."
        git clone --depth=1 --branch "$BRANCH" "$REPO_URL" "$INSTALL_DIR"
    fi

    cd "$INSTALL_DIR"
    log_info "Repository ready at $INSTALL_DIR"
}

# Run the setup wizard
run_wizard() {
    log_step "Starting Discourse Setup Wizard"
    echo

    cd "$INSTALL_DIR"

    if [[ -x "./discourse-setup" ]]; then
        exec ./discourse-setup "$@"
    else
        log_error "Setup script not found in $INSTALL_DIR"
        exit 1
    fi
}

# Show help
show_help() {
    cat <<EOF
Discourse One-Line Installer

Usage:
    wget -qO- https://raw.githubusercontent.com/discourse/discourse_docker/main/install-discourse | sudo bash
    wget -qO- ... | sudo bash -s -- [OPTIONS]

Options:
    --skip-rebuild          Skip the container rebuild after configuration
    --skip-connection-test  Skip DNS/port connectivity tests
    --debug                 Enable debug mode
    --help, -h              Show this help message

Environment Variables:
    DISCOURSE_INSTALL_DIR   Installation directory (default: /var/discourse)
    DISCOURSE_BRANCH        Git branch to use (default: main)

This script will:
    1. Install Docker if not present
    2. Clone/update the discourse_docker repository
    3. Run the interactive setup wizard (which checks system requirements)

For more information, visit: https://github.com/discourse/discourse_docker

EOF
}

# Parse arguments for help only (rest passed to wizard)
for arg in "$@"; do
    case "$arg" in
        --help|-h)
            show_help
            exit 0
            ;;
    esac
done

# Main
echo
echo -e "${BOLD}Discourse One-Line Installer${NC}"
echo

check_root
install_git
install_docker
setup_repo
run_wizard "$@"
