#!/bin/bash

# $Id: rotatekey.sh 15104 2012-11-08 20:05:17Z yuri $

# USAGE:
#   rotatekey.sh keyname <interval_hrs>

KEYNAME=$1 #(host|full)
INTERVAL_HRS=$2 #must be > cronjob_interval + 10minutes
INTERVAL_HRS=${INTERVAL_HRS:-336} #two weeks if not specified
MAILTO=$LANDER_ADMIN

#just for paths
LANDER_CONFIG=~plander/lander.conf
#read config
if [ -e $LANDER_CONFIG ]; then
    . $LANDER_CONFIG
else
    echo "$DATE ERROR: Config file $CONFIG does not exist" >&2
    exit 1
fi

log() {
    echo "$DATE ERROR: $@" >>$LANDER_ROTATEKEY_LOGFILE
}

die() {
    log "$@"
    exit 1
}

#set umask right away
umask 0077

keydir=
case $KEYNAME in
	( host )
        keydir=$LANDER_HOSTKEYDIR
        ;;
	( full )
        keydir=$LANDER_FULLKEYDIR
        ;;
	( * )
        die "Unexpected keyname for key setup: $KEYNAME"
        ;;
esac

lander_set_DATE

lander_file_exists $keydir || {
    die "keydir $keydir does not exist.  Have you run lander_setup.sh?"
    exit 1
}

keyfile=$(lander_file_ls "$keydir/$KEYNAME-[0-9]*" 2>/dev/null | sort -r | head -1) ||
    die "Cannot ls $keydir/[0-9]*"

if [ -n "$keyfile" ]; then
    #check if it's time to rotate
    if ! lander_file_older "$keyfile" \
                           $(( (INTERVAL_HRS*60-10)*60 )); then
        #too early
        exit 0
    fi
fi

#either doesn't exist or too old: need to generate a new key
cd /tmp
newkey=$KEYNAME-$(date -u +%F)
rm -f $newkey

errormsg=$($LANDER_SCRUBBER -m -s $newkey </dev/null 2>&1)

[ -s $newkey ] || {
    die "Scrubber $LANDER_SCRUBBER failed to create a key $newkey: $errormsg"
}

chgrp ${LANDER_GROUPS[raw]} $newkey
chmod 640 $newkey
lander_file_copylocal $newkey "$keydir/_$newkey" &&
    lander_file_move "$keydir/_$newkey" "$keydir/$newkey" || {
        lander_file_rm "$keydir/_$newkey" "$keydir/$newkey"
        die "failed to copy+rename $newkey to $keydir"
}

#timestamp the old key for convenience
echo "$DATE Aged $oldreal, new: $newkey" >>$LANDER_ROTATEKEY_LOGFILE

#next dagscrubber job will generate a new key
echo "rotated to newkey: $newkey"
