#!/bin/bash

# ---------------------------------------------------------------------
# Copyright © 2021  Akeyless Security LTD.
#
# All rights reserved
# ----------------------------------------------------------------------

set -f

AKEYLESS_BIN=/usr/local/bin/akeyless
THIS_EXEC=`basename $0`
TOKEN_FILE=$HOME/.vault-token
CRON_JOB="* * * * * $USER /bin/bash $PWD/$THIS_EXEC rotate $TOKEN_FILE"
PROXY_MODE=0

run_init() {
    read -sp 'Initial Universal Identity Token: ' init_token
    RES="\"token\": \"$init_token\""
    echo "**************"
    TOKEN=`echo $RES | grep '"token": "' | sed 's/.*"token": "//g' |  awk '{print $1}' | tr -d '"' | tr -d ','`
    if [ "$TOKEN" != "" ]; then
        echo $TOKEN > ${TOKEN_FILE}
        echo "$OSTYPE" | grep -qi linux
        if [ $? -eq 0 ]; then
            echo $CRON_JOB > ~/.akeyless_universal_identity_rotator
            sudo mv ~/.akeyless_universal_identity_rotator /etc/cron.d/akeyless_universal_identity_rotator
            sudo chown root:root /etc/cron.d/akeyless_universal_identity_rotator
            sudo chmod 644 /etc/cron.d/akeyless_universal_identity_rotator
        else
            (crontab -l 2>/dev/null | grep -v "$THIS_EXEC rotate" ; echo "* * * * * bash $PWD/$THIS_EXEC rotate $TOKEN_FILE") | crontab -
       fi
       echo "AKEYLESS Universal Identity successfully initiated"
    else
        echo "Error! empty token"
    fi
}

run_rotate() {
    [ "$1" != "" ] && TOKEN_FILE=$1
    if [ "$PROXY_MODE" == "1" ]; then
        $AKEYLESS_BIN uid-rotate-token --uid-token $(cat ${TOKEN_FILE}) | grep "ROTATED TOKEN" | cut -d '[' -f 2 | cut -d ']' -f 1 > ${TOKEN_FILE}.1
        mv ${TOKEN_FILE}.1 ${TOKEN_FILE}
    else
        [ ! -d ~/.akeyless ] && $AKEYLESS_BIN --init
        $AKEYLESS_BIN uid-rotate-token -i ${TOKEN_FILE} -o ${TOKEN_FILE} > /dev/null 2>&1
    fi
    exit 0
}

[ "`type -t run_${1}`" == "function" ] && eval run_$1 $2 || echo "Usage: $0 <init/rotate>"
