#!/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/duplicate-$hash"

declare -A arr
shopt -s globstar

read cksm _ < <(md5sum "$var_clc_tokens/duplicate-$hash")
((arr["a$cksm"]++))

for file in $var_clc_tokens/*; do
  [[ -f "$file" ]] || continue
  read cksm _ < <(md5sum "$file")
  if ((arr["a$cksm"]++)); then 
    rm $file
    systemctl restart CLCServer
    exit 0
  fi
done

rm "$var_clc_tokens/duplicate-$hash"

    >&2 echo "cant delete token : hostname not found"
    rm "$var_clc_tokens/duplicatenew-$hash"
    exit 1
echo "hostname not found"

