#!/usr/bin/env bash

search_dir=.
prefix=_pr.
tmp_dir="./${prefix}TEMPDIR"
pass_file="${prefix}PASSWORD"
dest=private.tar.gz

# Copies every file whose name starts with `$prefix` into an archive, stored at
# `$dest.gpg`, which is encrypted using the contents of the file `$pass_file`
# as a key.
zip() {
    # Recursively find the paths to each file descending from the directory
    # `$search_dir` whose name starts with the string `$prefix`, and run
    # `./priv.sh __copy_to_tmp <path>` for each file path found.
    find $search_dir -type f -name "$prefix*" -exec $0 __copy_to_tmp {}  \;

    # Compress all the files in the temporary directory `$tmp_dir` into a
    # tarball at `$dest`.
    tar -czf $dest $tmp_dir

    # Encrypt the tarball at `$dest` using the contents of the file
    # `$pass_file` as the passphrase, storing the new encrypted archive at
    # `$dest.gpg`.
    gpg --passphrase $(cat $pass_file) --batch --yes --symmetric $dest

    # Delete the temporary directory and the unencrypted tarball.
    rm -r $tmp_dir
    rm $dest
}

# Decrypts all the files stored in the encrypted archive generated by `zip()`
# and restores them to their original locations.
unzip() {
    # Decrpyt the encrypted archive at `$dest.gpg` using the contents of
    # `$pass_file` as the passphrase, storing the decrypted archive at `$dest`.
    gpg --passphrase $(cat $pass_file) --batch --yes -o $dest -d $dest.gpg

    # Extract the now-decrypted tarball. All the files will end up in the
    # temporary directory `$tmp_dir`.
    tar -xzf $dest

    # Recursively find the paths to every file in `$tmp_dir`, and run `priv.sh
    # __copy_from_tmp <path>` for each one.
    find $tmp_dir -type f -exec $0 __copy_from_tmp {} \;

    # Delete the decrypted tarball and the temporary directory.
    rm -r $tmp_dir
    rm $dest
}

# Takes a path to a file (`$1`) relative to `$search_dir` and copies it into
# the same location, but relative to `$tmp_dir`.
#
# E.g. `$search_dir/path/to/SECRETFILE` will be copied into
# `$tmp_dir/path/to/SECRETFILE`.
copy_to_tmp() {
    dn=$(dirname $1)
    mkdir -p $tmp_dir/$dn
    cp $1 $tmp_dir/$1
}

# Takes a path to a file (`$1`) in `$tmp_dir` and copies it into the same
# location, but with `$search_dir` taking the place of `$tmp_dir` at the
# beginning of the path.
#
# E.g. `$tmp_dir/path/to/SECRETFILE` will be copied into
# `$search_dir/path/to/SECRETFILE`.
copy_from_tmp() {
    x=$1
    cp $1 $search_dir${x#$tmp_dir}
}

case "$1" in
    zip)
        zip
        ;;
    unzip)
        unzip
        ;;
    __copy_to_tmp)
        copy_to_tmp $2
        ;;
    __copy_from_tmp)
        copy_from_tmp $2
        ;;
    *)
        exit 1
        ;;
esac
