#!/usr/bin/env bash
#
# Decrypt secret header to clipboard.
#

# Copy contents to clipboard.
#
# Function thanks to Password Store by Jason A. Donenfeld <Jason@zx2c4.com>
# distributed under GPLv2+: http://www.zx2c4.com/projects/password-store/
#
# Adapted by rhatto
clip() {
  # This base64 business is a disgusting hack to deal with newline inconsistancies
  # in shell. There must be a better way to deal with this, but because I'm a dolt,
  # we're going with this for now.

  #local xclip="xclip -selection clipboard"
  local xclip="xclip"
  before="$($xclip -o 2> /dev/null | base64)"

  # Avoid "Error: target STRING not available"
  # https://github.com/astrand/xclip/issues/38
  echo "$RANDOM" | $xclip &> /dev/null

  # Copy text into clipboard
  echo -n "$1" | $xclip &> /dev/null

  # Cleanup procedure
  (
    sleep 45
    now="$($xclip -o | base64)"
    if [[ $now != $(echo -n "$1" | base64) ]]; then
      before="$now"
    fi

    # It might be nice to programatically check to see if klipper exists,
    # as well as checking for other common clipboard managers. But for now,
    # this works fine -- if qdbus isn't there or if klipper isn't running,
    # this essentially becomes a no-op.
    #
    # Clipboard managers frequently write their history out in plaintext,
    # so we axe it here:
    qdbus org.kde.klipper /klipper org.kde.klipper.klipper.clearClipboardHistory &>/dev/null

    echo "$before" | base64 -d | $xclip 2> /dev/null
  ) & disown
  echo "Copied $2 to clipboard. Will clear in 45 seconds."
}

# Load functions
LIB="`dirname $0`/../functions"
source "$LIB" read $* || exit 1

# Check for xclip
if ! which xclip &> /dev/null; then
  echo "fatal: xclip not found"
  exit 1
fi

# Find our search mode
if [ "$(basename "$0")" == "search" ] && [ -z "$2" ]; then
  read -p "Enter option (Ctrl-C to abort): " query
else
  query="$2"
fi

# Get file
keyringer_get_file "$query"

# Decrypt
pass="$($GPG --use-agent -d "$KEYDIR/$FILE" | head -n 1)"

# Copy to clipboard
if [ ! -z "$pass" ]; then
  clip "$pass" "$2"
fi

# Exit
exit "$?"
