#!/usr/bin/env bash

get-pass-from-keepass() {
    if [[ -z "$1" ]]; then echo "\$1/entry is empty."; exit; fi
    local keepass_entry="$1"
    local keepass_password="${2:-}"

    if [[ ! -f "$KEEPASS_DATABASE_FILE" ]]; then
        echo "Keepass database file not found: $KEEPASS_DATABASE_FILE"
        exit 1
    fi

    if [[ ! -f "$KEEPASS_DATABASE_KEY_FILE" ]]; then
        echo "Keepass database key file not found: $KEEPASS_DATABASE_KEY_FILE"
        exit 1
    fi

    if [[ -n "$keepass_password" ]]; then
        keepassxc-cli show --show-protected --attributes Password \
            --key-file "$KEEPASS_DATABASE_KEY_FILE" \
            "$KEEPASS_DATABASE_FILE" \
            "$keepass_entry" <<< "$keepass_password"
    else
        keepassxc-cli show --show-protected --attributes Password \
            --key-file "$KEEPASS_DATABASE_KEY_FILE" \
            "$KEEPASS_DATABASE_FILE" \
            "$keepass_entry"
    fi
}
gpfk() {
    get-pass-from-keepass "$@"
}
