#!/usr/bin/env bash

init_dirs()
{
	[[ -z "$moz_plugin_path" && ! -z "$libdir" ]] && moz_plugin_path="$libdir/mozilla/plugins"
	[[ -z "$moz_plugin_path" ]] && moz_plugin_path="/usr/lib/mozilla/plugins"
	[[ -z "$bindir" ]] && bindir="$1/bin"
	[[ -z "$datadir" ]] && datadir="$1/share"
	[[ -z "$libdir" ]] && libdir="$1/lib"
	[[ -z "$mandir" ]] && mandir="$1/share/man"
}

resolvepath()
{
	if [ ! -z "$1" ]; then
		local path=$(echo "$1/" | sed -e "s|\${prefix}|$prefix|g")
		if [ "${path:0:1}" != "/" ]; then
			path="$(pwd)/$path"
		fi
		local oldpath="$path"
		while true; do
			path=$(echo "$path" | sed -e 's!/\.\{0,1\}/!/!')
			if [ "$path" == "$oldpath" ]; then break; fi
			oldpath="$path"
		done
		while true; do
			path=$(echo "$path" | sed -e 's!/\([^/]\{1,\}\)/\.\./!/!')
			if [ "$path" == "$oldpath" ]; then break; fi
			oldpath="$path"
		done
		if [ "$path" != "/" ] && [ "${path: -1}" == "/" ]; then
			path="${path%/}"
		fi
		echo "$path"
	fi
	return 0
}

usage()
{
	echo ""
	echo "Usage: ./configure [--prefix=PREFIX] [--bindir=PATH] [--datadir=PATH]"
	echo "                   [--libdir=PATH] [--mandir=PATH] [--bash-interp=PATH]"
	echo "                   [--moz-plugin-path=PATH] [--gcc-runtime-dlls=PATH]"
	echo "                   [--gpg-exec=PATH] [--so-mode=OCTAL] [--no-gpu-accel]"
	echo "                   [--show-installation-dialogs] [--debug] [--cxx=COMPILER]"
	echo "                   [--cxxflags=FLAGS] [--mingw-cxxflags=FLAGS]"
	echo ""
	echo " prebuilt options: [--git-commit=TAG/SHA1] [--downloader=CMDLINE]"
	echo ""
	echo " win32 options:    [--win32-prebuilt] [--win32-cxx=COMPILER]"
	echo "                   [--win32-flags=FLAGS] [--win32-static]"
	echo "                   [--wine-path=PATH]"
	echo ""
	echo " win64 options:    [--with-win64]"
	echo "                   [--win64-prebuilt] [--win64-cxx=COMPILER]"
	echo "                   [--win64-flags=FLAGS] [--win64-static]"
	echo "                   [--wine64-path=PATH]"
	echo ""
}

# Default configuration
version="unknown"
prefix="/usr/local"
bindir=""
datadir=""
libdir=""
mandir=""
bash_interp="$(which bash)"
if which gpg &> /dev/null; then
	gpg_exec="$(which gpg)"
else
	gpg_exec="/usr/bin/gpg"
fi
moz_plugin_path=""
gcc_runtime_dlls=""
so_mode="0644"
no_gpu_accel="false"
quietinstallation="true"
debug="false"

cxx=""
cxxflags="$CXXFLAGS"
mingw_cxxflags="$(echo "$CXXFLAGS" | \
	sed -e 's!-fstack-protector\(.[a-zA-Z0-9]*\)! !g' \
	-e 's!-m\([0-9]\|arch\|float-abi\|fpu\|tune\)[=]*\([a-zA-Z0-9-]*\)! !g' \
	-e 's![ \t]\+! !g' -e 's!\(^[ \t]*\|[ \t]*$\)!!g')"

git_commit=""
downloader=""

win32_cxx=""
win32_flags="-m32"
win32_static=0
wine_path="/opt/wine-compholio/bin/wine"

with_win64="false"
win64_cxx=""
win64_flags="-m64"
win64_static=0
wine64_path=""

while [[ $# > 0 ]] ; do
	CMD="$1"; shift
	case "$CMD" in
		--prefix=*)
			prefix="${CMD#*=}"
			;;
		--prefix)
			prefix="$1"; shift
			;;

		--bindir=*)
			bindir="${CMD#*=}"
			;;
		--bindir)
			bindir="$1"; shift
			;;

		--datadir=*)
			datadir="${CMD#*=}"
			;;
		--datadir)
			datadir="$1"; shift
			;;

		--libdir=*)
			libdir="${CMD#*=}"
			;;
		--libdir)
			libdir="$1"; shift
			;;

		--mandir=*)
			mandir="${CMD#*=}"
			;;
		--mandir)
			mandir="$1"; shift
			;;

		--bash-interp=*)
			bash_interp="${CMD#*=}"
			;;
		--bash-interp)
			bash_interp="$1"; shift
			;;

		--gpg-exec=*)
			gpg_exec="${CMD#*=}"
			;;
		--gpg-exec)
			gpg_exec="$1"; shift
			;;

		--moz-plugin-path=*)
			moz_plugin_path="${CMD#*=}"
			;;
		--moz-plugin-path)
			moz_plugin_path="$1"; shift
			;;

		--gcc-runtime-dlls=*)
			gcc_runtime_dlls="${CMD#*=}"
			;;
		--gcc-runtime-dlls)
			gcc_runtime_dlls="$1"; shift
			;;

		--so-mode=*)
			so_mode="${CMD#*=}"
			;;
		--so-mode)
			so_mode="$1"; shift
			;;

		--no-gpu-accel)
			no_gpu_accel="true"
			;;

		--show-installation-dialogs)
			quietinstallation="false"
			;;

		--debug)
			debug="true"
			;;

		--cxx=*)
			cxx="${CMD#*=}"
			;;
		--cxx)
			cxx="$1"; shift
			;;

		--cxxflags=*)
			cxxflags="${CMD#*=}"
			;;
		--cxxflags)
			cxxflags="$1"; shift
			;;

		--mingw-cxxflags=*)
			mingw_cxxflags="${CMD#*=}"
			;;
		--mingw-cxxflags)
			mingw_cxxflags="$1"; shift
			;;

		--git-commit=*)
			git_commit="${CMD#*=}"
			;;
		--git-commit)
			git_commit="$1"; shift
			;;

		--downloader=*)
			downloader="${CMD#*=}"
			;;
		--downloader)
			downloader="$1"; shift
			;;

		--win32-prebuilt)
			win32_cxx="prebuilt"
			;;
		--win32-cxx=*)
			win32_cxx="${CMD#*=}"
			;;
		--win32-cxx)
			win32_cxx="$1"; shift
			;;

		--win32-flags=*)
			win32_flags="$win32_flags ${CMD#*=}"
			;;
		--win32-flags)
			win32_flags="$win32_flags $1"; shift
			;;
		--win32-static)
			win32_static=1
			;;

		--wine-path=*)
			wine_path="${CMD#*=}"
			;;
		--wine-path)
			wine_path="$1"; shift
			;;

		--with-win64)
			with_win64="true"
			;;

		--win64-prebuilt)
			win64_cxx="prebuilt"
			;;
		--win64-cxx=*)
			win64_cxx="${CMD#*=}"
			;;
		--win64-cxx)
			win64_cxx="$1"; shift
			;;

		--win64-flags=*)
			win64_flags="$win64_flags ${CMD#*=}"
			;;
		--win64-flags)
			win64_flags="$win64_flags $1"; shift
			;;
		--win64-static)
			win64_static=1
			;;

		--wine64-path=*)
			wine64_path="${CMD#*=}"
			;;
		--wine64-path)
			wine64_path="$1"; shift
			;;

		--help)
			usage
			exit
			;;
		*)
			echo "WARNING: Unknown argument $CMD." >&2
			;;
	esac
done

# Determine current git commit
if [ -z "$git_commit" ] && [ -d "./.git" ] && command -v git >/dev/null 2>&1; then
	git_commit="$(git log --pretty=format:'%H' -n 1)"
fi

# Get the version number
changelog="$(head -n1 ./debian/changelog)"
if [[ "$changelog" =~ \((.*)\)\ (UNRELEASED)? ]]; then
	version="${BASH_REMATCH[1]}"
	if [ "${BASH_REMATCH[2]}" == "UNRELEASED" ]; then
		version="$version-daily"
	elif [ -z "$git_commit" ]; then
		git_commit="v$version"
	fi
fi

# Intialize other dirs, if not already set by switches
init_dirs "$prefix"

# Try to autodetect linux compiler
if [ -z "$cxx" ]; then
        if command -v g++ >/dev/null 2>&1; then
                cxx="g++"
        elif command -v clang++ > /dev/null 2>&1; then
                cxx="clang++"
        else
                echo "ERROR: No cxx compiler found. Please use --cxx to specify one."
                exit 1
        fi
fi

# In case of using prebuilt windows binaries we need the git_commit variable, and a downloader if the files don't exist yet
if [ "$win32_cxx" == "prebuilt" ] || [ "$win64_cxx" == "prebuilt" ]; then
	if [ -z "$git_commit" ]; then
		echo "ERROR: Unable to determine git commit! Please use --git-commit to specify the tag/sha1 of this version."
		exit 1
	fi

	if [ ! -f "./pluginloader-$git_commit.tar.gz" ] || [ ! -f "./pluginloader-$git_commit.tar.gz.sig" ]; then
		if [ -z "$downloader" ]; then
			if command -v wget >/dev/null 2>&1; then
				downloader="wget -O"
			elif command -v fetch >/dev/null 2>&1; then
				downloader="fetch -o"
			else
				echo "ERROR: Could neither find wget nor fetch! Please use --downloader to specify a program."
				exit 1
			fi
		fi
	fi
fi

# Try to autodetect windows 32-bit compiler
if [ -z "$win32_cxx" ]; then
	if command -v i686-w64-mingw32-g++ >/dev/null 2>&1; then
		win32_cxx="i686-w64-mingw32-g++"
		win32_static=1

	elif command -v mingw32-g++ > /dev/null 2>&1; then
		win32_cxx="mingw32-g++"
		win32_flags="$win32_flags -DMINGW32_FALLBACK"
		win32_static=1

	elif command -v i686-pc-mingw32-g++ > /dev/null 2>&1; then
		win32_cxx="i686-pc-mingw32-g++"
		win32_flags="$win32_flags -DMINGW32_FALLBACK"
		win32_static=1

	elif command -v i586-mingw32msvc-c++ > /dev/null 2>&1; then
		win32_cxx="i586-mingw32msvc-c++"
		win32_flags="$win32_flags -DMINGW32_FALLBACK"
		win32_static=1

	elif command -v wineg++ > /dev/null 2>&1; then
		win32_cxx="wineg++"
		win32_static=0

	else
		echo "ERROR: No mingw32-g++ compiler found. Please use --win32-cxx to specify one."
		exit 1
	fi
fi

# # Try to autodetect windows 64-bit compiler (if required)
if [ "$with_win64" == "true" ] && [ -z "$win64_cxx" ]; then
	if command -v x86_64-w64-mingw32-g++ >/dev/null 2>&1; then
		win64_cxx="x86_64-w64-mingw32-g++"
		win64_static=1

	else
		echo "ERROR: No mingw64-g++ compiler found. Please use --win64-cxx to specify one."
		exit 1
	fi
fi

if [ "$win32_static" -ne 0 ]; then
	win32_flags="$win32_flags -static-libgcc -static-libstdc++ -static"
fi

if [ "$win64_static" -ne 0 ]; then
	win64_flags="$win64_flags -static-libgcc -static-libstdc++ -static"
fi

if [ ! -z "$mingw_cxxflags" ]; then
	win32_flags="$mingw_cxxflags $win32_flags"
	win64_flags="$mingw_cxxflags $win64_flags"
fi

if [ "$with_win64" == "true" ] && [ -z "$wine64_path" ]; then
	wine64_path="$wine_path/../wine64"
fi

# Normalize the paths
prefix=$(resolvepath "$prefix")
bindir=$(resolvepath "$bindir")
datadir=$(resolvepath "$datadir")
libdir=$(resolvepath "$libdir")
mandir=$(resolvepath "$mandir")
bash_interp=$(resolvepath "$bash_interp")
gpg_exec=$(resolvepath "$gpg_exec")
moz_plugin_path=$(resolvepath "$moz_plugin_path")
gcc_runtime_dlls=$(resolvepath "$gcc_runtime_dlls")
wine_path=$(resolvepath "$wine_path")
wine64_path=$(resolvepath "$wine64_path")

(
	echo "#"
	echo "# This file is automatically created by ./configure, DO NOT EDIT!"
	echo "#"
	echo ""
	echo "# General"
	echo "version=$version"
	echo "prefix=$prefix"
	echo "bindir=$bindir"
	echo "datadir=$datadir"
	echo "libdir=$libdir"
	echo "mandir=$mandir"
	echo "bash_interp=$bash_interp"
	echo "gpg_exec=$gpg_exec"
	echo "moz_plugin_path=$moz_plugin_path"
	echo "gcc_runtime_dlls=$gcc_runtime_dlls"
	echo "so_mode=$so_mode"
	echo "no_gpu_accel=$no_gpu_accel"
	echo "quietinstallation=$quietinstallation"
	echo "debug=$debug"
	echo "cxx=$cxx"
	echo "cxxflags=$cxxflags"
	echo ""
	echo "# Prebuilt"
	echo "git_commit=$git_commit"
	echo "downloader=$downloader"
	echo ""
	echo "# Win32"
	echo "win32_cxx=$win32_cxx"
	echo "win32_flags=$win32_flags"
	echo "wine_path=$wine_path"
	echo ""
	echo "# Win64"
	echo "with_win64=$with_win64"
	echo "win64_cxx=$win64_cxx"
	echo "win64_flags=$win64_flags"
	echo "wine64_path=$wine64_path"
) > config.make

echo "Configuration Summary"
echo "---------------------"
echo ""
echo "Pipelight has been configured with:"
while IFS="=" read key val; do
	if [ -z "$key" ]; then
		echo ""
	elif [ "${key:0:1}" != "#" ]; then
		printf "%20s = %s\n" "$(echo "$key" | sed -e 's|_|-|g')" "$val"
	fi
done < config.make 
echo ""
echo "IMPORTANT: Please ensure you have XATTR support enabled for both wine and"
echo "           your file system (required to watch DRM protected content)!"
echo ""

exit 0
