#!/usr/bin/env bash

# ============================================
# Lifecycle
# ============================================

function keys::on_load() {
  system::require_command wg
  system::require_command qrencode
}

# ============================================
# Generation
# ============================================

function keys::generate_pair() {
  local name="$1"
  local dir
  dir="$(ctx::clients)"

  local private_key_file="${dir}/${name}_private.key"
  local public_key_file="${dir}/${name}_public.key"

  if [[ -f "$private_key_file" ]] || [[ -f "$public_key_file" ]]; then
    log::wg_warning "Keys already exist for client: ${name}"
    return 1
  fi

  wg genkey | tee "$private_key_file" | wg pubkey > "$public_key_file"
  chmod 600 "$private_key_file"

  log::wg_key "Generated key pair for: ${name}"
}

function keys::private() {
  local name="$1"
  local file
  file="$(ctx::clients)/${name}_private.key"

  if [[ ! -f "$file" ]]; then
    log::error "Private key not found for: ${name}"
    return 1
  fi

  cat "$file"
}

function keys::public() {
  local name="$1"
  local file
  file="$(ctx::clients)/${name}_public.key"

  if [[ ! -f "$file" ]]; then
    log::error "Public key not found for: ${name}"
    return 1
  fi

  cat "$file"
}

# ============================================
# Query
# ============================================

function keys::find_by_public() {
  local public_key="$1"
  local clients_dir
  clients_dir="$(ctx::clients)"
  
  for pubkey_file in "${clients_dir}"/*_public.key; do
    [[ -f "$pubkey_file" ]] || continue
    if [[ "$(cat "$pubkey_file")" == "$public_key" ]]; then
      basename "$pubkey_file" _public.key
      return 0
    fi
  done
  return 1
}

# ============================================
# Removal
# ============================================

function keys::remove() {
  local name="$1"
  local dir
  dir="$(ctx::clients)"

  rm -f "${dir}/${name}_private.key"
  rm -f "${dir}/${name}_public.key"

  log::wg_key "Removed keys for: ${name}"
}

# ============================================
# QR Code
# ============================================

function keys::qr() {
  local name="$1"
  local conf
  conf="$(ctx::clients)/${name}.conf"

  if [[ ! -f "$conf" ]]; then
    log::error "Client config not found: ${name}"
    return 1
  fi

  qrencode -t ansiutf8 < "$conf"
}
