#!/bin/sh

set -e

src="$1"
dst="$2"
recipient="$3"

if [ -z "$src" ] || [ -z "$dst" ] || [ -z "$recipient" ]; then
	echo "Usage: $0 <src_mount> <dst_mount> <new_key_id>"
	exit 1
fi

if ! [ -d "$src" ]; then
	echo "$src: no such directory"
	exit 1
fi

if ! [ -d "$dst" ]; then
	echo "$dst: no such directory"
	exit 1
fi

# Make sure the target key is available
if ! gpg --list-keys "$3" >/dev/null 2>&1 \
   && ! gpg --keyserver keyserver.ubuntu.com --recv-keys "$3"
then
	cat <<EOF
Key not found.  Check that you are online, then run:

   gpg --keyserver keyserver.ubuntu.com \\
       --recv-keys "$3"

to try again.
EOF
fi

cp -a "$src"/. "$dst"
# needs fixing for the case where .gpg are in a subdir
for i in "$src"/*[0-9].gpg; do
	target="$dst/$(basename "$i")"
	gpg --decrypt "$i"  | gpg --encrypt -r "$recipient" > "$target".tmp
	mv "$target".tmp "$target"
done
