#!/bin/sh

set -eu

print_usage() {
  echo -e "Usage: $(basename $0) [-r] <file>"
  echo -e "\nArguments:"
  echo -e "    <file>  the file to decrypt, edit and encrypt"
}

# Parse short options
OPTIND=1
while getopts ":h" opt
do
  case "$opt" in
    "h") print_usage >&2; exit 0 ;;
    *) print_usage >&2; exit 1 ;;
  esac
done
shift $(expr $OPTIND - 1) # remove options from positional parameters

if ! command -v svanill ; then
    echo "Error: \"svanill\" not found"
    exit 1
fi

    print_usage
    exit 1
fi

target_file="$1"
temp_target_file=$(mktemp)

# On exit, remove the file
trap "rm $temp_target_file" EXIT

svanill_edit () {
  first_editing=$1
  if [ $first_editing -eq 1 -a -f "$target_file" ]; then
    svanill -i "$target_file" dec > $temp_target_file
  fi

  editor=""
  if (which $EDITOR &> /dev/null) ; then
    editor=$EDITOR
  elif (which vim &> /dev/null); then
    editor=vim
  elif (which vi &> /dev/null); then
    editor=vi
  else
    echo "vim/vi is unavailable."
    exit 69 # EX_UNAVAILABLE
  fi

  md5sum_before=$(md5sum "$temp_target_file")
  $editor "$temp_target_file"
  md5sum_after=$(md5sum "$temp_target_file")

  if [ "$md5sum_before" == "$md5sum_after" ]; then
    echo "File unchanged, nothing to do"
    exit 0
  fi

  echo "Set and confirm the password to save the file (CTRL-C to exit)"
  svanill -i "$temp_target_file" -o "$target_file" enc && RC=$? || RC=$?

  if [ $RC -eq 0 ]; then
    echo ... done
    exit 0
  else
    echo
    echo 'An error occurred while encrypting the file, what do you want to do?'
    echo '(C)ontinue editing (default)'
    echo '(Q)uit and lose the changes'
    echo '(K)eep an UNENCRYPTED temporary file with the changes and exit'
    read -p '=> your choice: ' user_response
    case $user_response in
      q|Q)
        ;;
      k|K)
        trap - EXIT
        echo 'You can find the UNENCRYPTED file here:' $temp_target_file ;;
      *) svanill_edit 0 ;;
    esac
  fi
}

svanill_edit 1
