#!/bin/bash

if [ -z "$1" ]
then
>&2 echo "cant creat a token : hostname must not be empty"
exit 1
fi

export filename="/etc/clc/server.conf"
var_clc_tokens=`cat $filename | python -c "import sys, json; print json.load(sys.stdin)['server']['tokens']['path']"`

apikey="`cat /dev/urandom | tr -dc 'A-Za-z0-9' | fold -w 90 | head -n 1`"
hash="`echo -n "$apikey" |sha512sum | awk '{print $1}'`"
host="`basename $1`"

printf "$host" > "$var_clc_tokens/duplicatenew-$hash"

declare -A arr
shopt -s globstar

for file in $var_clc_tokens/*; do
  [[ -f "$file" ]] || continue
  read cksm _ < <(md5sum "$file")
  if ((arr["a$cksm"]++)); then
    >&2 echo "cant creat a token : hostname already exist"
    rm "$var_clc_tokens/duplicatenew-$hash"
    exit 1
  fi
done

    rm "$var_clc_tokens/duplicatenew-$hash"


printf "$host" > "$var_clc_tokens/$hash"
echo -n "$apikey"
>&2 echo ""

