#!/usr/bin/env bash
#
# Edit secrets
#

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

# Get file
keyringer_get_file "$2"

# Set recipients file
keyringer_set_recipients "$FILE"

# Get original file EXTENSION
FILENAME="$(basename "$FILE" .asc)"
FILENAME="$(basename "$FILENAME")"
EXTENSION="${FILENAME##*.}"

# Set a tmp file
keyringer_set_tmpfile $BASENAME.$EXTENSION

# Decrypt the information to the file
$GPG --yes -o "$TMPWORK" --use-agent -d "$KEYDIR/$FILE"

# Check whether decryption suceeded
if [ "$?" != "0" ]; then
  echo "Error decrypting $FILE, aborting"
  exit 1
fi

# Action check
if [ "$BASENAME" == "edit" ]; then
  APP="$EDITOR"
elif [ "$BASENAME" == "open" ]; then
  if which xdg-open &> /dev/null; then
    APP="xdg-open"
  else
    echo "You should have xdg-open application to perform this action, aborting."
    exit 1
  fi
fi

# Set APPNAME
APPNAME="`echo $APP | awk '{ print $1 }'`"

# Prompt
echo "Press any key to open the decrypted data with $APPNAME, Ctrl-C to abort"
echo "WARNING: please make sure that $APPNAME doesn't leak data to external applications or files"
echo "Press ENTER to continue"
read -s key
$APP "$TMPWORK"

# Wait for background process to finish
wait

# Workaround for some applications running in client/server mode, handling open file requests
# to a daemon and exiting immediatelly, making keyringer guess the editing is over and the file
# must be encrypted again (See #49).
#
# Thus, we cannot just wipe the file and exit keyringer, as the user might have a buffered copy
# of the unencrypted file in the application, which can lead to information leakage if the user
# saves the file and leaves the editor.
echo "Press any key when done using the file and you're sure that $APPNAME is closed."
read -s -n 1

# Encrypt again. Unset RELATIVE_PATH as it was already used to determine FILE path
export KEYRINGER_ADD_EXTENSION=false
RELATIVE_PATH="" keyringer_exec encrypt "$BASEDIR" "$FILE" "$TMPWORK"

# Check exit status
errcrypt="$?"

# Remove temp file
keyringer_unset_tmpfile "$TMPWORK"

# Check exit status again
errwipe="$?"

# Error handling must be done after temp file removal
if [ "$errcrypt" != "0" ]; then
  exit "$errcrypt"
elif [ "$errwipe" != "0" ]; then
  exit $errwipe
fi
