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

# kbs2-kbsecret-login-import: Import login 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="login"

for label in $(kbsecret list -s "${session}" -t "${kind}"); do
  record=$(kbsecret login -s "${session}" -i $'\x01' -x "${label}")

  username=$(awk -F $'\x01' '{ print $2 }' <<< "${record}")
  password=$(awk -F $'\x01' '{ print $3 }' <<< "${record}")

  kbs2 new "${label}" <<< "${username}"$'\x01'"${password}"
  echo "[+] Imported ${label}"
done
