#!/usr/bin/env bash

## Copy a password using the password manager `pass` and then open the URL
## specified in the password's file (`url: http://example.com/`). If there is a
## username in the password's file (`user: name@example.com`), it will be made
## available by appending it to the URL as a fragment.
##
## Usage: pass-use [-s <browser>]
##
## Options:
##   -s <browser>   Browser to use if password file includes `browser: secondary`.
##
## Dependencies: fzf, GNU sed, pass, xdg-utils

set -euo pipefail
shopt -s inherit_errexit

die() { echo "${0##*/}: $1" >&2; exit 1; }

[[ " $* " =~ ' --help ' ]] && sed -n 's/^## \?//p' "$0" && exit

while getopts s: opt; do
  case $opt in
    s) secondary_browser=$OPTARG ;;
    *) exit 1 ;;
  esac
done
shift "$(( OPTIND - 1 ))"

(( $# )) && die 'invalid argument'

# Get password name.
pw_file=$(cd "${PASSWORD_STORE_DIR:-~/.password-store}"; fzf)
pw_name=${pw_file%.gpg}

# Copy password.
pass show -c "$pw_name"

# Get password file contents.
pw_contents=$(pass show "$pw_name")

# Get URL.
url=$(sed -n 's/^url: *\(\S\+\) */\1/p' <<< "$pw_contents")
[[ -n $url ]] || die 'URL not found'
url+=#$(sed -n 's/^user: *\(\S\+\) */\1/p' <<< "$pw_contents")

# Set browser.
browser=xdg-open
grep -q '^browser: *secondary' <<< "$pw_contents" &&
  browser=${secondary_browser:-$browser}
type "$browser" &> /dev/null || die "command not found: $browser"

# Open URL.
$browser "$url" &> /dev/null &
