#!/bin/bash -e


help_msg="Usage: (ID=<TVM_ID>|FILE=<FILE_WITH_TVM_ID>) tvm_curl <curl_params>"


if [ -z "$ID" ]; then
    if [ -n "$FILE" ]; then
        ID="$(cat $FILE)"
    elif [ -f "/tvm2_root_client_id" ]; then
        ID="$(cat /tvm2_root_client_id)"
    elif [ -f "/app/config/config.yml" ]; then
        ID=`python3 -c "
import yaml
print(next(filter(lambda m: m['_name'] == 'ymod_tvm', yaml.safe_load(open('/app/config/config.yml', 'r'))['config']['modules']['module']))['configuration']['service_id'])
"`
    else
        echo -e "$help_msg"
        exit 1
    fi
fi

[ -z "$ID" ] && echo -e "$help_msg" && exit 1

if [ "$SSH_USER" != "root" ] && [ -n "$SSH_USER" ]; then
    LOGIN="$SSH_USER"
else
    LOGIN="$(ssh-add -l | head -n1 | cut -d' ' -f3 | cut -d/ -f3 | cut -d@ -f1)"
fi


TICKET="$(tvmknife get_service_ticket sshkey -s '2002458' -d "$ID" -l "$LOGIN" 2>/dev/null)"


curl -H "X-Ya-Service-Ticket: $TICKET" "$@"
