#!/bin/sh
# env
# Written in 2020,2022 by Lucas
# CC0 1.0 Universal/Public domain - No rights reserved
#
# To the extent possible under law, the author(s) have dedicated all
# copyright and related and neighboring rights to this software to the
# public domain worldwide. This software is distributed without any
# warranty. You should have received a copy of the CC0 Public Domain
# Dedication along with this software. If not, see
# <http://creativecommons.org/publicdomain/zero/1.0/>.

usage()
{
	printf "Usage: %s newkey\n" "${0##*/}" >&2
	exit 1
}

err()
{
	printf "%s: %s\n" "${0##*/}" "$*" >&2
	exit 1
}

newsekrit()
{
	SEKRIT_DIR="$newdir" SEKRIT_GPG_ID="$newkey" sekrit "$@"
}

[ $# -eq 1 ] || usage
newkey=$1
gpg2 -k "$newkey" >/dev/null || err "can't find key $newkey"

umask 077
newdir=$(mktemp -dt sekrit-XXXXXXXXXX) ||
    err "failed to create temporary directory"
scratch=$(mktemp -tp "$newdir" .sekrit-scratch-XXXXXXXXXX) ||
    err "failed to create scratch file"
trap 'rm -fr -- "$scratch" "$newdir"' INT QUIT TERM

sekrit ls | while IFS= read -r entry; do
	printf "%s... " "$entry"
	sekrit get "$entry" >|"$scratch" ||
	    err "failed to export entry $entry"
	newsekrit add "$entry" <"$scratch" ||
	    err "failed to import entry $entry"
	printf "OK\n"
done
rm -f "$scratch"

outdir=sekrit-rekey-$(date +%Y%m%d)
if mv "$newdir" "$outdir"; then
	finaldir=$outdir
else
	finaldir=$newdir
fi
printf "New sekrit store can be found at %s\n" "$finaldir"
