#!/usr/bin/env bash
#
# dex - [d]ecrypt [e]ncrypt e[x]change

# shellcheck shell=bash disable=SC2312

# TODO: recursive  in folder
# TODO: encrypt if not, decrypt if not

set -e

msg() {
  echo >&2 -e "${1-}"
}

die() {
  msg=$1
  code=${2-1}
  msg "${msg}"
  exit "${code}"
}

set -u

mode='EXCHANGE' ### or EDIT (-e)
encrypt_nonexist=true

lockfolder="${HOME}/.local/share/dex"
[ -d "${lockfolder}" ] || mkdir -p "${lockfolder}"

# lockfile="$HOME/.local/share/dex.lock"

POSITIONAL=()
while [ "$#" -gt 0 ]; do
  key="$1"

  case ${key} in
    -E | --encrypt)
      mode='ENCRYPT'
      shift
      ;;
    -D | --DECRYPT)
      mode='DECRYPT'
      shift
      ;;
    -e | --edit)
      mode='EDIT'
      shift
      ;;
    -u | --unlock)
      mode="UNLOCK"
      shift
      ;;
    -n | --noencrypt-nonexist)
      encrypt_nonexist=false
      shift
      ;;
    -p | --print)
      mode='PRINT'
      shift
      ;;
    -clf | --clean-lockfiles)
      for file in ${lockfolder}/*; do
        lock_status=$(flock -n -x "${file}" echo 'unlocked!')
        [ -n "${lock_status}" ] && rm -- "${file}"
      done
      exit
      ;;
    --pager)
      mode='PAGER'
      shift
      ;;
    -?*)
      echo "Unknown option: $1"
      exit
      ;;
    *)                   # unknown option
      POSITIONAL+=("$1") # save it in an array for later
      shift
      ;;
  esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters

filename="$1"
filepath=$(realpath "${filename}")
filepathenc=${filepath//\//%}
lockfile="${lockfolder}/${filepathenc}"

vipe_suffix="$(basename "${filename}")"

typestr=$(file "${filename}")

if [ "${mode}" = "EXCHANGE" ]; then
  case ${typestr} in
    encrypted)
      result=$(gpg -dq "${filename}") \
        && printf '%s' "${result}" >"${filename}"
      unset result
      ;;
    *)
      data=$(gpg -o - -e "${filename}" > >(base64)) \
        && printf '%s' "${data}" | base64 -d >"${filename}"
      unset data
      ;;
  esac
elif [ "${mode}" = "PAGER" ]; then
  case ${typestr} in
    encrypted)
      gpg -dq "${filename}" | less
      ;;
    *)
      less "${filename}"
      ;;
  esac
elif [ "${mode}" = "PRINT" ]; then
  case ${typestr} in
    encrypted)
      gpg -dq "${filename}"
      ;;
    *)
      cat "${filename}"
      ;;
  esac
elif [ "${mode}" = "UNLOCK" ]; then
  if [ -f "${lockfile}" ]; then
    flock -u "${lockfile}"
  fi
elif [ "${mode}" = "EDIT" ]; then
  case ${typestr} in
    encrypted)
      # uses lockfiles to ensure file is not multiply modified
      (
        flock -n 9 || die "Failure to acquire lockfile: ${lockfile}."
        echo "Acquiring lock..."
        data=$(gpg -dq "${filename}" | vipe --suffix "${vipe_suffix}") \
          && gpg -e --batch --yes -o "${filename}" < <(printf '%s' "${data}")
        unset data
        echo "Releasing lock..."
      ) 9>"${lockfile}"
      ;;
    *)
      if [ -f "${filename}" ]; then
        # If file exists and not encrypted
        ${EDITOR:-vi} "${filename}"
      else
        if ${encrypt_nonexist}; then
          # if file doesn't exist
          # Uses lockfiles to ensure file is not multiply modified
          (
            flock -n 9 || exit 1
            data=$(vipe --suffix "${vipe_suffix}") \
              && gpg -e --batch --yes -o "${filename}" < <(printf '%s' "${data}")
            unset data
          ) 9>"${lockfile}"
        else
          ${EDITOR:-vi} "${filename}"
        fi
      fi
      ;;
  esac
elif [ "${mode}" = "ENCRYPT" ]; then
  # shellcheck disable=SC2249
  case ${typestr} in
    encrypted)
      data=$(gpg -o - -e "${filename}" > >(base64)) \
        && printf '%s' "${data}" | base64 -d >"${filename}"
      unset data
      ;;
  esac
elif [ "${mode}" = "DECRYPT" ]; then
  # shellcheck disable=SC2249
  case ${typestr} in
    encrypted)
      result=$(gpg -dq "${filename}") && printf '%s' "${result}" >"${filename}"
      unset result
      ;;
  esac
fi
