Skip to content

Instantly share code, notes, and snippets.

@Zwyx
Last active March 27, 2024 18:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Zwyx/aecea360db2c50a058a9b1f0c5287b45 to your computer and use it in GitHub Desktop.
Save Zwyx/aecea360db2c50a058a9b1f0c5287b45 to your computer and use it in GitHub Desktop.
Display detailed information about a password store and reencrypt it
#!/bin/bash
# Created by github.com/Zwyx
# MIT Licence
if [ "$1" == "--help" ] || [ "$1" == "-h" ]; then
echo "Usage: ./encrypt.sh [subfolder-name]..."
exit
fi
BOLD="$(tput bold)"
NORM="$(tput sgr0)"
# Just a bullet proof way of getting the password store directory
# https://stackoverflow.com/questions/59895/how-can-i-get-the-source-directory-of-a-bash-script-from-within-the-script-itsel
DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"
echo -e "Password store root directory:\n\t'$BOLD$DIR$NORM'"
cd "$DIR"
# We will need to change the Internal Field Separator if no arguments are provided, so we save it first
# https://unix.stackexchange.com/questions/184863/what-is-the-meaning-of-ifs-n-in-bash-scripting
SAVED_IFS=$IFS
if [ $# -eq 0 ]; then
ALL_SUBDIRS="$(find . \( ! -regex '.*/\..*' \) -type d)"
IFS=$'\n'
else
ALL_SUBDIRS=$@
fi
# Search for the subdirectories which contain encrypted secrets
subdirs=()
for subdir in $ALL_SUBDIRS; do
if [ ! -z "$(find "$subdir" -maxdepth 1 -type f -name "*.gpg")" ]; then
subdirs+=("$subdir")
fi
done
# We now reset the Internal Field Separator
IFS=$SAVED_IFS
echo -e "\n$BOLD${#subdirs[@]}$NORM subfolders will be encrypted."
# List the GPG IDs which will be used to encrypt a directory
list() {
echo -e "\n'$BOLD$(echo "$1" | sed "s|^\./||")$NORM' will be encrypted for:"
path="$1"
gpgId="$path/.gpg-id"
# Start in the directory and go up a directely, one by one, until we find the `.gpg-id` file
while [ ! -f "$gpgId" ]; do
oldPath="$path"
path="$(echo "$path" | sed 's|\(.*\)/.*|\1|')"
if [ "$path" == "$oldPath" ]; then
echo "ERROR: the subfolder name '$1' is invalid."
exit
fi
gpgId="$path/.gpg-id"
done
cat "$gpgId" | sed 's/^/\t/g'
}
for i in "${subdirs[@]}"; do
list "$i"
done
echo
read -p "Proceed? [y/N] " REPLY
if [ "$REPLY" != "y" ] && [ "$REPLY" != "Y" ]; then
echo "Exiting."
exit
fi
echo -e "Proceeding...\n"
# We create the `.gpg-id` file in the root folder if it doesn't exist yet, and we put a single space in it;
# this prevents `pass` from trying to deinitialize the store and erroring when trying to delete `.gpg-id`
if [ ! -f "$DIR/.gpg-id" ] || [ "$(cat "$DIR/.gpg-id")" == "" ]; then
echo " " > "$DIR/.gpg-id"
fi
PASSWORD_STORE_DIR="$DIR" pass init "$(cat "$DIR/.gpg-id")"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment