#!/bin/bash
# vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80:
#
# Copyright (c) 2016 Red Hat, Inc.
# Author: Nathaniel McCallum <npmccallum@redhat.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

TMP='{"protected":{"cty":"jwk-set+json"}}'

trap 'exit' ERR

shopt -s nullglob

HASHES=`jose alg -k hash`

if [ $# -ne 2 ] || [ ! -d "$1" ]; then
    echo "Usage: $0 <jwkdir> <cachedir>" >&2
    exit 1
fi

[ ! -d "$2" ] && mkdir -p -m 0700 "$2"

src=`realpath "$1"`
dst=`realpath "$2"`

payl=()
sign=()

for jwk in $src/*.jwk; do
    if jose jwk use -i "$jwk" -r -u sign -u verify; then
        sign+=("-s" "$TMP" "-k" "$jwk")
        payl+=("-i" "$jwk")
    elif jose jwk use -i "$jwk" -r -u deriveKey; then
        payl+=("-i" "$jwk")
    else
        echo "Skipping invalid key: $jwk" >&2
    fi
done

if [ ${#sign[@]} -gt 0 ]; then
    jose jwk pub -s "${payl[@]}" \
        | jose jws sig -I- "${sign[@]}" -o "$dst/.default.jws"
    mv -f "$dst/.default.jws" "$dst/default.jws"
    new=default.jws
fi

shopt -s dotglob

for jwk in $src/*.jwk; do
    for hsh in $HASHES; do
        thp=`jose jwk thp -i "$jwk" -a $hsh`

        if jose jwk use -i "$jwk" -r -u deriveKey; then
            ln -sf "$jwk" "$dst/.$thp.jwk"
            mv -f "$dst/.$thp.jwk" "$dst/$thp.jwk"
            new="$new\n$thp.jwk"
        elif jose jwk use -i "$jwk" -r -u sign; then
            keys=("${sign[@]}" -s "$TMP" -k "$jwk")
            jose jwk pub -s "${payl[@]}" \
                | jose jws sig -I- "${keys[@]}" -o "$dst/.$thp.jws"
            mv -f "$dst/.$thp.jws" "$dst/$thp.jws"
            new="$new\n$thp.jws"
        fi
    done
done

for f in "$dst"/*; do
    b=`basename "$f"`
    echo -e "$new" | grep -q "^$b\$" || rm -f "$f"
done
