#!/bin/sh
#
# urn - age-gpg wrapper to encrypt dir & decrypt file - POSIX
# dependencies: age
#
# ---
# source: https://github.com/arcxio/urn

usage() {
  printf %s "\
$(basename "$0")
  a simple POSIX script to encrypt dir and decrypt file with age

commands:
  PATH [age options..]

  PATH is a directory - Makes an encrypted archive of it.
  PATH is a file      - Decrypts & extracts directory from it.
"
  exit 0
}

make_tar() {
  if command -v pax >/dev/null 2>&1; then
    pax -x ustar -w "./$1"
  else
    tar c "./$1"
  fi
}

extract_tar() {
  if command -v pax >/dev/null 2>&1; then
    pax -r
  else
    tar -xf
  fi
}

urn() {
  path=$(realpath -- "$1") || return 1
  shift

  if [ -d "${path}" ]; then
    cd "$(dirname "${path}")" || return 1
    name=$(basename "${path}")
    if command -v age >/dev/null 2>&1; then
      make_tar "${name}" | age --encrypt "$@" -o "${OLDPWD}/${name}.tar.age"
    else
      gpg_id="$(pass show gpg_key)"
      make_tar "${name}" | gpg --output "${OLDPWD}/${name}.tar.asc" --encrypt --recipient "${gpg_id}" "$@"
    fi
  elif [ -f "${path}" ]; then
    if command -v age >/dev/null 2>&1; then
      age --decrypt "$@" "${path}" | extract_tar
    else
      gpg --output "${path%.*}" --decrypt "${path}"
      tar -xf "${path%.*}"
    fi
  else
    printf 'urn: %s\n' "${path}: No such file or directory"
    return 2
  fi
}

if [ -n "$1" ]; then
  urn "$@"
else
  usage
fi
