#!/usr/bin/env bash
# Curl-safe native Vow + vpm installer (pipe to sh).
# Hosted at https://install.vowlang.dev — downloads native release tarball.
set -euo pipefail

_vow_installer_dir() {
  if [[ -n "${BASH_VERSION:-}" && -n "${BASH_SOURCE[0]:-}" && "${BASH_SOURCE[0]}" != "$0" ]]; then
    cd "$(dirname "${BASH_SOURCE[0]}")" && pwd
    return 0
  fi
  if [[ -f "$0" && "$0" != sh && "$0" != bash ]]; then
    cd "$(dirname "$0")" && pwd
    return 0
  fi
  return 1
}

_vow_source_native_lib() {
  local lib="" dir=""
  if [[ -n "${VOW_NATIVE_INSTALL_LIB:-}" && -f "${VOW_NATIVE_INSTALL_LIB}" ]]; then
    # shellcheck source=lib/native-install.sh
    source "${VOW_NATIVE_INSTALL_LIB}"
    return 0
  fi
  if dir="$(_vow_installer_dir 2>/dev/null)"; then
    lib="$dir/lib/native-install.sh"
    if [[ -f "$lib" ]]; then
      # shellcheck source=lib/native-install.sh
      source "$lib"
      return 0
    fi
  fi
  local install_url="${VOW_INSTALL_URL:-https://install.vowlang.dev}"
  local tmp
  tmp="$(mktemp -d)"
  if ! curl -fsSL "${install_url}/lib/native-install.sh" -o "$tmp/native-install.sh"; then
    rm -rf "$tmp"
    printf 'error: could not load installer library from %s/lib/native-install.sh\n' "$install_url" >&2
    exit 1
  fi
  # shellcheck source=/dev/null
  source "$tmp/native-install.sh"
  rm -rf "$tmp"
}

_vow_source_native_lib
vow_native_install_from_release
