#!/bin/bash

set -o pipefail

KEYRING_NAME="2fauth"
KEYRING_VALUE="token"
DOMAIN="https://auth.iedsoftworks.com"

getApiToken() {
  token=$(secret-tool lookup "$KEYRING_NAME" "$KEYRING_VALUE")
  if [[ $? == 0 ]]; then
    return 0
  fi

  token=$(zenity --forms --add-multiline-entry="API Key" --text="Provide a valid API key")
  if [[ $token == "" ]]; then
    return 1
  fi

  echo "$token" | secret-tool store --label "2FAuth API Key" "$KEYRING_NAME" "$KEYRING_VALUE"
}

getApiToken

list=$(curl --oauth2-bearer "$token" "$DOMAIN/api/v1/twofaccounts" | jq 'map({"\(.service) - \(.account)": .id}) | add' -r)
selection=$(echo "$list" | jq 'keys | map("\(.)\n") | add' -r | anyrun --plugins libstdin.so)

if [[ $selection == "" ]]; then
  exit 0
fi

id=$(echo $list | jq ".[\"${selection}\"]")

curl --oauth2-bearer "$token" "$DOMAIN/api/v1/twofaccounts/$id/otp" |
  jq ".password" -r |
  wl-copy

notify-send -i "lock" "2FA Code copied" "Copied code for '$selection'"
