#!/bin/sh

RDD_VERSION="3.1"

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'
ERR_EXIST='1'

print_help()
{
    printf "%s\n" "
Usage:
rootrdd [-d]
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.

Parameters:
-d
  prints only dir with existing configs (rdd.conf.d/, rdd.def)
  and returns error otherwise.

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
        if test -z "${dir_MUST_EXIST}" ; then
            printf "%s\n" "${MSG_NOTHING_FOUND}" 1>&2
            printf "%s\n" "${current_dir}"
        else
            exit "${ERR_EXIST}"
        fi
    fi
}

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

rdd_root
