#!/usr/bin/env bash

# -------------------------------------------------------------------------- #
# Copyright 2002-2024, 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.                                             #
#--------------------------------------------------------------------------- #

set -eo pipefail

# avoid executing this script when no $USER_DATA or $USERDATA is granted (avoids locking multi-stage builds)
export USER_DATA="${USER_DATA:-${USERDATA}}"
if [ -z "$USER_DATA" ]; then
    echo "No USER_DATA env variable found. Skipping execution..."
    exit 0
fi

CLOUDINIT_BASE_DIR="/var/lib/one-context/cloudinit"
CLOUDINIT_ENV_FILE="${CLOUDINIT_BASE_DIR}/cloudinit_env.sh"

lock_and_cleanup()
{
    # write cloud-init boot finished file
    date +"%Y-%m-%d %H:%M:%S" > "${CLOUDINIT_LOCK_FILE}"
    rm -rf "${CLOUDINIT_RUNCMD_TMP_DIR}"
}

# Source cloudinit env vars
# shellcheck source=/dev/null
. "${CLOUDINIT_ENV_FILE}"

if [ -e "${CLOUDINIT_LOCK_FILE}" ]; then
    echo "Lock file exists in ${CLOUDINIT_LOCK_FILE}. Skipping execution..."
    exit 0
fi

trap lock_and_cleanup EXIT

# Execute cloudinit scripts
if [ -e "${CLOUDINIT_RUNCMD_TMP_SCRIPT}" ]; then

    chmod u+x "${CLOUDINIT_RUNCMD_TMP_SCRIPT}"

    echo "Executing ${CLOUDINIT_LOCK_FILE}..."
    set +e
    $SHELL -ex "${CLOUDINIT_RUNCMD_TMP_SCRIPT}"
    EXIT_CODE=$?
    set -e
    if [ "${EXIT_CODE}" -ne 0 ]; then
        echo "runcmd script execution failed. Exit code: ${EXIT_CODE}"
        exit 1
    fi
    echo "runcmd script execution finished"

else
    echo "No runcmd script found in: ${CLOUDINIT_RUNCMD_TMP_SCRIPT}. Skipping execution..."
fi

