#!/bin/bash

# Detect the EnginFrame directory from the current script.
# Known limitations: don't resolve symlinks
#
get_enginframe_dir() {
    local -- _target="${BASH_SOURCE[0]}"

    (
    cd "$(dirname "${_target}")/.." 2>/dev/null && pwd
    )

}


# Get the value of Java-style property from the specified properties file.
#
get_property_from_file() {
    local _fname=''
    local _property_name=''

    while [ "$#" -gt 0 ]; do
        case "$1" in
            -f|--file)
                _fname="$2"
                shift
                ;;
            -p|--property-name)
                _property_name="$2"
                shift
                ;;
            *)
                return 1
                ;;
        esac
        shift
    done

    if [ -z "${_fname}" ]; then
        return 2
    fi

    if [ -z "${_property_name}" ]; then
        return 3
    fi

    awk \
        -v name="${_property_name}" \
        '
        BEGIN {
            FS="="
        }

        {
            sub(/^ +/, "", $1)
            sub(/ +$/, "", $1)
            if ($1 == name) {
                value=$2
            }
        }

        END {
            print value
        }
        ' \
        "${_fname}"
}


die() {
    printf '%s\n' "$1" >&2
    if [ -n "${_exit_code}" ]; then
        exit "${_exit_code}"
    else
        exit 1
    fi
}
    
    
main() {

    _enginframe_dir="$(get_enginframe_dir)"

    if [ -z "${_enginframe_dir}" ]; then
        die "Unable to guess the enginframe directory"
    fi

    if [ ! -d "${_enginframe_dir}" ]; then
        die "Wrong EnginFrame directory detected: ${_enginframe_dir}"
    fi

    _current_version_file="${_enginframe_dir}/current-version"

    echo "Reading EnginFrame version from: ${_current_version_file}"

    if [ ! -r "${_current_version_file}" ]; then
        die "Missing required parameter EnginFrame version directory to launch" 
    fi

    _current_version=$( get_property_from_file -p 'EF_VERSION' -f "${_enginframe_dir}/current-version")

    if [ -z "${_current_version}" ]; then
        die "Unable to detect the current version"
    fi

    echo "Current version: ${_current_version}"

    EF_VERSION_ROOT="${_enginframe_dir}/${_current_version}"

    if [ ! -d "${EF_VERSION_ROOT}" ]; then
        die "Directory ${EF_VERSION_ROOT} does not exists"
    fi

    if [ ! -x "${EF_VERSION_ROOT}/bin/enginframe" ]; then
        die "Unable to find ${EF_VERSION_ROOT}/bin/enginframe launcher"
    fi

    "${EF_VERSION_ROOT}/bin/enginframe" "$@"
    exit $?
}


main "$@"


#
# vi: ts=4 sw=4 et syntax=sh :
#

