#!/bin/sh
# Voltainer Quick Installer
# https://voltainer.io
#
# Usage:
#   curl -fsSL https://get.voltainer.io | sudo bash
#   # or with options:
#   curl -fsSL https://get.voltainer.io | sudo bash -s -- --version 1.0.1
#
# This script:
#   1. Detects OS and architecture
#   2. Downloads the Voltainer release tarball
#   3. Verifies the checksum
#   4. Runs the bundled installer
#
# For macOS, use MacVolt instead: https://macvolt.dev

set -eu

# =============================================================================
# Configuration
# =============================================================================

VOLT_VERSION="${VOLT_VERSION:-v1.0.1}"
VOLT_CDN="${VOLT_CDN:-https://cdn.armoredgate.com}"
VOLT_RELEASES_PATH="/voltainer/releases"

# =============================================================================
# Helpers
# =============================================================================

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

info()    { printf "${BLUE}[voltainer]${NC} %s\n" "$*"; }
success() { printf "${GREEN}[ok]${NC} %s\n" "$*"; }
warn()    { printf "${YELLOW}[warn]${NC} %s\n" "$*"; }
error()   { printf "${RED}[error]${NC} %s\n" "$*" >&2; }
fatal()   { error "$@"; exit 1; }

# =============================================================================
# Parse Arguments
# =============================================================================

parse_args() {
    while [ $# -gt 0 ]; do
        case "$1" in
            --version|-v)
                VOLT_VERSION="$2"
                shift 2
                ;;
            --no-trial)
                export VOLT_TRIAL=0
                shift
                ;;
            --help|-h)
                cat <<'USAGE'
Voltainer Installer

Usage:
  curl -fsSL https://get.voltainer.io | sudo bash
  curl -fsSL https://get.voltainer.io | sudo bash -s -- [OPTIONS]

Options:
  --version, -v VERSION  Install a specific version (default: v1.0.1)
  --no-trial             Skip Pro trial provisioning (Community tier only)
  --help, -h             Show this help message

Environment variables:
  VOLT_VERSION           Same as --version
  VOLT_TRIAL             Set to 0 to skip trial (same as --no-trial)

For macOS, use MacVolt instead: https://macvolt.dev
USAGE
                exit 0
                ;;
            *)
                warn "Unknown option: $1 (use --help for usage)"
                shift
                ;;
        esac
    done
}

# =============================================================================
# System Detection
# =============================================================================

detect_os() {
    OS="$(uname -s)"
    case "$OS" in
        Linux)
            OS="linux"
            ;;
        Darwin)
            printf "\n"
            printf "${YELLOW}╭────────────────────────────────────────────────────────────╮${NC}\n"
            printf "${YELLOW}│  macOS detected — Voltainer requires Linux.                │${NC}\n"
            printf "${YELLOW}│                                                            │${NC}\n"
            printf "${YELLOW}│  For macOS, use ${BOLD}MacVolt${NC}${YELLOW} instead:                         │${NC}\n"
            printf "${YELLOW}│    brew install --cask macvolt                             │${NC}\n"
            printf "${YELLOW}│                                                            │${NC}\n"
            printf "${YELLOW}│  Or download from: https://macvolt.dev                     │${NC}\n"
            printf "${YELLOW}╰────────────────────────────────────────────────────────────╯${NC}\n"
            printf "\n"
            exit 1
            ;;
        MINGW*|MSYS*|CYGWIN*)
            fatal "Windows detected. Voltainer requires Linux. Use WSL2 or a Linux VM."
            ;;
        *)
            fatal "Unsupported OS: $OS. Voltainer requires Linux."
            ;;
    esac
}

detect_arch() {
    ARCH="$(uname -m)"
    case "$ARCH" in
        x86_64|amd64)   ARCH="amd64" ;;
        aarch64|arm64)  ARCH="arm64" ;;
        armv7l)         fatal "32-bit ARM (armv7) is not supported. Use a 64-bit system." ;;
        *)              fatal "Unsupported architecture: $ARCH" ;;
    esac
}

check_root() {
    if [ "$(id -u)" -ne 0 ]; then
        error "This installer must be run as root."
        printf "\n"
        printf "Run with sudo:\n"
        printf "  ${GREEN}curl -fsSL https://get.voltainer.io | sudo bash${NC}\n"
        printf "\n"
        exit 1
    fi
}

check_distro() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        DISTRO_ID="${ID:-unknown}"
        DISTRO_NAME="${PRETTY_NAME:-$DISTRO_ID}"
    else
        DISTRO_ID="unknown"
        DISTRO_NAME="Unknown Linux"
    fi
}

# =============================================================================
# Download Helpers
# =============================================================================

download() {
    local url="$1"
    local dest="$2"

    if command -v curl >/dev/null 2>&1; then
        curl -fsSL "$url" -o "$dest"
    elif command -v wget >/dev/null 2>&1; then
        wget -qO "$dest" "$url"
    else
        fatal "Neither curl nor wget found. Install curl and retry."
    fi
}

check_download_tools() {
    if ! command -v curl >/dev/null 2>&1 && ! command -v wget >/dev/null 2>&1; then
        info "Installing curl..."
        case "$DISTRO_ID" in
            debian|ubuntu|linuxmint|pop)
                apt-get update -qq >/dev/null 2>&1
                apt-get install -y -qq curl >/dev/null 2>&1
                ;;
            fedora|rhel|centos|rocky|almalinux)
                dnf install -y -q curl 2>/dev/null || yum install -y -q curl 2>/dev/null
                ;;
            arch|manjaro)
                pacman -Sy --noconfirm curl >/dev/null 2>&1
                ;;
            opensuse*|sles)
                zypper install -y curl >/dev/null 2>&1
                ;;
            *)
                fatal "Please install curl manually and retry."
                ;;
        esac
    fi
}

# =============================================================================
# Main Installation
# =============================================================================

install_voltainer() {
    local version="${VOLT_VERSION#v}"  # Strip leading 'v' if present
    local tarball="voltainer-v${version}-appliance-${OS}-${ARCH}.tar.gz"
    local url="${VOLT_CDN}${VOLT_RELEASES_PATH}/${tarball}"
    local checksum_url="${VOLT_CDN}${VOLT_RELEASES_PATH}/SHA256SUMS"

    local tmp_dir
    tmp_dir="$(mktemp -d)"
    trap 'rm -rf "$tmp_dir"' EXIT

    info "Downloading Voltainer v${version} for ${OS}/${ARCH}..."

    if ! download "$url" "$tmp_dir/$tarball" 2>/dev/null; then
        fatal "Failed to download: $url"
    fi
    success "Downloaded $tarball"

    info "Verifying checksum..."
    if download "$checksum_url" "$tmp_dir/SHA256SUMS" 2>/dev/null; then
        cd "$tmp_dir"
        if command -v sha256sum >/dev/null 2>&1; then
            if ! grep "$tarball" SHA256SUMS | sha256sum -c - >/dev/null 2>&1; then
                fatal "Checksum verification failed! The download may be corrupted."
            fi
            success "Checksum verified"
        else
            warn "sha256sum not available — skipping checksum verification"
        fi
        cd - >/dev/null
    else
        warn "Could not download checksums — skipping verification"
    fi

    info "Extracting..."
    tar -xzf "$tmp_dir/$tarball" -C "$tmp_dir" 2>/dev/null || {
        fatal "Failed to extract archive"
    }

    local install_script=""
    if [ -f "$tmp_dir/install.sh" ]; then
        install_script="$tmp_dir/install.sh"
    else
        install_script="$(find "$tmp_dir" -name 'install.sh' -type f 2>/dev/null | head -1)"
    fi

    if [ -z "$install_script" ] || [ ! -f "$install_script" ]; then
        fatal "install.sh not found in release archive"
    fi

    info "Running bundled installer..."
    chmod +x "$install_script"

    # Pass through --no-trial if set
    local install_args=""
    if [ "${VOLT_TRIAL:-1}" = "0" ]; then
        install_args="--no-trial"
    fi

    cd "$(dirname "$install_script")"
    exec sh "$install_script" $install_args
}

# =============================================================================
# Main
# =============================================================================

main() {
    printf "\n"
    printf "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}\n"
    printf "${BOLD}  Voltainer Quick Installer${NC}\n"
    printf "${BOLD}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}\n"
    printf "\n"

    parse_args "$@"
    detect_os
    detect_arch
    check_root
    check_distro
    check_download_tools

    info "System: $DISTRO_NAME ($ARCH)"

    install_voltainer
}

main "$@"
