#!/bin/sh
# study ham exam question pools
# Copyright (C) 2011 John Nogatch <jnogatch@yahoo.com>

# dir where question pools reside?
INSTALLDIR="$(dirname "$(readlink -f $0)")"

# dir to keep user's unanswered questions
USERDIR=~/.hamexam

# create user dir, if needed
if [ ! -d "${USERDIR}" ]; then
    echo "creating ${USERDIR}"
    mkdir "${USERDIR}"
    if [ $? -ne 0 ]; then
	echo "unable to create ~/.hamexam directory"
	exit 1
    fi
fi

# check argument for T, G, or E, default to showing usage, version, brief help
# set POOL within set {T,G,E}
case "$1" in
    "2" | [tT]* ) POOL="T";;
    "3" | [gG]* ) POOL="G";;
    "4" | [eE]* ) POOL="E";;

    *) echo "usage: hamexam {t|g|e}";
	echo "hamexam version 1.0.1";
	echo "Technician, Element 2 effective July-2010";
	echo "General, Element 3 effective July-2011";
	echo "Extra, Element 4 effective July-2008";
	echo "hamexam is an interactive study guide for USA FCC amateur radio (ham radio) examinations.";
	echo "The 3 question pools are:";
	echo "    t element 2, Technician Class (entry level),";
	echo "    g element 3, General Class (also requires element 2),";
	echo "    e element 4, Extra Class (also requires elements 2 and 3).";
	echo "Questions are chosen randomly from the selected pool.";
	echo "Incorrect answers cause the question to be asked again later.";
	echo "Licenses are issued by the FCC, but exams are conducted by Volunteer Examiners."
	echo "For more information about USA amateur radio licensing: http://www.arrl.org/licensing-preparation-exams";
	exit 1;;
esac

# go to user dir so that question names are accessible
cd ${USERDIR}
if [ $? -ne 0 ]; then
    echo "unable to access ~/.hamexam directory"
    exit 1
fi

# if no questions remain, reload all the questions
ls ${POOL}* >> /dev/null 2>&1
if [ $? -ne 0 ]; then
    case ${POOL} in
	"T" ) echo "reloading Technicican Class element 2";;
	"G" ) echo "reloading General Class element 3";;
	"E" ) echo "reloading Extra Class element 4";;
	"" | * ) echo "POOL variable was not set correctly";
	    exit 1;;
    esac
    ls "${INSTALLDIR}"/${POOL} | xargs touch
else
    echo "resuming remaining questions"
fi

# bring up diagrams for this element, if not already running
for PNG in ${INSTALLDIR}/${POOL}*.png ; do
    ps -f | fgrep -v fgrep | fgrep "evince ${PNG}" >> /dev/null 2>&1
    if [ $? -ne 0 ]; then
	evince ${PNG} &
    fi
done

# report how many questions remain
ls ${POOL}* | wc | awk '{print $1 " questions remain in this pool\n"}'

while :; do
    # random choice from remaining questions
    Q=`shuf -n 1 -e ${POOL}*`

    # exit if no more questions
    if [ "${Q}" = "${POOL}*" ]; then
	echo "question pool ${POOL} completed"
	break
    fi

    # ask the question
    awk -f "${INSTALLDIR}"/ask.awk "${INSTALLDIR}"/${POOL}/"${Q}"

    case $? in
	# if correct, remove the question
	0) rm "${Q}";;

	# check for quit or EOF
	2) break;;
    esac
done

# end of hamexam
