#!/usr/bin/env bash

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

function cmd::qr::on_load() {
  flag::register --name
  flag::register --type
}

# ============================================
# Help
# ============================================

function cmd::qr::help() {
  cat <<EOF
Usage: wgctl qr --name <name>

Display QR code for a client config.
Useful for adding clients to mobile devices.

Options:
  --name <name>   Full client name (e.g. phone-nuno)

Examples:
  wgctl qr --name phone-nuno
  wgctl qr --name tablet-nuno
EOF
}

# ============================================
# Run
# ============================================

function cmd::qr::run() {
  local name=""
  local type=""

  while [[ $# -gt 0 ]]; do
    case "$1" in
      --name) name="$2";        shift 2 ;;
      --type) type="$2";        shift 2 ;;
      --help) cmd::qr::help;    return  ;;
      *)
        log::error "Unknown flag: $1"
        cmd::qr::help
        return 1
        ;;
    esac
  done

  if [[ -z "$name" ]]; then
    log::error "Missing required flag: --name"
    cmd::qr::help
    return 1
  fi

  name=$(peers::resolve_and_require "$name" "$type") || return 1

  log::section "Client QR: ${name}"
  keys::qr "$name"
}
