#!/usr/bin/env bash
set -euo pipefail

####################################################################
# Koro ERP — One-Command Installer
#
# Downloads all required files and runs the interactive installer.
#
# Usage — from the website:
#   curl -fsSL https://YOUR_DOMAIN/deploy/get-koroerp.sh | bash
#
# The script auto-detects the download URL from where it was fetched.
# Override with KORO_DOWNLOAD_URL if needed:
#   curl -fsSL .../get-koroerp.sh | KORO_DOWNLOAD_URL=https://example.com/deploy bash
####################################################################

# ── Configuration ────────────────────────────────────────────────
# If KORO_DOWNLOAD_URL is set, use it. Otherwise, try to auto-detect
# from the URL this script was downloaded from (set by the website's
# setup page as an env variable before piping to bash).
BASE_URL="${KORO_DOWNLOAD_URL:-https://koroworks.com/deploy}"

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

info()  { echo -e "${BLUE}[INFO]${NC}  $*"; }
ok()    { echo -e "${GREEN}  [OK]${NC}  $*"; }
fail()  { echo -e "${RED}[FAIL]${NC}  $*"; exit 1; }

# ── Banner ───────────────────────────────────────────────────────
echo ""
echo -e "${BOLD}${BLUE}╔═══════════════════════════════════════════════════════════╗${NC}"
echo -e "${BOLD}${BLUE}║           Koro ERP — One-Command Installer               ║${NC}"
echo -e "${BOLD}${BLUE}╚═══════════════════════════════════════════════════════════╝${NC}"
echo ""
info "Download URL: $BASE_URL"
echo ""

# ── Prerequisites ────────────────────────────────────────────────
if ! command -v curl >/dev/null 2>&1 && ! command -v wget >/dev/null 2>&1; then
  fail "curl or wget is required. Install one and try again."
fi

# Download helper — tries curl first, falls back to wget
dl() {
  local url="$1" dest="$2"
  mkdir -p "$(dirname "$dest")"
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$url" -o "$dest"
  else
    wget -q "$url" -O "$dest"
  fi
}

# ── Create install directory ─────────────────────────────────────
INSTALL_DIR="${KORO_INSTALL_DIR:-$(pwd)/koro-erp}"

if [ -d "$INSTALL_DIR" ] && [ -f "$INSTALL_DIR/apis/docker-compose.yml" ]; then
  info "Existing installation found at $INSTALL_DIR"
  echo -en "  ${YELLOW}[?]${NC}  Re-download files? Existing .env and keys will be kept. [y/N]: "
  read -r overwrite
  if [[ ! "$overwrite" =~ ^[Yy] ]]; then
    info "Skipping download — running installer..."
    cd "$INSTALL_DIR"
    exec bash install.sh "$@"
  fi
fi

mkdir -p "$INSTALL_DIR"
cd "$INSTALL_DIR"

# ── Download all files ───────────────────────────────────────────
info "Downloading Koro ERP files..."

FILES=(
  "apis/docker-compose.yml"
  "apis/.env.example"
  "apis/install.sh"
  "apis/install.ps1"
  "apis/install-binaries.sh"
  "apis/install-binaries.ps1"
  "apis/caddy/Caddyfile"
  "apps/docker-compose.yml"
  "ai/docker-compose.yml"
  "ai/.env.example"
  "ai/install.sh"
  "ai/install.ps1"
  "ai/link.sh"
  "ai/link.ps1"
  "ai/caddy/Caddyfile"
  "install.sh"
  "install.ps1"
  "manage.sh"
)

for f in "${FILES[@]}"; do
  dl "${BASE_URL}/${f}" "${f}" 2>/dev/null && ok "$f" || fail "Failed to download $f"
done

chmod +x install.sh apis/install.sh apis/install-binaries.sh ai/install.sh

ok "All files downloaded to $INSTALL_DIR"

# ── Run the installer ───────────────────────────────────────────
echo ""
info "Starting installer..."
echo ""
if [[ -r /dev/tty ]]; then
  exec bash install.sh "$@" </dev/tty
fi
fail "Interactive terminal is required. Download the files first, then run: bash install.sh"
