#!/usr/bin/env bash

# -------------------------------------------------------------------------- #
# Copyright 2002-2020, OpenNebula Project, OpenNebula Systems                #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #

ENV_FILE=${ENV_FILE:-/var/run/one-context/one_env}

if [ "$REPORT_READY" != "YES" ]; then
    exit 0
fi

# $TOKENTXT is available only through the env. file
if [ -f "${ENV_FILE}" ]; then
    . "${ENV_FILE}"
fi

###

if which curl >/dev/null 2>&1; then
    curl -X "PUT" "${ONEGATE_ENDPOINT}/vm" \
        --header "X-ONEGATE-TOKEN: $TOKENTXT" \
        --header "X-ONEGATE-VMID: $VMID" \
        --insecure \
        -d "READY=YES"

    if [ "$?" = "0" ]; then
        exit 0
    fi
fi

if which wget >/dev/null 2>&1; then
    wget --method=PUT "${ONEGATE_ENDPOINT}/vm" \
        --body-data="READY=YES" \
        --header "X-ONEGATE-TOKEN: $TOKENTXT" \
        --header "X-ONEGATE-VMID: $VMID" \
        --no-check-certificate

    if [ "$?" = "0" ]; then
        exit 0
    fi
fi

if which onegate >/dev/null 2>&1; then
    onegate vm update --data "READY=YES"

    if [ "$?" = "0" ]; then
        exit 0
    fi
fi
