#!/bin/bash

# hpdet, part of hprofile, by Martin Aspeli <optilude@gmx.net>
# Released under the GNU General Public License

# hpdet is used to determine which profile is to be used, given a profile
# type. For example, to find out the currently valid "boot" profile, run
# "hpdet boot". Run hpdet -h for more help.

VERSION="2.0b1"
CONFIG="/etc/hprofile/conf"

if test -r "${CONFIG}" ; then
	source "${CONFIG}"
else
	echo "Could not find configuration file ${CONFIG}" >&2
	exit 1
fi

print_help () {
  echo "Usage: hpdet -h | -v | <profile type>"
	echo
	echo "    -h              Print this help message and exit"
	echo "    -v              Print version and exit"
	echo "    <profile type>  Type of profile to determine."
	echo
	echo "hpdet looks for a configuration directory for the given profile type"
	echo "in ${cdir}/profiles/<profile type>. "
	echo
	echo "In this directory, two files must be present: 'default', a text file"
	echo "which gives the name of the default profile of this type, and 'ptest',"
	echo "an executable file which, when called, will try to determine which"
	echo "profile should be applied (e.g. by asking the user, examining the"
	echo "kernel command line, or examining some state of the system), and output"
	echo "this to the standard output."
	echo
	echo "The 'ptest' executable for the profile type specified will be called to"
	echo "determine the appropriate profile. If the script is not found or does"
	echo "not output anything, the profile specified in the 'default' file will "
	echo "be used. hpdet then print the name of the profile to the standard "
	echo "output."
	
}

print_version () {
	echo "hpdet version ${VERSION}"
}

init () {
	local opt
	while getopts "hv" opt ; do
		case "${opt}" in
			h)
				print_help
				exit 0
				;;
			v)
				print_version
				exit 0
				;;
			*)
				print_help
				exit 1
				;;
		esac
	done
}

init $@
profile_type=${1}

if test -z "${profile_type}" ; then
	print_help
	exit 1
fi

profile_dir="${cdir}/profiles/${profile_type}"
profile=""

# Run the ptest script. If it exists and echoes nonzero, its output is taken as
# the name of the profile

if test -x "${profile_dir}/ptest" ; then
	profile=$(${profile_dir}/ptest)
fi

if test -z "${profile}" -a -r "${profile_dir}/default" ; then
	profile=$(cat "${profile_dir}/default" | head -n 1)
fi

if test -n "${profile}" ; then
	echo "${profile}"
	exit 0
else
	echo "Unable to determine ${profile_type} profile." >&2
	exit 1
fi
