#!/bin/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

# 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" &&
           cat "$2.new" >"$2" &&
           rm -f "$2.new"
           ;;
    ("-d") #decryption, print to stdout
           scrypt dec "$2"
           ;;
    ("-c") #decryption, non-stdout, "copy to clipboard" or similar
           puss_crypt "$@" | xclip
           ;;
  esac;
}

puss(){
  puss_dir="${puss_dir:-~/.pusswordstore}";
  mkdir -p "$puss_dir";
  pw="$puss_dir/$2";
  case "$1" in
    ("add") read -r i;echo $i >"$pw"&&
            puss_crypt  -e "$pw"
            ;;
    ("del") rm "$pw" ;;
    ("edit") t="$(mktemp)";
             cp -p "$pw" "$t";
             puss_crypt  -d "$pw" >"$t";
             "${EDITOR:-vi}" "$t" &&
             puss_crypt  -e "$t";
             mv "$t" "$pw"
             ;;
    ("read") puss_crypt  -d "pw" ;;
    (""|"ls"|"list") find "$puss_dir"|
                     sed -e "s|^$puss_dir||" \
                         -e "/^\$/d"
                     ;;
    ("--help"|"-h") echo "usage: $0 add password | del password | edit password | [read] password | list" ;;
    (*) puss_crypt  -d "$puss_dir/$1" ;;
  esac;
}
puss "$@"