#!/bin/bash

#
# Search for libgenrunlevel
#
LIB=${0%/*}/libgenrunlevel
[ -d ${LIB} ] || LIB="/lib"
LIB+=/libgenrunlevel

if [ ! -e ${LIB} ]; then
	echo "ERROR: ${LIB} not found!"
	exit 1
fi

#
# Load libgenrunlevel
#
. ${LIB}


[ ${#} -eq 0 ] && set -e -- -help

while [ ${#} -gt 0 ]; do
	case "${1}" in
	-all)
		all=true
		;;
	-overwrite)
		overwrite=true
		;;
	-dist=*)
		distro=${1#-dist=}
		;;
	-dist)
		shift
		dist=${1}
		;;
	-path=*)
		search_path=${1#-path=}
		;;
	-path)
		shift
		search_path=${1}
		;;
	-destdir=*)
		DESTDIR=${1#-destdir=}
		;;
	-destdir)
		shift
		DESTDIR=${1}
		;;
	-confdir=*)
		CONFDIR=${1#-confdir=}
		;;
	-confdir)
		shift
		CONFDIR=${1}
		;;
	-help)
		echo 'USAGE:' >&2
		echo " ${0} [-overwrite] [-path=PATH] [-destdir=PATH] [-confdir=PATH] -all" >&2
		echo " ${0} [-overwrite] [-path=PATH] [-destdir=PATH] [-confdir=PATH] FILE" >&2
		echo " ${0} -help" >&2
		exit 0
		;;
	--)
		shift
		break
		;;
	*)
	 	break
	 	;;
	esac
	shift
done

[ "${CONFDIR}" ] || CONFDIR="${DESTDIR}/etc/initng"
mkdir -p "${CONFDIR}"

[ "${search_path}" ] || search_path=$(echo $(
	for dir in $()/bin /sbin /usr/bin /usr/sbin /usr/kde/\*/bin \
			/usr/kde/\*/sbin /opt/bin /opt/sbin /opt/\*/bin \
			/opt/\*/sbin /usr/local/sbin /usr/local/bin
	do [ "$(echo ${dir})" ] && echo ${dir}
	done | grep -v '*')
)

[ "${all}" ] && set -- $(get_runlevels)

for l; do
	create_list ${l}
done

for rl in ${runlevels}; do
	write_runlevel ${rl} > "${CONFDIR}/${rl}"
done

echo "Done generating files."
