#!/usr/bin/env bash

# ============================================
# Core — shell introspection
# ============================================

function core::function_exists() { declare -F "$1" >/dev/null 2>&1; }
function core::variable_exists() { declare -p "$1" &>/dev/null; }
function core::array_exists()    { [[ "$(declare -p "$1" 2>/dev/null)" == "declare -a"* ]]; }

function core::call_if_exists() {
  local fn="$1"
  shift
  if declare -F "$fn" >/dev/null 2>&1; then
    "$fn" "$@"
  fi
  return 0
}

WGCTL_QUIET=false
function core::set_quiet() { WGCTL_QUIET=true; }
function core::is_quiet()  { [[ "$WGCTL_QUIET" == "true" ]]; }

# ============================================
# Utility
# ============================================

function util::require_flag() {
  local flag="$1" value="$2"
  if [[ -z "$value" ]]; then
    log::error "Flag ${flag} requires a value"
    return 1
  fi
}

# ============================================
# String
# ============================================

function string::trim()       { echo "$1" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//'; }
function string::to_lower()   { echo "$1" | tr '[:upper:]' '[:lower:]'; }
function string::to_upper()   { echo "$1" | tr '[:lower:]' '[:upper:]'; }
function string::contains()   { [[ "$1" == *"$2"* ]]; }
function string::starts_with() { [[ "$1" == "$2"* ]]; }
function string::ends_with()  { [[ "$1" == *"$2" ]]; }
function string::is_empty()   { [[ -z "$1" ]]; }

# ============================================
# System
# ============================================

function system::require_root() {
  if [[ "$EUID" -ne 0 ]]; then
    log::error "wgctl must be run as root"
    exit 1
  fi
}

function system::command_exists() {
  command -v "$1" >/dev/null 2>&1
}

function system::require_command() {
  if ! system::command_exists "$1"; then
    log::error "Required command not found: $1"
    exit 1
  fi
}
