#! /bin/sh 

cur_flags=$-
echo "current flags: $cur_flags"

set -e

CUR_PATH=$(dirname "$0")
CUR_PATH=$(cd "$CUR_PATH" && pwd)
ROOT_PATH=$(dirname "$CUR_PATH")
LICENSE_PATH="$ROOT_PATH/license"

echo "starting license client"
echo "license client home path: $LICENSE_PATH"

cd $LICENSE_PATH

echo -e "127.0.0.1\tlicense-client" >> /etc/hosts

touch /etc/machine-id

export GOPROXY='http://nexus.iwarma.ru/repository/proxy-go/' \
       GOPRIVATE='gitlab.iwarma.ru' \
       GONOPROXY='gitlab.iwarma.ru' 

NETRC_PATH="$CUR_PATH/.netrc"

echo "machine gitlab.iwarma.ru" > $NETRC_PATH
echo "login $NETRC_USER" >> $NETRC_PATH
echo "password $NETRC_TOKEN" >> $NETRC_PATH 

mv $NETRC_PATH /root/ #maybe you should comment some extra dns in /etc/resolv.conf
go mod tidy 
go build -ldflags "-s -w"

./client --config config_example.json </dev/null >/dev/null 2>&1 &

client_response=0
client_counter=0
client_timeout=10

set +e

while [ "$client_response" != 200 ] && [ "$client_response" != 404 ] && [ "$client_counter" != "$client_timeout" ]; do
    client_response=$(curl -s -o /dev/null -w "%{http_code}" -X GET http://license-client:8050/license/)
    sleep 1s
    client_counter=$(( $client_counter + 1 ))
done

echo "client response: $client_response"
echo "client counter: $client_counter"

#client_PID=$(pidof client)

cd $ROOT_PATH

case "e" in
  "$cur_flags")
  set -e
  ;;
  *)
  set +e
  ;;
esac