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

echo "[WGRplane] Easy Install Script – install.sh"

# Detect OS
if [ -f /etc/os-release ]; then
  . /etc/os-release
fi
OS_ID=${ID:-unknown}
OS_CODENAME=${VERSION_CODENAME:-unknown}

echo "Detected OS: $OS_ID ($OS_CODENAME)"

install_docker_apt() {
  echo "[WGRplane] Installing Docker and dependencies via apt (Debian/Ubuntu)..."
  sudo apt-get update -y
  sudo apt-get install -y ca-certificates curl gnupg lsb-release
  # Try to install docker.io as the simplest path
  if ! command -v docker >/dev/null 2>&1; then
    if apt-cache show docker.io >/dev/null 2>&1; then
      sudo apt-get install -y docker.io
    else
      echo "[WGRplane] Fallback: installing docker-ce from Docker's official repo..."
      curl -fsSL https://get.docker.com -o get-docker.sh
      sudo sh get-docker.sh
      rm -f get-docker.sh
    fi
  fi
  sudo systemctl enable --now docker || true

  # Install Docker Compose (plugin-based or legacy)
  if command -v docker-compose >/dev/null 2>&1; then
    echo "[WGRplane] docker-compose already installed (legacy)."
  elif command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then
    echo "[WGRplane] docker-compose is available as a Docker plugin (docker compose)."
  else
    echo "[WGRplane] Installing docker-compose (latest)"
    # Try to install the latest release without hardcoding version
    if command -v curl >/dev/null 2>&1; then
      LATEST_URL=$(curl -fsSL https://api.github.com/repos/docker/compose/releases/latest 2>/dev/null | grep -o 'https://[^\"]*linux-$(uname -m\)' || true)
      if [ -z "$LATEST_URL" ]; then
        LATEST_URL="https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)"
      fi
      sudo sh -c "curl -L $LATEST_URL -o /usr/local/bin/docker-compose && chmod +x /usr/local/bin/docker-compose"
      if command -v docker-compose >/dev/null 2>&1; then
        echo "[WGRplane] docker-compose installed at /usr/local/bin/docker-compose"
      fi
    else
      echo "[WGRplane] curl not available. Skipping docker-compose installation."
    fi
  fi
}

install_docker_yum() {
  echo "[WGRplane] Installing Docker via yum/dnf (CentOS/RHEL)..."
  if command -v dnf >/dev/null 2>&1; then
    sudo dnf -y install dnf-plugins-core
    sudo dnf config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
    sudo dnf -y install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
  else
    sudo yum -y install yum-utils
    sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
    sudo yum -y install docker-ce docker-ce-cli containerd.io
  fi
  sudo systemctl enable --now docker || true
}

case "$OS_ID" in
  ubuntu|debian)
    install_docker_apt
    ;;
  centos|fedora|rhel|amazon)
    install_docker_yum
    ;;
  *)
    echo "[WGRplane] Unsupported OS for automated install. Please install Docker manually."; exit 1
    ;;
esac

echo "[WGRplane] Docker verification: $(docker --version 2>&1 || echo 'not found')"
if command -v docker-compose >/dev/null 2>&1; then
  echo "[WGRplane] docker-compose is available: $(docker-compose --version 2>&1)"
elif command -v docker >/dev/null 2>&1 && docker compose version >/dev/null 2>&1; then
  echo "[WGRplane] docker compose (plugin) is available: $(docker compose version | tr -d '\n')"
else
  echo "[WGRplane] Docker Compose not detected. Attempting to install via Docker plugin if possible..."
fi

# Clone repo if not present
REPO_URL_VAR="${GIT_REPO:-}"
if [ -d .git ]; then
  echo "[WGRplane] Repository already present. Skipping clone."
elif [ -n "$REPO_URL_VAR" ]; then
  echo "[WGRplane] Cloning repository from $REPO_URL_VAR"
  git clone "$REPO_URL_VAR" . || { echo "[WGRplane] Clone failed."; exit 1; }
else
  echo "[WGRplane] GIT_REPO not set. Skipping clone. You can export GIT_REPO=https://... before running."
fi

# Create a default .env if missing
ENV_FILE=".env"
if [ ! -f "$ENV_FILE" ]; then
  echo "[WGRplane] Creating default .env file at $ENV_FILE"
  cat > "$ENV_FILE" <<'EOF'
# Auto-generated environment file for WGRplane
WGRPLANE_ENV=production
WG_INTERFACE=wg0
WG_CONF_PATH=/etc/wireguard/wg0.conf
EOF
else
  echo "[WGRplane] .env already exists. Skipping creation."
fi

# Start application with docker-compose
echo "[WGRplane] Starting application with docker-compose..."
if command -v docker-compose >/dev/null 2>&1; then
  sudo docker-compose up -d || { echo "[WGRplane] docker-compose up failed."; exit 1; }
elif command -v docker >/dev/null 2>&1; then
  if docker compose version >/dev/null 2>&1; then
    sudo docker compose up -d || { echo "[WGRplane] docker compose up failed."; exit 1; }
  else
    echo "[WGRplane] Docker Compose plugin not installed. Please install docker-compose or enable docker compose plugin."; exit 1
  fi
else
  echo "[WGRplane] Docker is not installed or not found in PATH. Cannot start application."; exit 1
fi

echo "[WGRplane] Install script completed. Check with: docker ps -a; docker-compose ps; wg-policy-ctl status  (depending on your setup)."
