#!/bin/sh
#
# vim:set ts=4 et:
#
# generate config.mk for gbsplay Makefile
#
# 2003-2006,2008,2010,2015,2017-2019 (C) by Christian Garbs <mitch@cgarbs.de>
#                                           Tobias Diedrich <ranma+gbsplay@tdiedrich.de>
# Licensed under GNU GPL v1 or, at your option, any later version.
#

## initialize interpreter parameters

set -u # bail on use of uninitialized variables
trap 'exit_trap' EXIT

## initialize variables

EXTRA_ALL=
EXTRA_INSTALL=
EXTRA_SRCS=
EXTRA_UNINSTALL=
EXTRA_I18NFLAGS=
XMMS_INPUT_PLUGIN_DIR=
CC="${CC-gcc}" # use gcc by default
CONFIGURE_FLAGS="${CONFIGURE_FLAGS- }"
CFLAGS="${CFLAGS-}"
LDFLAGS="${LDFLAGS-}"
HOSTCC="$CC"
HOSTOS=$(uname)
HOSTARCH=$(uname -m)
BUILDCC="$HOSTCC"
BUILDOS="$HOSTOS"
BUILDARCH="$HOSTARCH"
TMPDIR=${TMPDIR-/tmp}

package=gbsplay
prefix=/usr/local
exec_prefix=
bindir=
libdir=
mandir=
docdir=
localedir=
mimedir=
appdir=
sysconfdir=
buildalias=
hostalias=

## define sane environment
unset LC_ALL LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY \
      LC_MESSAGES LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE      \
      LC_MEASUREMENT LC_IDENTIFICATION
LANG=C
export LANG

## sane echo is in /usr/ucb on Solaris
if [ -d /usr/ucb ]; then
    PATH="/usr/ucb:$PATH"
fi

## set default version number to unknown
# will be overwritten on git build or tar.gz export
VERSION=unknown

##### begin of subroutines

exit_trap()
{
    EXIT_CODE=$?
    test $EXIT_CODE -ne 0 && tail config.err
    exit $EXIT_CODE
}

## die with error
die()
{
    test -n "$1" && echo "$1"
    rm -rf "$TEMPDIR"
    exit 1
}

## check for presense of include files
check_include()
{
    include="$1"
    includedirs="${2-} /usr/local/include /opt/local/include"
    includename="$(echo "$include" | sed -e 's@[/\.]@_@g')"
    eval "value=\${have_${includename}-}"
    test -z "$value" || return

    flags=""
    for dir in "" $includedirs; do
        msg="checking for $include"
        test -z "$dir" || msg="$msg in $dir"
        test -z "$dir" || flags="-I$dir"
        if cc_check "$msg" "have_$includename" "$flags" ok <<EOF; then
#include <$include>
int main(int argc, char **argv) {
    return 0;
}
EOF
            eval "include_${includename}_path=\"$dir \""
            return 0
        fi
    done
    return 1
}

## find library path needed for lib
find_lib()
{
    lib="$1"
    libdirs="${2-} /usr/local/lib /opt/local/lib"

    eval "val=\"\${lib${lib}_path-}\""
    if [ ! -z "$val" ]; then
        return 0
    else
        for dir in "" $libdirs; do
            msg="looking for -l$lib"
            flags="-l$lib"
            test -z "$dir" || msg="$msg in $dir"
            test -z "$dir" || flags="$flags -L$dir"
            if cc_check "$msg" "" "$flags" ok <<EOF; then
int main(int argc, char **argv) { return 0; }
EOF
                eval "lib${lib}_path=\"$dir \""
                return 0
            fi
        done
    fi
    return 1
}

## remove duplicate flags
remove_dupes()
{
    flags="$1"
    newflags=""
    for i in $flags; do
        dupe=0
        for j in $newflags; do
            test "$i" = "$j" && dupe=1
        done
        if [ $dupe -eq 0 ]; then
            newflags="$(test -z "$newflags" || printf "%s " "$newflags")$i"
        fi
    done
    echo "$newflags"
}

append_nodupe()
{
    varname="$1"
    dupe=0

    while [ -n "${2-}" ]; do
        eval "flags=\"\$$varname\""
        append="$2"

        if [ -n "$flags" ]; then
            for i in $flags; do
                test "$i" = "$append" && dupe=1
            done
        fi

        if [ $dupe -eq 0 ]; then
            if [ -z "$flags" ]; then
                eval "${varname}=\"$append\""
            else
                eval "${varname}=\"$flags $append\""
            fi
        fi
        shift
    done
}

## check for needed extra libraries and library paths for a lib
check_libs()
{
    INFILE="$TEMPDIR/cl.c"
    OUTFILE="$TEMPDIR/cl"
    checklib="$1"
    extralibs="${2-}"
    extralibdirs="${3-}"
    name="${4-}"
    extraflags="${5-}"
    msg="${6--l$checklib}"
    cflags="$CFLAGS $LDFLAGS"

    eval "lib${checklib}_flags="

    cat > "$INFILE"

    cc_check "checking if we need additional libs for $msg" "" "$extraflags" "no" "yes" < "$INFILE"
    test $? -eq 0 && return 0

    for extralib in $extralibs; do
        find_lib "$extralib" "$extralibdirs"
        test $? -ne 0 && return 1
        eval "val=\"\$lib${extralib}_path\""
        if [ "$val" != " " ]; then
            append_nodupe extraflags "-L$val"
        fi
    done

    minerrs=$($BUILDCC -o "$OUTFILE" "$INFILE" $cflags "-l$checklib" $extraflags 2>&1 | wc -l)
    for extralib in $extralibs; do
        errs=$($BUILDCC -o "$OUTFILE" "$INFILE" $cflags "-l$checklib" "-l$extralib" $extraflags 2>&1 | wc -l)
        if [ "$errs" -lt "$minerrs" ]; then
            minerrs=$errs
            append_nodupe extraflags "-l$extralib"
        fi
    done

    if [ "$minerrs" -ne 0 ]; then
        return 1
    fi

    eval "lib${checklib}_flags=\"$extraflags\""
    return 0
}

## generalized 'does it compile' check
cc_check()
{
    INFILE="$TEMPDIR/cc.c"
    OUTFILE="$TEMPDIR/cc"
    name="$1"
    varname="$2"
    flags="$CFLAGS $LDFLAGS ${3-}"
    okmsg="${4-ok}"
    errmsg="${5-not found}"

    test "$name" && printf "%s:  " "$name"

    cat > "$INFILE"
    
    if "$BUILDCC" -o "$OUTFILE" "$INFILE" $flags; then
        test "$name" && echo "$okmsg"
        test "$varname" && eval "$varname=yes"
        return 0
    else
        test "$name" && echo "$errmsg"
        test "$varname" && eval "$varname=no"
        return 1
    fi
}

cc_has_flag()
{
    flag="$1"
    cc_check "checking if cc supports ${flag}" "" "${flag} -Werror" yes no <<EOF
int main(int argc, char **argv) { return 0; }
EOF
}

need_include() {
    if ! check_include "$1"; then
        die "Could not find $1, which is needed for compilation."
    fi
}

## config.h helper
have_x() {
    localvar="have_$(echo $1 | tr A-Z a-z)"
    eval "result=\$$localvar"
    if [ "$result" = "yes" ]; then
        echo "#define HAVE_$1 1"
    else
        echo "/* #undef HAVE_$1 */"
    fi
}

plugout_x() {
    localvar="use_$(echo $1 | tr A-Z a-z)"
    eval "result=\$$localvar"
    if [ "$result" = "yes" ]; then
        echo "#define PLUGOUT_$1 1"
    else
        echo "/* #undef PLUGOUT_$1 */"
    fi
}

use_x() {
    localvar="use_$(echo $1 | tr A-Z a-z)"
    eval "result=\$$localvar"
    if [ "$result" = "yes" ]; then
        echo "#define USE_$1 1"
    else
        echo "/* #undef USE_$1 */"
    fi
}

## external which is unreliable
which()
{
    IFS_SAVE="$IFS"
    IFS=:
    PROGRAM="$1"
    for ELEMENT in $PATH; do
        if [ -z "$ELEMENT" ]; then
            ELEMENT=.
        fi
        if [ -f "$ELEMENT/$PROGRAM" ] && [ -x "$ELEMENT/$PROGRAM" ]; then
            IFS="$IFS_SAVE"
            echo "$ELEMENT/$PROGRAM"
            return 0
        fi
    done
    IFS="$IFS_SAVE"
    return 1
}

# set variable to default value if empty
# really the same as $var="${var-$default}"
setdefault()
{
    eval "value=\$$1"
    if [ -z "$value" ]; then
        eval "$1=$2"
    fi
}

# check if $1 is a known feature
isknown()
{
    for i in $OPTS; do
        if [ "$i" = "$1" ]; then
            return 0
        fi
    done

    if [ "${1#use_}" != "$1" ]; then
        echo "unknown feature '${1#use_}'"
    elif [ "${1#build_}" != "$1" ]; then
        echo "unknown module '${1#build_}'"
    else
        echo "unknown option '$2'"
    fi
    echo
    return 1
}

# list enabled $1 (modules, features)
# of type $2 (build, use)
printoptional()
{
    printf "%s %s:" "${3-optional}" "$1"
    for i in $OPTS; do
        eval "val=\$$i"
        if [ "${i#${2}_}" != "$i" ]; then
            if [ "$val" = "yes" ]; then
                printf " +%s" "${i#${2}_}"
            elif [ "$val" = "no" ]; then
                printf " -%s" "${i#${2}_}"
            fi
        fi
    done
    echo
}

# remember state of use_$1
remember_use()
{
    eval "remembered=\$use_$1"
}

# check state of use_$1 against remembered state
# error out if option was requested but can't be satisfied after checks
recheck_use()
{
    eval "val=\$use_$1"
    if [ "$remembered" = 'yes' ] && [ "$val" != 'yes' ]; then
        die "error: --enable-$1 was requested but is not available"
    fi
}

# parse option $1
parseoption()
{
    case $1 in
    --prefix=*)
        prefix="${1#--prefix=}"
        ;;
    --exec-prefix=*)
        exec_prefix="${1#--exec-prefix=}"
        ;;
    --bindir=*)
        bindir="${1#--bindir=}"
        ;;
    --mandir=*)
        mandir="${1#--mandir=}"
        ;;
    --docdir=*)
        docdir="${1#--docdir=}"
        ;;
    --localedir=*)
        localedir="${1#--localedir=}"
        ;;
    --mimedir=*)
        mimedir="${1#--mimedir=}"
        ;;
    --appdir=*)
        appdir="${1#--appdir=}"
        ;;
    --sysconfdir=*)
        sysconfdir="${1#--sysconfdir=}"
        ;;
    --infodir=*)
        infodir="${1#--infodir=}"
        ;;
    --datadir=*)
        datadir="${1#--datadir=}"
        ;;
    --localstatedir=*)
        localstatedir="${1#--localstatedir=}"
        ;;
    --host=*)
        hostalias="${1#--host=}"
        HOSTCC="${hostalias}-${CC}"
        ;;
    --build=*)
        buildalias="${1#--build=}"
        BUILDCC="${buildalias}-${CC}"
        ;;
    --have-*)
        eval "have_${1#--have-}=yes"
        isknown "have_${1#--have-}" "$1" || usage 1
        ;;
    --donthave-*)
        eval "have_${1#--donthave-}=no"
        isknown "have_${1#--donthave-}" "$1" || usage 1
        ;;
    --enable-*)
        eval "use_${1#--enable-}=yes"
        isknown "use_${1#--enable-}" || usage 1
        ;;
    --disable-*)
        eval "use_${1#--disable-}=no"
        isknown "use_${1#--disable-}" || usage 1
        ;;
    --with-*)
        eval "build_${1#--with-}=yes"
        isknown "build_${1#--with-}" || usage 1
        ;;
    --without-*)
        eval "build_${1#--without-}=no"
        isknown "build_${1#--without-}" || usage 1
        ;;
    CFLAGS=*)
        CFLAGS="${1#CFLAGS=}"
        ;;
    LDFLAGS=*)
        LDFLAGS="${1#LDFLAGS=}"
        ;;
    --help)
        usage 0
        ;;
    *)
        echo "unknown option '$1'"
        echo
        usage 1
        ;;
    esac
}
##### end of subroutines

## enable logging of errors

ERRORLOG=config.err
exec 2> $ERRORLOG

## find a path for tmp directory

TMPPATH="/tmp"
if [ "$TMPDIR" ]; then
    TMPPATH="$TMPDIR"
fi

if [ ! -d "$TMPPATH" ]; then
    TMPPATH="."
fi

## generate tmp directory

BASENAME="$(basename "$0")"
if [ "$(which mktemp)" != "" ]; then
    TEMPDIR="$(mktemp -d "$TMPPATH/$BASENAME.XXXXXXXXXX")"
    RESULT=$?
else
    TEMPDIR="$TMPPATH/$BASENAME.$$"
    mkdir "$TEMPDIR"
    RESULT=$?
fi
if [ $RESULT -ne 0 ]; then
    echo "can't create temporary directory at <$TMPPATH>!"
    exit 1;
fi

usage()
{
    cat<<EOF
Usage: $0 [OPTION]...

Configuration:
  --help                 display this help and exit

Installation directories:
  --prefix=PREFIX        install architecture-independent files in PREFIX
                         [/usr/local]
  --exec-prefix=EPREFIX  install architecture-dependent files in EPREFIX
                         [PREFIX]
  --bindir=BINDIR        install binaries in BINDIR
                         [EPREFIX/bin]
  --libdir=BINDIR        install binaries in LIBDIR
                         [EPREFIX/lib]
  --mandir=MANDIR        install manpages in MANDIR
                         [PREFIX/man]
  --docdir=DOCDIR        install documentation in DOCDIR
                         [PREFIX/share/doc/$package]
  --sysconfdir=SCONFDIR  look for system-wide configuration file in SCONFDIR
                         [/etc]

Optional Features:
  --disable-i18n         omit libintl support
  --disable-regparm      do not use register arguments on x86
  --disable-hardening    disable hardening flags
  --enable-debug         build with debug code
  --enable-sharedlibgbs  build libgbs as a shared library
  --enable-regparm       build with explicit regparm support
                         (enabled by default on Linux x86 only)

Optional Modules:
  --with-xmmsplugin      build XMMS input plugin
  --without-contrib      don't install contrib scripts
  --without-test         don't test gbsplay output during build

Output Plugins:
  --disable-alsa         omit ALSA sound output plugin
  --disable-devdsp       omit /dev/dsp sound output plugin
  --disable-dsound       omit Direct Sound output plugin
  --disable-iodumper     omit iodumper plugin
  --disable-midi         omit MIDI file writer plugin
  --disable-altmidi      omit alternative MIDI file writer plugin
  --disable-nas          omit NAS sound output plugin
  --disable-pulse        omit PulseAudio sound output plugin
  --disable-stdout       omit stdout file writer plugin
EOF
    exit "$1"
}

OPTS=""
OPTS="${OPTS} build_contrib"
OPTS="${OPTS} build_test"
OPTS="${OPTS} build_xmmsplugin"
OPTS="${OPTS} use_alsa"
OPTS="${OPTS} use_debug"
OPTS="${OPTS} use_devdsp"
OPTS="${OPTS} use_dsound"
OPTS="${OPTS} use_hardening"
OPTS="${OPTS} use_i18n"
OPTS="${OPTS} use_iodumper"
OPTS="${OPTS} use_midi"
OPTS="${OPTS} use_altmidi"
OPTS="${OPTS} use_nas"
OPTS="${OPTS} use_pulse"
OPTS="${OPTS} use_regparm"
OPTS="${OPTS} use_sharedlibgbs"
OPTS="${OPTS} use_stdout"
for OPT in $OPTS; do
    eval "${OPT}="
done

## load user config
if [ -f config.conf ]; then
    printf "loading config.conf... "
    while read -r line; do
        parseoption "$line"
    done < config.conf
    echo ok
fi

## flags from CONFIGURE_FLAGS env (for travis-ci)
for flag in ${CONFIGURE_FLAGS}; do
    parseoption "$flag"
done

## commandline flags
while [ "${1-}" ]; do
    parseoption "$1"
    shift
done

## on Linux x86, regparm defaults to on

if (      [ "$BUILDARCH" = "i386"   ] \
       || [ "$BUILDARCH" = "i486"   ] \
       || [ "$BUILDARCH" = "i586"   ] \
       || [ "$BUILDARCH" = "i686"   ] \
       || [ "$BUILDARCH" = "x86_64" ] \
   ) && [ "$BUILDOS" = "Linux" ]; then
    setdefault use_regparm yes
    setdefault build_test yes
else
    setdefault use_regparm no
    setdefault build_test no
fi

## more defaults
setdefault build_xmmsplugin no
setdefault build_contrib yes
setdefault use_hardening yes
## disable test when cross-compiling
if [ -n "$buildalias" ] && [ "$buildalias" != "$hostalias" ]; then
    build_test=no
fi

## check for C compiler

printf "checking for working compiler:  "
INFILE="$TEMPDIR/cc.c"
OUTFILE="$TEMPDIR/cc"

cat > "$INFILE" <<EOF
int main(int argc, char **argv) {
    return 0;
}
EOF
$BUILDCC -o "$OUTFILE" "$INFILE" $CFLAGS $LDFLAGS
RESULT=$?
if [ $RESULT -eq 0 ]; then
    if [ "$buildalias" ] && [ "$buildalias" != "$hostalias" ]; then
        echo "cross-compiling, skipping execute check"
    else
	if [ -s "$OUTFILE" ]; then
            if "$OUTFILE"; then
		echo "ok"
            else
		die "can't execute generated code"
            fi
	else
            die "no code generated"
	fi
    fi
else
    die "error executing '$BUILDCC'"
fi

# Check git timestamp

if [ -f .git/HEAD ]; then
    VERSION=$(git describe --tags)
fi

## check for cygwin environment

printf "checking if OS is Cygwin:  "
if [ "$(uname -o)" = "Cygwin" ]; then
    cygwin_build=yes
    echo "yes"
else
    cygwin_build=no
    echo "no"
fi

## check for various headers

need_include inttypes.h

if [ "$use_devdsp" != no ]; then
    remember_use devdsp
    check_include sys/soundcard.h
    use_devdsp="$have_sys_soundcard_h"
    recheck_use devdsp
fi

if [ "$use_alsa" != no ]; then
    remember_use alsa
    check_include alsa/asoundlib.h
    use_alsa="$have_alsa_asoundlib_h"
    cc_check "checking for ESTRPIPE support" have_estrpipe <<EOF
#include <errno.h>
#include <alsa/asoundlib.h>
int main(int argc, char **argv)
{
    if (ESTRPIPE == 0)
        return 1;  /* Never reached. */
    return 0;
}
EOF
    recheck_use alsa
fi

if [ "$use_dsound" != no ]; then
    remember_use dsound
    check_include dsound.h
    retval1=$?
    retval2=1
    if [ $retval1 -eq 0 ]; then
        check_libs dsound "dsound dsound3d" <<EOF
#include <windows.h>
#include <dsound.h>
int main(int argc, char** argv) {
    LPDIRECTSOUND8 lp;
    HRESULT hr = DirectSoundCreate8(NULL, &lp, NULL);
    if (SUCCEEDED(hr)) IDirectSound8_Release(lp);
    return 0;
}
EOF
        retval2=$?
    fi
    use_dsound=no
    if [ "$retval1" -eq 0 ] && [ "$retval2" -eq 0 ]; then
        use_dsound="$have_dsound_h"
    fi
    recheck_use dsound
fi

if [ "$use_pulse" != no ]; then
    remember_use pulse
    check_include pulse/simple.h
    use_pulse="$have_pulse_simple_h"
    recheck_use pulse
fi

if [ "$use_nas" != no ]; then
    remember_use nas
    check_include audio/audiolib.h "/usr/X11R6/include"
    retval1=$?
    retval2=1
    if [ $retval1 -eq 0 ]; then
        check_libs audio "X11 Xt m" "/usr/X11R6/lib /usr/X11/lib /usr/lib/X11" <<EOF
int main(int argc, char **argv) { return 0; }
EOF
        retval2=$?
    fi
    use_nas=no
    if [ "$retval1" -eq 0 ] && [ "$retval2" -eq 0 ]; then
        if [ "$include_audio_audiolib_h_path" != " " ]; then
            append_nodupe CFLAGS "-I$include_audio_audiolib_h_path"
        fi
        use_nas=yes
    fi
    recheck_use nas
fi

if [ "$use_i18n" != no ]; then
    remember_use i18n
    check_include locale.h
    check_include libintl.h

    ## check for gettext

    printf "checking for gettext tools:  "
    have_xgettext=yes
    for i in xgettext msgmerge msgfmt msgen; do
        if [ "$(which $i)" = "" ]; then
            test "$have_xgettext" = "yes" && echo "not ok"
            have_xgettext=no
            echo "$i is missing"
        fi
    done
    test "$have_xgettext" = "yes" && echo "ok"

    use_i18n=no
    if [ "$have_locale_h" = "yes" ] && [ "$have_libintl_h" = "yes" ]; then
        if [ "$include_locale_h_path" != " " ]; then
            append_nodupe CFLAGS "-I$include_locale_h_path"
            EXTRA_I18NFLAGS="$EXTRA_I18NFLAGS -I$include_locale_h_path"
        fi
        if [ "$include_libintl_h_path" != " " ]; then
            append_nodupe CFLAGS "-I$include_libintl_h_path"
            EXTRA_I18NFLAGS="$EXTRA_I18NFLAGS -I$include_libintl_h_path"
        fi
        use_i18n=yes
    fi
    recheck_use i18n
fi

if [ "$use_i18n" = "yes" ]; then
    check_libs c "intl" "" "" "$EXTRA_I18NFLAGS" "i18n" <<EOF
#include <libintl.h>
int main(int argc, char **argv)
{
    bindtextdomain("foo", "bar");
    textdomain("foo");
    gettext("msg");
    return 0;
}
EOF
    if [ $? -eq 0 ] && [ "$libc_flags" != "" ]; then
        append_nodupe LDFLAGS "$libc_flags"
    fi
fi

if [ "$build_xmmsplugin" != "no" ]; then
    ## check for pthread

    PTHREAD=
    check_include pthread.h
    if [ "$have_pthread_h" = "yes" ]; then
        cc_check "checking for Linux flavoured pthread" have_pthread "-lpthread" found no <<EOF
#include <pthread.h>
int main(int argc, char **argv)
{
    pthread_self();
    return 0;
}
EOF
        if [ $? -eq 0 ]; then
            PTHREAD="-lpthread"
        else
            cc_check "checking FreeBSD-flavoured pthread" have_pthread "-pthread" found no <<EOF
#include <pthread.h>
int main(int argc, char **argv)
{
    pthread_self();
    return 0;
}
EOF
            if [ $? -eq 0 ]; then
                PTHREAD="-pthread"
            else
                echo "no known pthread implementation found!"
            fi
        fi
    fi

    ## check for glib development files

    printf "checking for glib-dev:  "
    GLIB_CFLAGS=
    if CONFIG=$(which glib-config); then
        if GLIB_CFLAGS=$(glib-config --cflags); then
            echo "ok"
        else
            echo "error running glib-config --cflags!"
        fi
    else
        echo "glib-config not found!"
    fi

    ## check for xmms development files

    printf "checking for xmms-dev:  "
    XMMS_CFLAGS=
    if CONFIG=$(which xmms-config); then
        if XMMS_CFLAGS=$(xmms-config --cflags); then
            if XMMS_INPUT_PLUGIN_DIR=$(xmms-config --input-plugin-dir); then
                echo "ok"
            else
                echo "error running xmms-config --input-plugin-dir!"
            fi
        else
            echo "error running xmms-config --cflags!"
        fi
    else
        echo "xmms-config not found!"
    fi
else
    GLIB_CFLAGS=
    XMMS_CFLAGS=
    PTHREAD=
fi

## can XMMS be built?

if [ "$build_xmmsplugin" != "no" ] && [ "$GLIB_CFLAGS" ] && [ "$XMMS_CFLAGS" ] && [ "XMMS_INPUT_PLUGIN_DIR" ] && [ "$PTHREAD" ]; then
    append_nodupe CFLAGS $GLIB_CFLAGS $XMMS_CFLAGS
    EXTRA_INSTALL="$EXTRA_INSTALL install-gbsxmms.so"
    EXTRA_UNINSTALL="$EXTRA_UNINSTALL uninstall-gbsxmms.so"
    build_xmmsplugin=yes
else
    build_xmmsplugin=no
fi

## check compiler features

if cc_has_flag "-Wdeclaration-after-statement"; then
    append_nodupe CFLAGS "-Wdeclaration-after-statement"
fi
if cc_has_flag "-Wvla"; then
    append_nodupe CFLAGS "-Wvla"
fi
if cc_has_flag "-Wimplicit-fallthrough"; then
    append_nodupe CFLAGS "-Wimplicit-fallthrough"
fi
if cc_has_flag "-Wswitch-unreachable"; then
    append_nodupe CFLAGS "-Wswitch-unreachable"
fi

if [ "$use_hardening" != "no" ]; then
    if cc_has_flag "-Wl,-z,relro"; then
        append_nodupe LDFLAGS "-Wl,-z,relro"
    fi

    if cc_has_flag "-Wl,-z,now"; then
        append_nodupe LDFLAGS "-Wl,-z,now"
    fi

    if cc_has_flag "-Wl,-pie"; then
        append_nodupe LDFLAGS "-Wl,-pie"
    elif cc_has_flag "-pie"; then
        append_nodupe LDFLAGS "-pie"
    fi

    if cc_has_flag "-fstack-protector-strong"; then
        append_nodupe CFLAGS "-fstack-protector-strong"
        append_nodupe LDFLAGS "-fstack-protector-strong"
    elif cc_has_flag "-fstack-protector"; then
        append_nodupe CFLAGS "-fstack-protector"
        append_nodupe LDFLAGS "-fstack-protector"
        append_nodupe CFLAGS "--param=ssp-buffer-size=4"
    fi
    if cc_has_flag "-fstack-clash-protection"; then
        append_nodupe CFLAGS "-fstack-clash-protection"
        append_nodupe LDFLAGS "-fstack-clash-protection"
    fi
fi

if [ "$use_regparm" != "no" ]; then
    cc_check "checking for regparm support" use_regparm <<EOF
void __attribute__((regparm(3))) foo(void)
{
}
int main(int argc, char **argv)
{
    foo();
    return 0;
}
EOF
fi

## set variables we have no test for to default values if not set

setdefault exec_prefix "$prefix"
setdefault bindir      "$exec_prefix/bin"
setdefault libdir      "$exec_prefix/lib"
setdefault mandir      "$prefix/man"
setdefault docdir      "$prefix/share/doc/$package"
setdefault localedir   "$prefix/share/locale"
setdefault mimedir     "$prefix/share/mime"
setdefault appdir      "$prefix/share/applications"
setdefault sysconfdir  "/etc"

setdefault use_sharedlibgbs no
setdefault use_debug no

setdefault use_midi yes
setdefault use_altmidi yes
setdefault use_stdout yes
setdefault use_iodumper yes

printoptional modules build
printoptional features use

append_nodupe CFLAGS -D_FORTIFY_SOURCE=2 -Wall -fsigned-char

if [ "$use_debug" = "yes" ]; then
    append_nodupe CFLAGS -g3
else
    append_nodupe CFLAGS -Os -pipe -fomit-frame-pointer
fi

EXTRA_CFLAGS="$CFLAGS"
EXTRA_LDFLAGS="$LDFLAGS"
echo "EXTRA_CFLAGS=$EXTRA_CFLAGS"
echo "EXTRA_LDFLAGS=$EXTRA_LDFLAGS"

## write configuration

(
    set +u  # Allow uninitialised vars here
    while read -r var; do
        eval "echo \"$var := \$$var\""
    done << __EOF__
EXTRA_ALL
EXTRA_CFLAGS
EXTRA_INSTALL
EXTRA_LDFLAGS
EXTRA_SRCS
EXTRA_UNINSTALL
PTHREAD
XMMS_INPUT_PLUGIN_DIR
VERSION
prefix
exec_prefix
bindir
libdir
mandir
docdir
localedir
mimedir
appdir
sysconfdir
CC
BUILDCC
HOSTCC
build_contrib
build_test
build_xmmsplugin
have_xgettext
use_i18n
use_sharedlibgbs
cygwin_build
libaudio_flags
__EOF__
    echo plugout_alsa := $use_alsa
    echo plugout_devdsp := $use_devdsp
    echo plugout_dsound := $use_dsound
    echo plugout_iodumper := $use_iodumper
    echo plugout_midi := $use_midi
    echo plugout_altmidi := $use_altmidi
    echo plugout_nas := $use_nas
    echo plugout_pulse := $use_pulse
    echo plugout_stdout := $use_stdout
) > config.mk

(
    set +u  # Allow uninitialised vars here
    echo "#ifndef _CONFIG_H_"
    echo "#define GBS_VERSION \"$VERSION\""
    echo "#define LOCALE_PREFIX \"$localedir\""
    echo "#define SYSCONF_PREFIX \"$sysconfdir\""
    plugout_x ALSA
    plugout_x DEVDSP
    plugout_x DSOUND
    plugout_x IODUMPER
    plugout_x MIDI
    plugout_x ALTMIDI
    plugout_x NAS
    plugout_x PULSE
    plugout_x STDOUT
    use_x I18N
    use_x REGPARM
    have_x ESTRPIPE
    echo "#endif"
) > config.h

(
    echo "s/%%%VERSION%%%/$VERSION/g"
) > config.sed

## end

rm -rf "$TEMPDIR"
test -s $ERRORLOG || rm $ERRORLOG
