user_name="${USER}"
stand_name="${1:-$user_name}"

env_token="${SANDBOX_TOKEN}"
{ file_token=`cat ~/.sandbox_token`; } 2> /dev/null
TOKEN="${file_token:-env_token}"
full_stand_id="tools_femida_$stand_name"

if [ -z "${TOKEN}" ]; then
    echo "
    Couldn't find sandbox token. Save it to a ~/.sandbox_token file or SANDBOX_TOKEN env variable
    https://oauth.yandex-team.ru/authorize?response_type=token&client_id=968e0e6d85d647feb327d893a42cf26f&optional_scope=sandbox:api
    "

    exit 0
fi

echo "Putting a new stage to Deploy..."

sed "s/id: tools_femida_personal_example/id: $full_stand_id/g" ./configs/personal_stand.example.yml > "$stand_name".stand.yml
ya dctl put stage "$stand_name".stand.yml --rewrite-delegation-tokens
rm "$stand_name".stand.yml

echo "Setting up the balancer for a new stage..."

task_id=$(curl -L -X POST 'https://sandbox.yandex-team.ru/api/v1.0/task/' -H 'Authorization: OAuth '$TOKEN -H 'Content-Type: application/json' --data-raw '{
    "template_alias": "INSERT_USNTABLE_FEMIDA_",
    "custom_fields": [
        {
            "name": "megaconfig",
            "value": {
                "endpoint_set": "'$full_stand_id'.backend",
                "skip_domain_upstream_actions": "True",
                "users": [
                    "robot-femida-ci"
                ],
                "guids": [
                    "254182"
                ],
                "namespace": "femida.test.yandex-team.ru",
                "domain": "femida.test.yandex-team.ru",
                "fqdns": [
                    "'$stand_name'.femida.test.yandex-team.ru"
                ],
                "action": "insert_unstable",
                "datacenters": [
                    "myt"
                ],
                "wait": "False"
            }
        }
    ]
}' | grep -o '"id": \d*' | grep -o '\d*')

echo "Sandbox task id $task_id"

curl -L -X PUT 'https://sandbox.yandex-team.ru/api/v1.0/batch/tasks/start' -H 'Authorization: OAuth '$TOKEN -H 'Content-Type: application/json' --data-raw '{
    "id": [
        '$task_id'
    ]
}'
