#!/bin/sh

# puss.sh version 7
#
# Based on:
# <https://gist.githubusercontent.com/Jan69/facb130bc938ffd5ec1
# b51ff964406c1/raw/4fff75fa24e3718a45a26317d679962982b04d0b/puss.sh>
#
# pusswordstore - jan6's simple, *nix password manager
# name comes from combining "pus" with "passwordstore", as it's
# inspired from passwordstore.org, but without the unneeded complexity
# should work with any posix shell, in any posix-ish environment, with
# any encryption tool

list() {
   find "$puss_dir" -type f | sed \
       -e "s|^$puss_dir/||"       \
       -e "/^\$/d"                \
       -e "s/\.${puss_ext##.}$//"
}

# en-/decryption wrapper
# use whatever tool you want, gpg, scrypt, age, openssl enc, you name it

puss_crypt() {
   case "$1" in
   ("-e")
       # encryption, $2 is the filename to encrypt,
       # encrypted file should be same as original filename
       # you most likely need an intermediary file, else you'll
       # corrupt or trunctate it (unless you read into memory first)
       # scrypt enc "$2" >"$2.new" &&
       recip=$(cat $puss_dir/.gpg-id)
       if [ -z "$recip" ]
       then
           echo "Couldn't find GPG encryption id in $puss_dir/.gpg-id"
           exit -1
       fi
       gpg2 -e -r "$recip" --quiet --compress-algo=none \
           --no-encrypt-to --pinentry-mode loopback -o "$2.new" "$2"
       cat "$2.new" >"$2" &&
       rm -f "$2.new"
       ;;
   ("-d")
       # decryption, print to stdout
       # scrypt dec "$2"
       gpg2 -d --quiet --compress-algo=none --no-encrypt-to \
           --pinentry-mode loopback "$2"
       ;;
   ("-c")
       # decryption, non-stdout, "copy to clipboard" or similar
       puss_crypt "$@" | xclip
       ;;
   esac
}

puss() {
   puss_dir="$(readlink -f ${puss_dir:-~/.pusswordstore})"
   puss_ext=".gpg"
   mkdir -p "$puss_dir"
   pw="$puss_dir/$2$puss_ext"
   case "$1" in
   ("add"|"insert")
       read -r i
       echo $i >"$pw" && puss_crypt -e "$pw"
       ;;
   ("del"|"rm")
       rm "$pw"
       ;;
   ("edit")
       t="$(mktemp)"
       cp -p "$pw" "$t"
       puss_crypt -d "$pw" >"$t"
       if [ $? -eq 0 ]
       then
           "${EDITOR:-vi}" "$t" &&
           puss_crypt -e "$t"
           mv "$t" "$pw"
       fi
       ;;
   ("read")
       puss_crypt -d "$pw"
       ;;
   ("search")
       list | grep -i "$2"
       ;;
   (""|"ls"|"list")
       list
       ;;
   ("--help"|"-h")
       echo "usage: $0 add password | del password | edit password | [read] password | list"
       ;;
   (*)
       pw="$puss_dir/$1$puss_ext"
       puss_crypt -d "$pw"
       ;;
  esac
}

puss "$@"