#!/bin/bash
# oidc-keychain - re-use oidc-agent between logins
#
# Inspired by https://www.funtoo.org/Keychain for ssh-agent and gpg-agent
#

ME=oidc-keychain

usage()
{
  (
  echo "Usage: $ME [-?|--help|--usage|-V|--version] [-k|--kill]"
  echo "   or: $ME [oidc-agent options] [--accounts ACCOUNT ...]"
  )>&2
}

help()
{
  (
  echo "$ME -- Re-use oidc-agent between logins"
  echo
  echo "oidc-agent options will be passed to oidc-agent when starting it."
  echo
  echo " General:"
  echo "  -k, --kill                 Kill oidc-agent if it is running"
  echo "      --accounts ACCOUNT ... Load the ACCOUNTs if not already loaded"
  echo 
  echo " Help:"
  echo "  -?, --help                 Give this help list"
  echo "      --usage                Give a short usage message"
  echo "  -V, --version              Print program version"
  )>&2
}

KILL=false
AGENT_OPTS=""
while [ -n "$1" ]; do
  # Look for own options
  case "$1" in
    -k|--kill)
      KILL=true
      ;;
    "-?"|-h|--help)
      usage
      help
      exit
      ;;
    --usage)
      usage
      exit
      ;;
    -V|--version)
      echo `oidc-agent -V`|sed 's/agent/keychain/'
      exit
      ;;
    --accounts)
      shift
      break
      ;;
    *)
      # Look for options to pass on to oidc-agent
      if [[ $1 = -* ]]; then
        if [ -z "$2" ] || [[ $2 = -* ]]; then
          AGENT_OPTS="$AGENT_OPTS $1"
        else
          AGENT_OPTS="$AGENT_OPTS $1 $2"
          shift
        fi
      else
        echo "$ME: internal error: unprocessed option $1" >&2
        exit 2
      fi
      ;;
  esac
  shift
done


if $KILL; then
  oidc-agent-service kill
  exit $?
fi

CMDS=$(OIDC_AGENT_OPTS=$AGENT_OPTS oidc-agent-service use)
eval `echo "$CMDS" | head -n -1`
echo "$CMDS"

# Determine prompt mode
if which oidc-prompt &>/dev/null; then
  PROMPT="--pw-prompt=gui"
fi

# Add given accounts if they're not already loaded.
while IFS= read -r line; do
    LOADED+=("$line")
done < <(oidc-add --loaded 2>/dev/null | tail -n +2)
for ACCOUNT; do
   if oidc-add $ACCOUNT $PROMPT 2>&1|tee /dev/fd/2|grep -q Error:; then
      exit 1
  fi
done
