#!/bin/bash
set -f

[ -z $AKEYLESS_PROXY ] && HOST=https://rest.akeyless.io || HOST=$AKEYLESS_PROXY
[ -z $AKEYLESS_PROXY_SKIP_VERIFY ] && SKIP_VERIFY="" || SKIP_VERIFY="-k"
IDX=1
PREV_ARG=0
STRIP=0
DEBUG=0
EQUAL='='
is_config=false
if [[ "$1" == "auth" || "$1" == "configure" ]]; then
    is_config=true
    if [ "$AKEYLESS_PROXY" == "http://127.0.0.1:8080" ] && [ "$AKEYLESS_PUBLIC" == "" ]; then
        max_to="-m 4"
        creds_hash=`echo "$@" | md5sum | awk '{print $1}'`
        check_token_file=~/.akeyless/.tmp_tokens/${creds_hash}
        if [ -f ${check_token_file} ]; then
            LAST_TOKEN_FETCH=`stat -c%Z ${check_token_file}`
            TIME_NOW=`date '+%s'`
            if [ "$((TIME_NOW - 5))" -le "$LAST_TOKEN_FETCH" ]; then
                touch ${check_token_file}
                cat ${check_token_file}
                exit 0
            fi
        fi
    fi
fi

restore_token() {
    hash1=$1
    cached_token_file=~/.akeyless/.tmp_tokens/${hash1}
    [ -f ${cached_token_file} ] && touch ${cached_token_file} && cat ${cached_token_file}
}

raw_url_encode() {
  local string="$*"
  local strlen=${#string}
  local encoded=""
  local pos c o
  for (( pos=0 ; pos<strlen ; pos++ )); do
     c=${string:$pos:1}
     case "$c" in
        [-_.~a-zA-Z0-9] ) o="${c}" ;;
        * )               printf -v o '%%%02x' "'$c"
     esac
     encoded+="${o}"
  done
  echo "${encoded}"    # You can either set a return variable (FASTER)
  REPLY="${encoded}"   #+or echo the result (EASIER)... or both... :p
}

for var in "$@"
do
    [ $DEBUG == 1 ] && echo "$var"
    if [ "$var" == "--strip" ]; then
        STRIP=1
        continue
    fi
    if [ $STRIP == 1 ]; then
        STRIP_VAL=$var
        STRIP=2
        continue
    fi
    if [ $IDX == 1 ]; then
        CMD=${var#--}
    elif [[ $var == --* ]]; then # arg before equal
        var=${var#--}
        case $var in
        (*"$EQUAL"*)
            var_lv=${var%%"$EQUAL"*}
            var_rv=${var#*"$EQUAL"}
            var="${var_lv}=$(raw_url_encode $var_rv)"
            ;;
        (*)
            ;;
        esac
        CMD="${CMD}&${var}"
        PREV_ARG=1
    elif [ $PREV_ARG == 1 ]; then # value after equal
        PREV_ARG=0
        CMD="${CMD}=$(raw_url_encode $var)"
    else # arg without equals
        CMD="${CMD}&$(raw_url_encode $var)"
    fi
    IDX=$((IDX+1))
done

echo "${CMD}" | grep -q "token"
[ $? -eq 0 ] || CMD="$CMD&token=$(cat ~/.vault-token 2>/dev/null)"
if [ $STRIP != 0 ]; then
    RUN=`curl -s -d "proxy=1&cmd=${CMD}" $HOST $SKIP_VERIFY | jq -r .$STRIP_VAL`
else
    RUN=`curl ${max_to} -s -d "proxy=1&cmd=${CMD}" $HOST $SKIP_VERIFY`
    if [ "$max_to" != "" ]; then
      echo "$RUN" | grep -qi "succe"
      if [ $? -eq 0 ]; then # successful auth
        mkdir -p ~/.akeyless/.tmp_tokens
        echo "$RUN" > ~/.akeyless/.tmp_tokens/$creds_hash
      else # has failure - restore from previous
        RUN=`restore_token $creds_hash`
      fi
    fi
fi
echo $RUN | grep -qi "exit status 1"
if [ $? -eq 0 ]; then # has failure
    echo "$RUN" 1>&2
    exit 175
else
    [ "$is_config" == "true" ] && echo "$RUN" | grep '"token": "' | cut -d '"' -f 4 > ~/.akeyless/latest_token
    echo "$RUN"
fi
exit 0

