#!/bin/sh

set -e
reload="yes"

# Utilities

yesno()
{
    local N="N" Y="Y"
    local q="$1" def=$(eval "echo -n \$$2")

    while :
    do
        echo -n "$q? [$def] "
        read REPLY
        REPLY=$(echo -n "$REPLY" | sed -e "s/^\ *//" -e "s/^\t*//")
        test -n "$REPLY" || REPLY="$def"

        case "$REPLY" in
            [Yy]*)
                echo yes > /dev/null
                eval "$2=\"Y\""
                return 0
            ;;

            [Nn]*)
                echo no > /dev/null
                eval "$2=\"N\""
                return 1
            ;;
        esac
    done
}

# Processing options

while [ $# -gt 0 ]
do
    case "$1" in
        --no-reload)
            reload=""
            shift
        ;;

        *)
            echo "Usage: $0 [--no-reload]" >&2
            exit 2
        ;;
    esac
done

# Starting configuration
echo "Configuring the PrimeNet GIMPS client..."
echo
echo "You are about to execute the prime-net client in configuration mode."
echo "The first time around it will ask you all the necessary questions "
echo "to configure itself."
echo "*** Do not use your login password as the GIMPS password ***"
echo "Doing so would compromise security at your site as that password is"
echo "sent over the network in clear by prime-net."
echo "Once you have answered all the questions, prime-net will fetch work "
echo "to do and start processing it. At that point press ^C so that it can "
echo "be restarted in the background as should be."
echo
echo "After the initial installation, prime-net will display the general "
echo "menu. The main configuration related sections are:"
echo "     2.  Test/User Information"
echo "    15.  Options/CPU"
echo "and  6.  Test/Exit"
echo
echo "Make sure you review the rules for participation in the EFF contest."
echo "See /usr/doc/prime-net/copyright"
echo
echo "[Hit return]"
read foo
cd /var/lib/prime-net
su daemon -c "./prime-net -m"

# Restarting the client
if [ "$reload" ] &&  \
   yesno "Restart the PrimeNet client now with the new configuration" Y
then
    /etc/init.d/prime-net restart
fi
