#!/usr/bin/env bash

set -Eeuo pipefail

readonly MINIMUM_BUN_VERSION="1.3.14"

fail() {
    printf '\nWOML installation failed: %s\n' "$1" >&2
    exit 1
}

version_is_supported() {
    local current="${1%%-*}"
    local required="$2"
    local current_major current_minor current_patch
    local required_major required_minor required_patch

    IFS=. read -r current_major current_minor current_patch <<< "$current"
    IFS=. read -r required_major required_minor required_patch <<< "$required"

    [[ "$current_major" =~ ^[0-9]+$ ]] || return 1
    [[ "$current_minor" =~ ^[0-9]+$ ]] || return 1
    [[ "$current_patch" =~ ^[0-9]+$ ]] || return 1

    ((10#$current_major > 10#$required_major)) ||
        ((10#$current_major == 10#$required_major && 10#$current_minor > 10#$required_minor)) ||
        ((10#$current_major == 10#$required_major && 10#$current_minor == 10#$required_minor && 10#$current_patch >= 10#$required_patch))
}

case "$(uname -s)" in
    Linux | Darwin) ;;
    *) fail "This installer currently supports Linux and macOS." ;;
esac

if command -v bun >/dev/null 2>&1; then
    bun_version="$(bun --version)"
    version_is_supported "$bun_version" "$MINIMUM_BUN_VERSION" ||
        fail "Bun ${MINIMUM_BUN_VERSION} or later is required. Found ${bun_version}."

    printf 'Installing WOML with Bun %s...\n' "$bun_version"
    bun add --global woml-cli
elif command -v npm >/dev/null 2>&1; then
    printf 'Bun was not found. Installing Bun and WOML with npm...\n'
    npm install --global bun woml-cli
    hash -r
else
    fail "Install Bun ${MINIMUM_BUN_VERSION} or later, or install npm, and run this command again."
fi

command -v bun >/dev/null 2>&1 ||
    fail "Bun was installed but is not available on PATH. Open a new terminal and try again."

bun_version="$(bun --version)"
version_is_supported "$bun_version" "$MINIMUM_BUN_VERSION" ||
    fail "Bun ${MINIMUM_BUN_VERSION} or later is required. Found ${bun_version}."

command -v woml >/dev/null 2>&1 ||
    fail "WOML was installed but the woml executable is not available on PATH. Open a new terminal and try again."

printf '\nWOML is ready:\n'
woml --version
printf '\nRun woml --help to get started.\n'
