#!/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=/var/run/one-context/one_env
MOUNT_DIR=${MOUNT_DIR:-/mnt}
TOKENTXT=$(cat "${MOUNT_DIR}/token.txt")

if [ -n "$ONEGATE_TOKEN" ]; then
    TOKENTXT="$ONEGATE_TOKEN"
fi

umask 0377
echo "export TOKENTXT=\"$TOKENTXT\"" > $ENV_FILE
echo "export VMID=\"$VMID\"" >> $ENV_FILE
echo "export ONEGATE_ENDPOINT=\"$ONEGATE_ENDPOINT\"" >> $ENV_FILE

function export_rc_vars
{
  if [ -f $1 ] ; then
    ONE_VARS=$(cat $1 | egrep -e '^[a-zA-Z\-\_0-9]*=' | sed 's/=.*$//')

    . $1

    for v in $ONE_VARS; do
        echo "export $v=\"${!v}\"" >> $ENV_FILE
    done
  fi
}

export_rc_vars ${CONTEXT_FILE}

chown root:root $ENV_FILE
chmod 0400 $ENV_FILE

