#!/bin/sh

RDD_VERSION="3.0"

MSG_NOTHING_FOUND="
Warning: no rdd configs were found (rdd.conf.d/, rdd.def).
Using current directory as the root of working directory.
"

MSG_NO_DIR="Error: no valid current directory."
ERR_NO_DIR='2'

print_help()
{
    printf "%s\n" "
Usage:
rootrdd
rootrdd --help|--version

rootrdd prints the root of current rdd(1) working directory.
any(1) build process resides there.
Command does not read the contents of configuration files.
This is shell implementation.

See \"man any\", \"man rdd\" for further details.
"
}

rdd_root()
{
    current_dir="$(pwd -P)"
    if ! test -d "${current_dir}" ; then
        printf "%s\n" "${MSG_NO_DIR}"
        exit ${ERR_NO_DIR}
    fi
    
    found_dir=
    checking_dir="${current_dir}"
    while test -n "${checking_dir}" ; do
        if test -r "${checking_dir}/rdd.def" -o -d "${checking_dir}/rdd.conf.d/" ; then
            found_dir="${checking_dir}"
            break
        fi
    
        checking_dir="${checking_dir%/*}"
    done
    if test -z "${checking_dir}" ; then
        if test -r "/rdd.def" -o -d "/rdd.conf.d/" ; then
            found_dir="/"
        fi
    fi
    
    if test -n "${found_dir}" ; then
        printf "%s\n" "${found_dir}"
    else
        printf "%s\n" "${MSG_NOTHING_FOUND}" 1>&2
        printf "%s\n" "${current_dir}"
    fi
}

case "$1" in
    --help)
            print_help
            exit 0
        ;;
    --version)
            printf "%s\n" "${RDD_VERSION}"
            exit 0
        ;;
esac

rdd_root
