#!/bin/sh

# Copyright (C) 2008 Jonathan Moore Liles                                     #
#                                                                             #
# This program is free software; you can redistribute it and/or modify it     #
# under the terms of the GNU General Public License as published by the       #
# Free Software Foundation; either version 2 of the License, or (at your      #
# option) any later version.                                                  #
#                                                                             #
# This program is distributed in the hope that it will be useful, but WITHOUT #
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       #
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for   #
# more details.                                                               #
#                                                                             #
# You should have received a copy of the GNU General Public License along     #
# with This program; see the file COPYING.  If not,write to the Free Software #
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  #
#

. scripts/colors

#####
## support functions for 'configure' scripts.

fatal ()
{
    echo "$BOLD$RED$*$SGR0" > /dev/stderr
    exit 255
}

UPDATE=no
HELP=no

split ()
{
    while [ $# -gt 0 ]
    do
        echo $1
        shift 1
    done
}

if [ $# -gt 0 ]
then
    case "$1" in
        --update)
            UPDATE=yes
            shift 1
            ;;
        --help)
            HELP=yes
            shift 1
            ;;
        *)
#            fatal "This is not an autoconf script. Run it without any options and you will be prompted."
            ;;
    esac

    if [ $# -gt 0 ]
    then
        echo "## options" > .config

        split "$@" | sed '
s/--\(enable\|disable\)-\([^ =]\+\)/--\1-\U\2/g;
s/--enable-\([^ =]\+\)=\(.*\)/USE_\1=\2/g;
s/--enable-\([^ =]\+\)/USE_\1=yes/g;
s/--disable-\([^ =]\+\)/USE_\1=no/g;
s/--\([^ =]\+\)/\1/g;
' | sed -n '/^[^ =]\+=./p' >> .config
        UPDATE=yes;
    fi
fi

if [ $HELP != yes ] && [ $UPDATE != yes ]
then
    if ! ( [ -t 0 ] && [ -t 1 ] )
    then
        fatal "not a terminal!"
    fi
fi

ask ()
{
    local A D O

    D="`eval echo \\$$2`"
    D=${D:-$3}

    if [ $HELP = yes ]
    then
        if [ "$3" = yes ] || [ "$3" = no ]
        then
            O=`echo -n "$2" | sed s/^USE_/--enable-/ | tr '[[:upper:]]' '[[:lower:]]'`
        else
            O=`echo -n "--$2" | tr '[[:upper:]]' '[[:lower:]]'`
        fi

        printf "    ${BOLD}${GREEN}%-15s${SGR0}\t%-40s (currently: ${BOLD}%s${SGR0})\n" "$O" "$1" "$D"

        return
    fi

    echo -n "$BLACK$BOLD::$SGR0 ${1}? [$BOLD${D}$SGR0] "

    if [ $UPDATE = yes ]
    then
        A="$D"
        echo
    else
        read A
        A=${A:-$D}
    fi

    if [ "$3" = yes ] || [ "$3" = no ]
    then
        case "$A" in
            no | n | N) A=no ;;
            yes | y | Y) A=yes ;;
            * ) fatal "Invalid response. Must be 'yes' or 'no'" ;;
        esac
    fi

    append "${2}=${A:-$D}"
}

ok ()
{
    echo -e '\r'`tput cuf 30`"$BOLD${GREEN}ok${SGR0} ${*:+${BOLD}${BLACK}($*)${SGR0}}"
}

failed ()
{
    echo "$BOLD${RED}failed!${SGR0}" > /dev/stderr
    rm -f .config
}

using ()
{
    [ "`eval echo \\$USE_$1`" = yes ]

    return $?
}

upcase ()
{
    echo "$*" | tr '[[:lower:]]' '[[:upper:]]'
}

extract_options ()
{
    local line name value

    if [ -f .config ]
    then
        {
            while read line
            do
                [ "$line" = "## options" ] && break
            done

            while read line
            do
                if [ "$line" = "## libs" ]
                then
                    break
                else
                    name=${line%=*}
                    value=${line#*=}
                    eval "$name='$value'"
                fi
            done
        } < .config
    fi
}

begin ()
{
    echo -n "Checking sanity..."
    require_command pkg-config pkg-config > /dev/null
    require_command sed sed > /dev/null
    ok
}

warn ()
{
    echo " ${BOLD}${YELLOW}* ${SGR0}$*"
}

info ()
{
    echo "${BOLD}${CYAN}--- ${SGR0}$*"
}

begin_options ()
{
    # get the old values
    extract_options

    if [ $HELP = yes ]
    then
        echo
        warn "This is a ${BOLD}non-configure${SGR0} script. Run without any arguments and you will be prompted"
        warn "with configuration choices. Alternatively, you may use the following autoconf style"
        warn "arguments for non-interactive configuration."
        echo
        echo " Available options:"
        echo
    else
        echo > .config
        append "# This file was automatically generated on `date`. Any changes may be lost!"
        append "## options"

        if [ $UPDATE = yes ]
        then
            info "Updating configuration"
        else
            info "Configuration required"
        fi
    fi
}

begin_tests ()
{
    if [ $HELP = yes ]
    then
        echo
        exit 0;
    fi

    append "## libs"
    extract_options
}

append ()
{
    echo "$1" >> .config
}

end ()
{
    info "Configuration complete"
    touch .config
}

require_command ()
{
    echo -n "Checking for ${BOLD}$1${SGR0}..."

    if ! [ -x "`which $2`" ]
    then
	failed
	fatal "Command $1 not found."
    else
	ok
    fi
}

require_package ()
{
    local name

    echo -n "Checking for $BOLD$1$SGR0..."
    if ! pkg-config --exists $3
    then
    	failed
	fatal "Required package $1 doesn't appear to be installed."
    elif ! pkg-config --atleast-version $2 $3
    then
        failed
        fatal "The installed version of $1 (`pkg-config --mod-version $3`) is too old."
    fi

    name="`upcase \"$1\"`"
    append "${name}_LIBS=`pkg-config --libs $3`"
    append "${name}_CFLAGS=-DHAVE_${1} `pkg-config --cflags $3`"

    ok `pkg-config --modversion "$3"`
    return 0
}

_test_version ()
{
    [ $1 -gt $4 ] && return 0
    [ $1 -eq $4 ] && [ $2 -gt $5 ] && return 0
    [ $1 -eq $4 ] && [ $2 -eq $5 ] && [ $3 -gt $6 ] && return 0
    [ $1 -eq $4 ] && [ $2 -eq $5 ] && [ $3 -eq $6 ] && return 0
    return 1
}

# return true if #1 is greater than or equal to $2
test_version ()
{
    local IFS
    IFS='.'

    _test_version $1 $2
}

version_of ()
{
    echo `pkg-config --modversion $1`
}

require_FLTK ()
{
    local use

    echo -n "Checking for ${BOLD}FLTK${SGR0}..."

    FLTK_VERSION=`fltk-config --version`

    if ! test_version $FLTK_VERSION $1
    then
        failed
        fatal "The installed FLTK version ($FLTK_VERSION) is too old."
    else
        ok $FLTK_VERSION
    fi

    use=

    while [ $# -gt 1 ]
    do
        shift 1
        use="$use --use-$1"
    done

    append "FLTK_LIBS=`fltk-config $use --ldflags`"
    append "FLTK_CFLAGS=`fltk-config $use --cflags`"
}