#!/usr/bin/env bash
# frozen_string_literal: true

# kbs2-kbsecret-env-import: Import environment records from a KBSecret session into kbs2

set -eo pipefail

[[ -n "${KBS2_SUBCOMMAND}" ]] \
  || { >&2 echo "Fatal: Not being run as a subcommand?"; exit 1; }

session="${1:-default}"
kind="environment"

for label in $(kbsecret list -s "${session}" -t "${kind}"); do
  record=$(kbsecret env -s "${session}" -n "${label}")

  variable=$(awk -F = '{ print $1 }' <<< "${record}")
  value=$(awk -F = '{ print $2 }' <<< "${record}")

  kbs2 new -k environment "${label}" <<< "${variable}"$'\x01'"${value}"
  echo "[+] Imported ${label}"
done
