#!/bin/sh

##########################################################################
#   Script description:
#       Prompt user and take input with a provided default value.
#       
#   History:
#   Date        Name        Modification
#   2012-01-08  Jason Bacon Begin
##########################################################################

##########################################################################
#   Main
##########################################################################

tty=`tty`
if [ $# != 3 ]; then
    cat << EOM > $tty
Usage: $0 tag "question" default-answer

    'tag' is a name used to uniquely identify this question in the
    recorded responses.  It must be a single word without spaces or
    special shell characters, and must be unique across all calls
    to $0.  The concatenation of \$AUTO_ASK_TAG_PREFIX and tag is
    added to ~/.config/auto-ask-responses.  Suffix AUTO_ASK_TAG_PREFIX
    with a - if you would like a separator, e.g.
    
    export AUTO_ASK_TAG_PREFIX=desktop-installer-
    
    'question' must be enclosed in quotes if it contains spaces or
    special characters.
    
    'default-answer' must also be enclosed in quotes if it contains
    spaces or special characters.

    Environment:
    
    If AUTO_ASK_USE_DEFAULTS is set (to anything), the user will
    not be prompted, and auto-ask will echo the default response
    from auto-ask-responses if possible, otherwise from argument 3.
    
    AUTO_ASK_TAG_PREFIX is prepended to tag.  This should be set to
    the name of the calling script or something similar to avoid tag
    name collisions with other scripts in
    ~/.config/auto-ask-responses.

EOM
    exit 1
fi

tag=$AUTO_ASK_TAG_PREFIX$1
question="$2"

dot_config=$HOME/.config
response_file=$dot_config/auto-ask-responses
mkdir -p $dot_config
touch $response_file

default_response="`awk -F'|' '$1 == "'$tag'" { print $2 }' $response_file`"
if [ 0"$default_response" = 0 ]; then
    default_response="$3"
fi

if [ -z $AUTO_ASK_USE_DEFAULTS ]; then
    valid=0
    while [ $valid = 0 ]; do
	printf "$question [$default_response] " > $tty
	read resp
	# resp cannot contain '|'
	if echo "$resp" | fgrep '|'; then
	    printf "Sorry, responses cannot contain '|'.\n" > $tty
	else
	    valid=1
	fi
    done
fi

if [ 0"$resp" = 0 ]; then
    resp="$default_response"
fi

awk -F'|' '$1 != "'$tag'" { print $0 }' $response_file > $response_file.temp
mv -f $response_file.temp $response_file
printf "${tag}|${resp}\n" >> $response_file

printf "$resp\n"
