#!/bin/bash

VERSION=$(cat version)
IPC_PROTOCOL_VERSION=1

if test -n "$CC"; then
    echo "Forcing compiler to be $CC"
else
    CC="gcc"
fi
NATIVECC="$CC"
TARGETCC="$NATIVECC"
CC="false"

if test -n "$OBJCOPY" ; then
    echo "Forcing objcopy to be $OBJCOPY"
else
    OBJCOPY="objcopy"
fi
TARGETOBJCOPY=$OBJCOPY

if test -n "$AR" ; then
    echo "Forcing ar to be $AR"
else
    AR="ar"
fi
TARGETAR=$AR

ARCHFLAGS=""
if test -n "$CFLAGS"; then
    ARCHFLAGS="$ARCHFLAGS $CFLAGS"
    echo "Adding $ARCHFLAGS to ARCHFLAGS"
fi

ARCHLIBS=""
if test -n "$LDFLAGS"; then
    ARCHLIBS="$ARCHLIBS $LDFLAGS"
    echo "Adding $ARCHLIBS to ARCHLIBS"
fi

PYTHON_INTERPRETER="$(which "python3")"
PYTHON_SETUP_ARGS=""

debug_flags="-g"
packageprefix=""
bencodetoolsprefix=""
user="no"

# components to compile
uselibuade="yes"
useuadefs="no"
useuade123="yes"
useuadecore="yes"
usescore="no"
usewriteaudio="yes"

pkgrequirements="ao"
textscope="no"
n900="no"

set_all_no() {
    uselibuade="no"
    useuadefs="no"
    useuade123="no"
    useuadecore="no"
    usescore="no"
    usewriteaudio="no"
}

for opt in "$@" ; do
	case $opt in

# General compilation options

	--prefix=*)
		prefix=`echo $opt | sed -n 's/--prefix=\(.*\)/\1/p'`
		;;
	--package-prefix=*)
		packageprefix=`echo $opt | sed -n 's/--package-prefix=\(.*\)/\1/p'`
		;;
	--bencode-tools-prefix=*)
		bencodetoolsprefix=`echo $opt | sed -n 's/--bencode-tools-prefix=\(.*\)/\1/p'`
		;;

        --bindir=*)
                bindir=`echo $opt | sed -n 's/--bindir=\(.*\)/\1/p'`
                ;;
	--includedir=*)
		includedir=`echo $opt | sed -n 's/--includedir=\(.*\)/\1/p'`
		;;
	--libdir=*)
		libdir=`echo $opt | sed -n 's/--libdir=\(.*\)/\1/p'`
		;;
	--make=*)
	        MAKE=`echo $opt | sed -n 's/--make=\(.*\)/\1/p'`
		;;
	--mandir=*)
		mandir=`echo $opt | sed -n 's/--mandir=\(.*\)/\1/p'`
		;;
	--sharedir=*)
		sharedir=`echo $opt | sed -n 's/--sharedir=\(.*\)/\1/p'`
		;;
	--pkg-config=*)
	        PKG_CONFIG=`echo $opt | sed -n 's/--pkg-config=\(.*\)/\1/p'`
		;;
	--target-ar=*)
	        TARGETAR=`echo $opt | sed -n 's/--target-ar=\(.*\)/\1/p'`
		;;
	--target-cc=*)
	        TARGETCC=`echo $opt | sed -n 's/--target-cc=\(.*\)/\1/p'`
		;;
	--target-objcopy=*)
	        TARGETOBJCOPY=`echo $opt | sed -n 's/--target-objcopy=\(.*\)/\1/p'`
		;;
	--target=*)
	        tmpvar=`echo $opt | sed -n 's/--target=\(.*\)/\1/p'`
		if test -z "$TARGETCC" ; then
		    TARGETCC="$tmpvar-gcc"
		    TARGETOBJCOPY="$tmpvar-objcopy"
		    TARGETAR="$tmpvar-ar"
		fi
		tmpvar=""
		;;

	--no-debug)
		debug_flags=""
		;;

	--home)
		user="yes"
		;;
        --user)
		user="yes"
		;;

# Options for frontends

	--without-libuade)
		uselibuade="no"
		;;
	--only-libuade)
		set_all_no
		uselibuade="yes"
		;;

	--with-text-scope)
		textscope="yes"
		;;

	--without-uade123)
		useuade123="no"
		;;
	--only-uade123)
		set_all_no
		useuade123="yes"
		;;

	--without-uadecore)
		useuadecore="no"
		;;
	--only-uadecore)
		set_all_no
		useuadecore="yes"
		;;

	--without-uadefs)
		useuadefs="no"
		;;
	--only-uadefs)
		set_all_no
		useuadefs="yes"
		;;

	--without-write-audio)
		usewriteaudio="no"
		;;
	--only-write-audio)
		set_all_no
		usewriteaudio="yes"
		;;

# Miscellaneous options
	--n900)
	        n900="yes"
		;;

	--help)
		echo
		echo "Installation control:"
                echo " --home                 Install uade to user's home directory. Do not run"
		echo "                        'make install' as root!"
                echo " --prefix=path          Install program under 'path'"
	        echo " --package-prefix=path  File installation prefix (for package maintainers)"
		echo " --bencode-tools-prefix=path Set prefix for bencode-tools. File named"
		echo "                        path/lib/libbencodetools.{so|dylib} should exist."
		echo " --bindir=dir           Install executables into this directory"
		echo " --includedir=dir       Add this directory to compilation include path"
		echo " --make=exe             Use 'exe' as the make command"
		echo " --mandir=dir           Install man page to this directory"
		echo " --no-debug             Do not compile debug stuff into executables"
		echo " --libdir=dir           Add this directory to linking path"
		echo " --sharedir=dir         Install data files into this directory"
		echo " --target=arch          Specify target architecture. The compiler will be"
		echo "                        tarch-gcc. (cross compiling)"
		echo " --target-ar=ar         Specify target archiver. (cross compiling)"
		echo " --target-cc=cc         Specify target compiler. (cross compiling)"
		echo " --target-objcopy=objc  Specify target objcopy. (cross compiling)"
		echo
		echo "Plugins and tools to compile:"
		echo " --with-text-scope      Enable text scope support (uade123 --scope)"
		echo " --without-libuade      Do not compile libuade"
		echo " --without-uade123      Do not compile uade123"
		echo " --without-uadecore     Do not compile uadecore. This is useful for"
		echo " --without-write-audio     Do not compile write audio"
		echo "                        distribution makers who want to compile new frontends"
		echo "                        without re-compiling the emulator binary."
		echo " --without-uadefs       Do not compile uadefs filesystem"
		echo " --only-libuade         Compile only libuade"
		echo " --only-uade123         Compile only uade123 plugin"
		echo " --only-uadecore        Compile only uadecore"
		echo " --only-uadefs          Compile only uadefs plugin"
		echo " --only-write-audio     Compile only write audio"
		echo
		echo "Other:"
		echo " --n900                 Set useful parameters for Nokia N900."
		echo "                        This means 22050Hz frequency and mono sound."
		echo
		echo "Library control:"
		echo " --pkg-config=exe       Use 'exe' as pkg-config executable"
		echo
		exit
		;;
	--x-libraries=*)
		;;
	--x-includes=*)
		;;
	*)
		echo "ignoring option $opt"
		;;
	esac
done

if test -z "$PKG_CONFIG" ; then
    PKG_CONFIG="pkg-config"
fi
"$PKG_CONFIG" --version 2> /dev/null > /dev/null || PKG_CONFIG=""
if test -z "$PKG_CONFIG" ; then
    echo
    echo "The system doesn't have pkg-config. You may not be able to compile some frontends (uadefs, ...)"
    echo
fi

# set kernel type (such as AmigaOS) with environment variable $UADEKERNEL
OS="$UADEKERNEL"
if test -z "$OS" ; then
    OS="`uname`"
fi

UNIXSHELL="yes"
UADE123NAME="uade123"
UADECORENAME="uadecore"

SHAREDLIBRARYFLAGS="-fPIC -shared"
SHAREDFLAG="-shared"
SHAREDNAMEFLAG="-Wl,-soname,\$@"
SHAREDSUFFIX="so"

cat >src/frontends/include/uade/sysincludes.h <<EOF
#include <netinet/in.h>
#include <sys/select.h>
EOF

if test -n "$OS" && test "$OS" = "MorphOS"; then
    echo
    echo "Configuring for MorphOS / AmigaOS."
    ARCHFLAGS="$ARCHFLAGS -noixemul"
elif test -n "$OS" && test "$OS" = "AmigaOS"; then
    echo
    echo "Configuring for AmigaOS 4."
    ARCHFLAGS="$ARCHFLAGS -lnet -lauto"
elif test -n "$OS" && test "$OS" = "Darwin"; then
    echo
    echo "Configuring for MacOSX"
    SHAREDLIBRARYFLAGS="-dynamic -bundle -undefined suppress -force_flat_namespace"
    SHAREDFLAG="-dynamiclib"
    SHAREDNAMEFLAG="-install_name \$(LIBDIR)/\$@"
    SHAREDSUFFIX="dylib"
elif test -n "$OS" && test "$OS" = "OpenBSD"; then
    # Force gmake for OpenBSD.
    MAKE="gmake"
elif test -n "$OS" && test "$OS" = "FreeBSD"; then
    cat > src/frontends/include/uade/sysincludes.h <<EOF
#include <sys/param.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <strings.h>
EOF
fi

grep -i cygwin 2>/dev/null >/dev/null <<EOF
$OS
EOF
if test "$?" = "0" ; then
    OS="Cygwin"
    UADE123NAME="uade123.exe"
    UADECORENAME="uadecore.exe"
fi

SOUNDSOURCE="sd-sound-generic.c"
SOUNDHEADER="sd-sound-generic.h"
echo "#include \"$SOUNDSOURCE\"" > src/sd-sound.c;
echo "#include \"$SOUNDHEADER\"" > src/sd-sound.h;

MACHINE="`uname -m`"
if test "$MACHINE" = "parisc"; then
    ARCHFLAGS="$ARCHFLAGS -ffunction-sections"
fi

INSTALLTEST="`which ginstall 2>/dev/null`"

if test ! -x "$INSTALLTEST"; then
 if test -n "$OS" && test "$OS" = "SunOS"; then
  echo
  echo "Warning: ginstall not found, install might not work."
  echo "If you do have ginstall make sure it is in your path."
  echo
  INSTALLTEST="`which install`"
 else
  INSTALLTEST="`which install`"
 fi
fi

if test -z "$MAKE" ; then
    if test -n "$OS" && test "$OS" = "MorphOS"; then
	MAKE="make"
    else
	MAKE="`which gmake`"
	if test ! -x "$MAKE"; then
	    MAKE="`which make`"
	fi
	if test ! -x "$MAKE"; then
	    echo FATAL: cannot find make
	    exit 1
	fi
    fi
fi

if test "$user" = "no"; then
    # global installation
    if test -z "$prefix"; then
	prefix="/usr/local"
    fi
else
    # user installation
    if test -z "$prefix"; then
	prefix="$HOME"
    fi
    PYTHON_SETUP_ARGS="--user"
fi

uadedatadir="$prefix/share/uade"
uadecoredir="$prefix/lib/uade"
if test -z "$bindir"; then
    bindir="$prefix/bin"
fi
if test -z "$includedir" ; then
    includedir="$prefix/include"
fi
if test -z "$libdir" ; then
    libdir="$prefix/lib"
fi
if test -z "$mandir"; then
    mandir="$prefix/share/man/man1"
fi
if test -z "$sharedir" ; then
    sharedir="$prefix/share"
fi

$NATIVECC --version 2>/dev/null >/dev/null
if test "$?" != "0"; then
    echo Native CC "$NATIVECC" not found, please install a C compiler
    exit 1
fi

$TARGETCC --version 2>/dev/null >/dev/null
if test "$?" != "0"; then
    echo Target CC "$TARGETCC" not found, please install a C compiler
    exit 1
fi

VASM=$(which vasm.vasmm68k-mot)
if [[ -n ${VASM} ]] ; then
    usescore="yes"
fi

AOFLAGS=""
AOLIBS="-lao"
if test -n "$PKG_CONFIG" ; then
    AOFLAGS=$($PKG_CONFIG --cflags ao)
    if test "$?" != "0"; then
	if test "$useuade123" = "yes" ; then
	    echo ""
	    echo "Can not compile uade123. Please install libao (including development kit)."
	    echo ""
	    useuade123="no"
	fi
    fi
    AOLIBS=$($PKG_CONFIG --libs ao)
fi

pkgconfigdir="$prefix/lib/pkgconfig"
rm -f libuade.pc
if test -n "$PKG_CONFIG" ; then
    installuadepcrule=""
    if test "$useuade123" = "no" ; then
	pkgrequirements=""
    fi
    userliblinkoption=""
    if test "$user" = "yes" ; then
       userliblinkoption="-Wl,-rpath,$libdir"
    fi
    cat > libuade.pc <<EOF
libdir=$libdir
includedir=$includedir
uadecore=$uadecoredir/$UADECORENAME
data_directory=$uadedatadir
ipc_protocol_version=$IPC_PROTOCOL_VERSION

Name: UADE (Unix Amiga Delitracker Emulator)
Description: A music player for Amiga music formats
Version: $VERSION
Requires:

Libs: -L${libdir} $userliblinkoption -luade
Cflags: -I${includedir}

EOF
fi

if test "$useuadefs" = "yes" ; then
    useuadefs="no"
    if test -n "$PKG_CONFIG" ; then
	if test -n "$($PKG_CONFIG fuse --libs 2>/dev/null)" ; then
	    useuadefs="yes"
	fi
    fi
fi

OSSUPPORTC="src/frontends/common/ossupport.c"
OSSUPPORTH="src/frontends/include/uade/ossupport.h"

# Target is UNIX.
cat > "$OSSUPPORTC" <<EOF
#include <uade/ossupport.h>

EOF
cat src/frontends/common/unixsupport.c >> "$OSSUPPORTC"

cat > "$OSSUPPORTH" <<EOF
#ifndef _UADE_OSSUPPORT_H_
#define _UADE_OSSUPPORT_H_

#include <uade/unixsupport.h>

EOF
cd compat
$TARGETCC $ARCHFLAGS $ARCHLIBS -o memmemtest memmemtest.c 2>/dev/null
if test "$?" != "0" ; then
    cat memmemrep.h >> "../$OSSUPPORTH"
    cat memmemrep.c >> "../$OSSUPPORTC"
    echo "Using memmem() replacement"
fi

$TARGETCC $ARCHFLAGS $ARCHLIBS -o strltest strltest.c 2>/dev/null
if test -e "strltest" ; then
    echo "#include <string.h>" >> "../$OSSUPPORTH"
else
    cat strlrep.c >> "../$OSSUPPORTC"
    cat strlrep.h >> "../$OSSUPPORTH"
    echo "Using strlcpy/cat() replacements"
fi

$TARGETCC $ARCHFLAGS $ARCHLIBS -o canontest canontest.c 2>/dev/null
if test ! -e "canontest" ; then
    cat canonrep.c >> "../$OSSUPPORTC"
    cat canonrep.h >> "../$OSSUPPORTH"
    echo "Using canonical_file_name() replacement"
fi

echo "#endif" >> "../$OSSUPPORTH"

csfile="../src/frontends/include/uade/compilersupport.h"
echo "#ifndef _UADE_COMPILER_SUPPORT_H_" > "$csfile"
echo "#define _UADE_COMPILER_SUPPORT_H_" >> "$csfile"
$TARGETCC $ARCHFLAGS $ARCHLIBS -o unlikelytest unlikelytest.c 2>/dev/null
if test "$?" = "0" ; then
    cat >> "$csfile" <<EOF
#define likely(x)	__builtin_expect(!!(x), 1)
#define unlikely(x)	__builtin_expect(!!(x), 0)
EOF
else
    cat >> "$csfile" <<EOF
#define likely(x) (!!(x))
#define unlikely(x) (!!(x))
EOF
fi
echo "#endif" >> "$csfile"
cd ..

conffile="src/frontends/include/uade/options.h"
conffiletag="_UADE_OPTIONS_H_"
cat > "$conffile" <<EOF
#ifndef $conffiletag
#define $conffiletag
EOF

if test "$user" = "yes" ; then
    echo "#define UADE_CONFIG_USER_MODE (1)" >> "$conffile"
else
    echo "#define UADE_CONFIG_USER_MODE (0)" >> "$conffile"
fi

echo "#define UADE_CONFIG_BASE_DIR \"$uadedatadir\"" >> "$conffile"

echo "#define UADE_CONFIG_UADE_CORE \"$uadecoredir/$UADECORENAME\"" >> "$conffile"
test -c /dev/urandom && echo "#define UADE_CONFIG_HAVE_URANDOM" >> "$conffile"

echo "#define UADE_VERSION \"$VERSION\"" >> "$conffile"

test "$OS" = "Cygwin" && echo "#define UADE_HAVE_CYGWIN" >> "$conffile"

test "$textscope" = "yes" && echo "#define UADE_CONFIG_TEXT_SCOPE" >> "$conffile"
echo "#endif /* $conffiletag */" >> "$conffile"

find_lib() {
    libname="$1"
    for d in "$bencodetoolsprefix" "$prefix" "$HOME" "/usr/local" "/usr" ; do
	if test -z "$d" ; then continue ; fi
	if test -e "$d/lib/$libname" ; then
	    echo "$d"
	    return
	fi
    done
}

LIBBENCODETOOLSNAME="libbencodetools.$SHAREDSUFFIX"

if test -z "$bencodetoolsprefix" ; then
    bencodetoolsprefix=$(find_lib "$LIBBENCODETOOLSNAME")
    if test -z "$bencodetoolsprefix" ; then
	echo
	echo "Can not find libbencodetools. You can use --bencode-tools-prefix to set bencode-tool's base directory. e.g. --bencode-tools-prefix=/foo, where /foo/lib/$LIBBENCODETOOLSNAME exists."
	echo
	echo "You may need to obtain bencode-tools from"
	echo
	echo "    http://zakalwe.fi/~shd/foss/bencode-tools/"
	echo
	echo "Or directly clone the source with:"
	echo
	echo "    git clone https://gitlab.com/heikkiorsila/bencodetools.git"
	echo
	exit 1
    fi
fi    

BENCODETOOLSFLAGS=""
if test "$bencodetoolsprefix" != "/usr" ; then
    BENCODETOOLSFLAGS="-I$bencodetoolsprefix/include"
    ARCHLIBS="$ARCHLIBS -L$bencodetoolsprefix/lib -Wl,-rpath,$bencodetoolsprefix/lib"
fi

echo ""
echo "UADE and frontends is installed to      : $bindir"
echo "Data directory                          : $uadedatadir"
echo "Uadecore directory                      : $uadecoredir"
echo "Man (documentation) directory           : $mandir"
echo "Installer                               : $INSTALLTEST"
echo "Make                                    : $MAKE"
if test "$TARGETCC" != "$NATIVECC" ; then
    echo "Native CC                               : $NATIVECC"
fi
echo "Target CC                               : $TARGETCC"
echo "libuade                                 : $uselibuade"
echo "uadecore                                : $useuadecore"
echo "uade123                                 : $useuade123"
echo "uadefs                                  : $useuadefs"
echo "write audio                             : $usewriteaudio"
echo "Text scope support                      : $textscope"
echo "bencode-tools prefix                    : $bencodetoolsprefix"
echo "vasm (to compile score)                 : ${VASM}"
echo

libuaderule=""
uadecorerule=""
uade123rule=""
uadefsrule=""
scorerule=""
writeaudiorule=""

if test "$uselibuade" = "yes" ; then
    libuaderule="libuade"
fi
if test "$useuadecore" = "yes" ; then
    uadecorerule="uadecore"
fi
if test "$useuade123" = "yes" ; then
    uade123rule="uade123"
fi
if test "$useuadefs" = "yes" ; then
    uadefsrule="uadefs"
fi
if test "$usescore" = "yes" ; then
    scorerule="score"
fi
if test "$usewriteaudio" = "yes" ; then
    writeaudiorule="writeaudio"
fi

compilerules="uadesimple"
installrules=""
for component in $libuaderule $uadecorerule $uade123rule $uadefsrule $scorerule $writeaudiorule ; do
    compilerules="$compilerules $component"
    installrules="$installrules $component""install"
done

replace_with_sed() {
    sed -e "s|{ARCHFLAGS}|$ARCHFLAGS|g" \
	-e "s|{ARCHLIBS}|$ARCHLIBS|g" \
	-e "s|{AOFLAGS}|$AOFLAGS|g" \
	-e "s|{AOLIBS}|$AOLIBS|g" \
	-e "s|{AR}|$TARGETAR|g" \
	-e "s|{BENCODETOOLSFLAGS}|$BENCODETOOLSFLAGS|g" \
	-e "s|{CC}|$TARGETCC|g" \
	-e "s|{OBJCOPY}|$TARGETOBJCOPY|g" \
	-e "s|{NATIVECC}|$NATIVECC|g" \
	-e "s|{SOUNDSOURCE}|$SOUNDSOURCE|g" \
	-e "s|{SOUNDHEADER}|$SOUNDHEADER|g" \
	-e "s|{DEBUGFLAGS}|$debug_flags|g" \
	-e "s|{SHAREDFLAG}|$SHAREDFLAG|g" \
	-e "s|{SHAREDNAMEFLAG}|$SHAREDNAMEFLAG|g" \
	-e "s|{SHAREDLIBRARYFLAGS}|$SHAREDLIBRARYFLAGS|g" \
	-e "s|{SHAREDSUFFIX}|$SHAREDSUFFIX|g" \
	-e "s|{VERSION}|$VERSION|g" \
	-e "s|{MAKE}|$MAKE|g" \
	-e "s|{DATADIR}|$uadedatadir|g" \
	-e "s|{BINDIR}|$bindir|g" \
	-e "s|{MANDIR}|$mandir|g" \
	-e "s|{INCLUDEDIR}|$includedir|g" \
	-e "s|{LIBDIR}|$libdir|g" \
	-e "s|{UADECOREDIR}|$uadecoredir|g" \
	-e "s|{PACKAGEPREFIX}|$packageprefix|g" \
	-e "s|{COMPILE_RULES}|$compilerules|g" \
	-e "s|{INSTALL_RULES}|$installrules|g" \
	-e "s|{UADECORENAME}|$UADECORENAME|g" \
	-e "s|{UADE123NAME}|$UADE123NAME|g" \
	-e "s|{PKGCONFIGDIR}|$pkgconfigdir|g" \
	-e "s|{PYTHON_SETUP_ARGS}|${PYTHON_SETUP_ARGS}|g" \
	-e "s|{PYTHON_INTERPRETER}|${PYTHON_INTERPRETER}|g" \
	"$@"
}

for file in Makefile.in src/Makefile.in src/frontends/*/Makefile.in src/frontends/mod2ogg/mod2ogg2.sh.in write_audio/Makefile.in ; do
    dst="`echo $file |sed -e "s|\.in||"`"
    replace_with_sed "$file" > "$dst"
done

cat >python/uade/uade_config.py <<EOF
WRITE_AUDIO_ACCELERATOR = '${uadecoredir}/write_audio'
EOF

# Make mod2ogg script executable
chmod u+x src/frontends/mod2ogg/mod2ogg2.sh

cp uade.conf.in uade.conf
if test "$n900" = "yes" ; then
    cat >> uade.conf <<EOF

# N900 specific options added by configure script

panning 1
frequency 22050
EOF
fi
