#!/bin/bash -e

if [ "$(uname -s)" == Darwin ]
then
    # use faster local utilities to speed up operation;
    # local-keychain-utils is written in Python and takes around a
    # third of a second, whereas the direct OS binary is takes 1/0th
    # of the time to run.
    local-keychain-get() {
        security find-generic-password -w -a "${OP_ACCOUNT_ALIAS:?}" 2>/dev/null
    }

    local-keychain-clear() {
        security delete-generic-password -a "${OP_ACCOUNT_ALIAS:?}"
    }

    local-keychain-store() {
        IFS= read -r password
        security add-generic-password -s 1password -w "${password}" -a "${OP_ACCOUNT_ALIAS:?}"
    }
fi

if [ -z "${OP_TEAM}" ]
then
    OP_TEAM=$(jq -r .accounts[0].shorthand ~/.op/config)
fi

if [ -z "${OP_ACCOUNT_ALIAS}" ]
then
    email=$(jq -r .accounts[0].email ~/.op/config)
    if [ -f ~/.with-op.json ]
    then
        prefix=$(jq -r .prefix ~/.with-op.json)
    else
        prefix=
    fi
    OP_ACCOUNT_ALIAS="${prefix?}${OP_TEAM:?}/${email:?}"
fi

if [ -z "${OP_SESSION_VARNAME}" ]
then
    user_uuid=$(jq -r .accounts[0].userUUID ~/.op/config)
    OP_SESSION_VARNAME="OP_SESSION_${user_uuid:?}"
fi

if session=$(local-keychain-get 1password "${OP_ACCOUNT_ALIAS:?}")
then
  declare "${OP_SESSION_VARNAME:?}"="${session:?}"
  export "${OP_SESSION_VARNAME:?}"
  if ! op account get >/dev/null
  then
    # session must have expired
    declare "${OP_SESSION_VARNAME:?}"=

    local-keychain-clear 1password "${OP_ACCOUNT_ALIAS:?}"
  fi
fi

if [ -z "${!OP_SESSION_VARNAME}" ]
then
  my_password="$(prompt-for-password --prompt "Password:" "Please enter your 1Password master password")"
  eval "$(op signin --account "${OP_TEAM:?}" <<< "${my_password:?}")"
  if [ -z "${!OP_SESSION_VARNAME}" ]
  then
    exit 1
  fi

  local-keychain-store 1password "${OP_ACCOUNT_ALIAS:?}" <<< "${!OP_SESSION_VARNAME}" || true
fi


exec "$@"
