#!/usr/bin/env bash

## Creates an initial mtmock.conf and tries to set the
## SCRIPTDIR and WORLDDIR members.
SCRIPTDIRS="/usr/share/games/minetest/builtin /usr/share/minetest/builtin"
WORLDDIRS=$HOME/.minetest/worlds

help() {
    cat <<-_EOF_
		usage:  $(basename $0) [-h] [-D SRCHDIR]

		    -h, --help
		        show this help page

		    -D SRCHDIR
		        adds SRCHDIR to the internal list of search directories

		To successfully execute the unit tests, the code defined in mtmock.lua
		has to be complemented with some directory locations.  Those locations
		are expected to be defined via the LUA file mtmock.conf.  This script
		aids in the creation of that file by scanning some predefined directories
		for the proper locations and writes the file to the current directory.
_EOF_
    exit 0
}

while [ $# -gt 0 ]; do
    case $1 in
        -h|--help)
            help
            ;;
        -D)
            shift
            SCRIPTDIRS="$1 ${SCRIPTDIRS}"
            WORLDDIRS="$1 ${WORLDDIRS}"
            ;;
    esac
    shift
done

for sd in ${SCRIPTDIRS}; do
    if [ -d ${sd}/builtin ]; then
        SCRIPTDIR=${sd}/builtin
    elif [ -d ${sd}/common ]; then
        SCRIPTDIR=${sd}
        break
    fi
done

for wd in ${WORLDDIRS}; do
    if [ -d ${wd}/worlds ]; then
        WORLDDIR=${wd}/worlds
    elif [ -d ${wd} ]; then
        WORLDDIR=${wd}
        break
    fi
done

if [ -z "${SCRIPTDIR}" ]; then
    echo "*** $(basename $0): cannot find minetest LUA script directory" >>/dev/stderr
    exit 1
elif [ -z "${WORLDDIR}" ]; then
    echo "*** $(basename $0): cannot find minetest world directory" >>/dev/stderr
    exit 2
fi

cat >mtmock.conf <<-EOF
	-- path to minetest's builtin LUA scrips
	mtmock.SCRIPTDIR='${SCRIPTDIR}/'

	-- path to minetest's worlds
	mtmock.WORLDDIR='${WORLDDIR}/'

	-- path to mods
	mtmock.MODDIR='$(realpath ../mods)/'
EOF

