#!/bin/sh -e
# vim: set ts=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80:
#
# Copyright (c) 2020 Red Hat, Inc.
# Author: Sergio Correia <scorreia@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/>.
#

SUMMARY="Perform rotation of tang keys"

usage() {
    _ret="${1:-1}"
    exec >&2
    echo "Usage: ${0} [-h] [-v] -d <KEYDIR>"
    echo
    echo "${SUMMARY}"
    echo
    echo "  -d KEYDIR  The directory with the keys, e.g. /var/db/tang"
    echo
    echo "  -h         Display this usage information"
    echo
    echo "  -v         Verbose. Display additional info on keys created/rotated"
    echo
    exit "${_ret}"
}

log() {
    _msg="${1}"
    _verbose="${2:-}"
    [ -z "${_verbose}" ] && return 0
    echo "${_msg}" >&2
}

error() {
    log "${1}" 1
    usage 1
}

set_perms() {
    chmod -- 0440 "${1}"
    if ! chown -- tang:tang "${1}" 2>/dev/null; then
        echo "Unable to change owner/group for ${1} to tang:tang" >&2
    fi
}

JWKDIR=
VERBOSE=
while getopts "hvd:" o; do
    case "${o}" in
        d) JWKDIR="${OPTARG}";;
        h) usage 0;;
        v) VERBOSE=1;;
        *) usage 1;;
    esac
done

[ -z "${JWKDIR}" ] && error "Please specify the keys directory with -d switch"
[ -r "${JWKDIR}" ] || error "Error trying to access JWK directory '${JWKDIR}'"

cd "${JWKDIR}" || error "Unable to change to keys directory '${JWKDIR}'"
    # Disable advertisement of current keys.
    for key in *.jwk; do
        [ -r "${key}" ] || continue
        mv -f -- "${key}" ."${key}"
        log "Disabled advertisement of key ${key} -> .${key}" "${VERBOSE}"
    done

    # Create a new set of keys.
    DEFAULT_THP_HASH="S256"

    # Set default umask for file creation.
    umask 0337

    for alg in "ES512" "ECMR"; do
        json="$(printf '{"alg": "%s"}' "${alg}")"
        jwe="$(jose jwk gen --input "${json}")"
        thp="$(printf '%s' "${jwe}" | jose jwk thp --input=- \
                                           -a "${DEFAULT_THP_HASH}")"
        echo "${jwe}" > "${thp}.jwk"
        set_perms "${thp}.jwk"
        log "Created new key ${thp}.jwk" "${VERBOSE}"
    done
cd - >/dev/null

log "Keys rotated successfully" "${VERBOSE}"
