#!/bin/bash

# Copyright (C) 2007 Robin Dunn, Kevin Ollivier  All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
#
# Driver for the wxWebKit build process.

set -o errexit
#set -o xtrace

#----------------------------------------------------------------------
# Set up the environment

scriptDir="$(cd $(dirname $0);pwd)"
WK_ROOT=$scriptDir/../..
WK_ROOTDIR="$WK_ROOT"

cd $scriptDir

if [ -z $WEBKITOUTPUTDIR ]; then
    WEBKITOUTPUTDIR=`cd $WK_ROOT/WebKitTools/Scripts; perl -e "use webkitdirs; print productDir()"`
fi

WKWINLIBS=WebKitLibraries/win
WINDEPS="         $WKWINLIBS/lib/pthreadVC2.dll"
WINDEPS="$WINDEPS $WKWINLIBS/bin/icuuc40.dll $WKWINLIBS/bin/icudt40.dll $WKWINLIBS/bin/icuin40.dll"
WINDEPS="$WINDEPS $WKWINLIBS/bin/libcurl.dll $WKWINLIBS/bin/libeay32.dll $WKWINLIBS/bin/ssleay32.dll $WKWINLIBS/bin/zlib1.dll"
WINDEPS="$WINDEPS $WKWINLIBS/lib/sqlite3.dll"
WINDEPS="$WINDEPS $WKWINLIBS/bin/libxml2.dll $WKWINLIBS/bin/libxslt.dll" 
WINDEPS="$WINDEPS $WKWINLIBS/bin/iconv.dll" 

# TODO: check that we are running from the root of the source tree...

# cygpath will bork if the dir doesn't exist...
mkdir -p $WEBKITOUTPUTDIR

if [ $OSTYPE == cygwin ]; then
    EXE=.exe
    WK_ROOTDIR=`cygpath -d $WK_ROOT`
    WEBKITOUTPUTDIR=`cygpath -d $WEBKITOUTPUTDIR`
    export WEBKITOUTPUTDIR
    if [ -z $WXWIN ]; then
        echo "Error, you must set WXWIN to your wxWidgets root directory."
        exit 1
    fi
    if [ -z $WX_PREFIX ]; then
        WX_PREFIX=$WXWIN
    fi
    if [ -z $BAKEFILE_PATHS ]; then
        export BAKEFILE_PATHS=$WXWIN/build/bakefiles/wxpresets
    fi
    LINKER=`which link`
    if [ "$LINKER" = "/usr/bin/link" ]; then
        echo "WARNING: wxWebKit builds using MSVC on Windows, but it looks like"
        echo "you have the GCC linker on your path. If /usr/bin/link does NOT point"
        echo "to the MSVC linker, you need to move it or change your path to pick up"
        echo "Microsoft's link.exe program first."
    fi

else
    export WEBKITOUTPUTDIR
    WX_PREFIX=`wx-config --prefix`
    if [ ! -d "$WX_PREFIX" ]; then
        echo "ERROR: Cannot find your wxWidgets installation."
        echo "Make sure wx-config is on your PATH and points to a valid wxWidgets installation."
        exit 1
    fi
    
    CONFIG=`wx-config --selected-config`
    if [ "${CONFIG:0:4}" != "gtk2" -a "${CONFIG:0:3}" != "mac" ]; then
        echo "WARNING: This configuration '$CONFIG' is not currently supported by wxWebKit. Please use the win, mac, or gtk2 port depending on your platform."
    fi
    
    if [ ! -d "$WX_PREFIX/share/bakefile" ]; then
        echo "ERROR: wxWidgets installation does not have wxpresets."
        echo "wx-config is pointing to an installation that does not have Bakefile presets installed. Run `wx-config --version` to ensure your wxWidgets is of version 2.8+."
        exit 1
    fi    
    
    if [ -z $BAKEFILE_PATHS ]; then
        export BAKEFILE_PATHS=$WX_PREFIX/share/bakefile
    fi
fi

# after all that, make sure that BAKEFILE_PATHS was either set
# previously, or by the code above
if [ -z $BAKEFILE_PATHS ]; then
    echo "Error, you must set BAKEFILE_PATHS to the directory containing wxpresets."
    exit 1
fi

#----------------------------------------------------------------------
# process command line args
build_type_set=0

do_bake=0
do_prep=0
do_extras=0
do_build=0
do_clean=0
do_install=0
use_wxgc=0
debug=1
wxdebug=0
wxpython=0
make_args=''
other_args=''

for flag in $*; do
    case $flag in
    bake)   do_bake=1                                      ;;
    prep)   do_prep=1                                      ;;
    build)  do_build=1                                     ;;
    all)    do_extras=1; do_bake=1; do_prep=1; do_build=1  ;;
    clean)  other_args=clean; do_clean=1                   ;;
    wxgc)   use_wxgc=1                                     ;;
    wxdebug) wxdebug=1                                     ;;
    wxpython) wxpython=1                                   ;;
    wxpython-install) wxpython_install=1                   ;;
    *)      export $flag ;; #other_args='$other_args "$flag"'               ;;
    esac
done


#----------------------------------------------------------------------

# if no arguments were passed, do a full build.
if [ $do_bake == 0 -a $do_prep == 0 -a $do_build == 0 -a $do_clean == 0 ]; then
    do_bake=1; do_prep=1; do_build=1
fi

if [ -f $WK_ROOT/WebKitBuild/Configuration ]; then
    BUILD_TYPE=`cat $WK_ROOT/WebKitBuild/Configuration`
    echo "Configuration is: $BUILD_TYPE"
    
    if [ $BUILD_TYPE == "Release" ]; then
        debug=0
    fi
    if [ $BUILD_TYPE == "Debug" ]; then
        debug=1
    fi
    
fi

function do_make {
    dir=$1
    cxxflags=$2
    olddir=$PWD
    shift
    shift
    # NOTE: If we try to do make clean after the Bakefiles were cleaned out, or before they were
    # first generated, we will get errors about missing files, so we need to check that the
    # makefile exists before running it. 
    if [ $OSTYPE == cygwin ]; then
        cd $dir
        if [ -f makefile.vc ]; then
            nmake -f makefile.vc CXXFLAGS="$cxxflags" $@
        fi
        cd $olddir
    else
        if [ -f $dir/GNUmakefile ]; then
            make -C $dir -f GNUmakefile $MAKE_ARGS CXXFLAGS="$cxxflags -fvisibility=hidden -fvisibility-inlines-hidden" $@
        fi
    fi
    if [ $? != 0 ]; then
        exit $? 
    fi
}

# output the first parameter that is a dir and exists
function find_existing_dir {
    for arg in $*; do
        tester=$arg
        if [ $OSTYPE == cygwin ]; then
            tester=`cygpath -u $arg`
        fi
        if [ -d $tester ]; then
            echo $arg
            return
        fi
    done
}


olddir=$PWD

if [ $do_clean != 1 ]; then

    mkdir -p $WEBKITOUTPUTDIR/build

    if [ $do_bake == 1 ]; then
        # bakefile stuff
        cd $WK_ROOT/WebKit/wx
        bakefile_gen
    
        # we need to do this because Bakefile doesn't know which
        # platform it's running on with GNU format, and so it defaults
        # to the standard Unix file endings and linker args.
        if [ "${OSTYPE:0:6}" = "darwin" ]; then    
            sed "s/libjscore.so/libjscore.dylib/" < $WK_ROOT/JavaScriptCore/GNUmakefile > temp
            mv temp $WK_ROOT/JavaScriptCore/GNUmakefile
            
            sed "s/\-shared/\-dynamiclib/" < $WK_ROOT/JavaScriptCore/GNUmakefile > temp
            mv temp $WK_ROOT/JavaScriptCore/GNUmakefile
            
            sed "s/\-shared/\-dynamiclib/" < $WK_ROOT/WebCore/GNUmakefile > temp
            mv temp $WK_ROOT/WebCore/GNUmakefile
            
            sed "s/libwxwebkit.so/libwxwebkit.dylib/" < $WK_ROOT/WebKit/wx/GNUmakefile > temp
            mv temp $WK_ROOT/WebKit/wx/GNUmakefile
            
            sed "s/\-shared/\-dynamiclib/" < $WK_ROOT/WebKit/wx/GNUmakefile > temp
            mv temp $WK_ROOT/WebKit/wx/GNUmakefile
        fi
    fi

    if [ $do_prep == 1 ]; then
        # Other preparation steps
        
        # since the buildbot will wipe the build tree clean sometimes, we need to reinstall
        # the dependencies if they aren't installed.
        if [ "${OSTYPE:0:6}" == "darwin" ]; then
            $WK_ROOT/WebKitTools/wx/install-unix-extras
        fi
        
        
        export CREATE_HASH_TABLE="$WK_ROOT/JavaScriptCore/create_hash_table"
        cd $WK_ROOT/JavaScriptCore
        mkdir -p DerivedSources/JavaScriptCore
        cd DerivedSources/JavaScriptCore
        
        make -f ../../DerivedSources.make JavaScriptCore=../.. BUILT_PRODUCTS_DIR=../.. all FEATURE_DEFINES="ENABLE_DATABASE ENABLE_XSLT ENABLE_JAVASCRIPT_DEBUGGER"
        if [ $? != 0 ]; then
            exit 1
        fi
    
        cd $WK_ROOT/WebCore
        mkdir -p DerivedSources/WebCore
        cd DerivedSources/WebCore
        make -f ../../DerivedSources.make all WebCore=../.. SOURCE_ROOT=../.. FEATURE_DEFINES="ENABLE_DATABASE ENABLE_XSLT ENABLE_JAVASCRIPT_DEBUGGER"
        if [ $? != 0 ]; then
            exit 1
        fi
    fi
fi


if [ $do_build == 1 -o $do_clean == 1 ]; then   
    WXGC_DEFINE=""
    EXTRA_CPPFLAGS=""
    
    if [ "${OSTYPE:0:6}" == "cygwin" ]; then
        PLATFORM_OS="win"
    elif [ "${OSTYPE:0:6}" == "darwin" ]; then
        PLATFORM_OS="mac"
        EXTRA_CPPFLAGS="-DMAC_OS_X_VERSION_MIN_REQUIRED=1040"
        use_wxgc=1
    else
        PLATFORM_OS="linux"
        use_wxgc=1
    fi

    if [ $use_wxgc == 1 ]; then
        WXGC_DEFINE="-DWTF_USE_WXGC=1"
    fi
    WX_EXT=
    if [ "${OSTYPE:0:6}" == "cygwin" -a $wxdebug == 1 ]; then
        WX_EXT=d
    fi
    if [ $wxpython == 1 ]; then
        other_args=WX_PYTHON=1
        WX_EXT=h
        wxdebug=1
    fi

    WINDEPS="$WINDEPS $WXWIN/lib/vc_dll/wxmsw28u${WX_EXT}_core_vc.dll $WXWIN/lib/vc_dll/wxbase28u${WX_EXT}_vc.dll"
    
    do_make $WK_ROOT/JavaScriptCore      "-DBUILDING_WX__=1 $WXGC_DEFINE $EXTRA_CPPFLAGS" WX_DEBUG=$wxdebug DEBUG=$debug WEBKIT_ROOT=$WK_ROOTDIR PLATFORM_OS=$PLATFORM_OS $other_args 

    mkdir -p $WEBKITOUTPUTDIR/JavaScriptCore
    cp -p $WK_ROOT/JavaScriptCore/API/*.h $WEBKITOUTPUTDIR/JavaScriptCore/

    do_make $WK_ROOT/WebCore "-DBUILDING_WX__=1 $WXGC_DEFINE $EXTRA_CPPFLAGS" WX_DEBUG=$wxdebug WEBKIT_ROOT=$WK_ROOTDIR DEBUG=$debug PLATFORM_OS=$PLATFORM_OS $other_args
    do_make $WK_ROOT/WebKit/wx "-DBUILDING_WX__=1 -DWXMAKINGDLL_WEBKIT=1 $WXGC_DEFINE $EXTRA_CPPFLAGS" WX_DEBUG=$wxdebug DEBUG=$debug WEBKIT_ROOT=$WK_ROOTDIR PLATFORM_OS=$PLATFORM_OS $other_args 
    do_make $WK_ROOT/WebKitTools/wx/browser  "-DBUILDING_WX__=1 -DWXUSINGDLL_WEBKIT=1 $WXGC_DEFINE $EXTRA_CPPFLAGS" WX_DEBUG=$wxdebug DEBUG=$debug WEBKIT_ROOT=$WK_ROOTDIR PLATFORM_OS=$PLATFORM_OS $other_args 
    do_make $WK_ROOT/WebKitTools/DumpRenderTree/wx  "-DBUILDING_WX__=1 -DWXUSINGDLL_WEBKIT=1 $WXGC_DEFINE $EXTRA_CPPFLAGS" WX_DEBUG=$wxdebug DEBUG=$debug WEBKIT_ROOT=$WK_ROOTDIR PLATFORM_OS=$PLATFORM_OS $other_args

    if [ $do_clean == 1 ]; then
        rm -rf $WK_ROOT/JavaScriptCore/DerivedSources
        rm -rf $WK_ROOT/WebCore/DerivedSources
        rm -rf $WK_ROOT/WebCore/include/JavaScriptCore
    fi

    if [ $do_build == 1 ]; then 
        if [ "${OSTYPE:0:6}" = "darwin" ]; then
            cd  $WEBKITOUTPUTDIR
            mkdir -p wxBrowser.app/Contents/MacOS
            mkdir -p wxBrowser.app/Contents/Frameworks
            cp wxBrowser wxBrowser.app/Contents/MacOS
            install_name_tool -change libwxwebkit.dylib @executable_path/../Frameworks/libwxwebkit.dylib wxBrowser.app/Contents/MacOS/wxBrowser
            if [ ! -f "$WEBKITOUTPUTDIR/libwxwebkit.dylib" ]; then
                ln -s $WEBKITOUTPUTDIR/libwxwebkit.dylib wxBrowser.app/Contents/Frameworks
            fi
        fi
        
        if [ $wxpython == 1 ]; then
            if [ -z $SWIG ]; then
                SWIG=`which swig`
            fi

            if [ ! -f "$SWIG" ]; then
                echo "ERROR: Cannot find SWIG. Make sure that SWIG 1.3.29 is located on your path.";
                exit 1;
            fi
    
            cd $WK_ROOT/WebKit/wx/bindings/python
            
            SWIG_FLAGS=`python -c "import wx.build.config; import string; print string.join(wx.build.config.swig_args, ' ')"`
            WEBKIT_INCLUDE="-I$WK_ROOT/WebKit/wx"
            if [ "${OSTYPE:0:6}" == "cygwin" ]; then
                WEBKIT_INCLUDE="-I`cygpath -d $WK_ROOT/WebKit/wx`"
            fi
            
            # Determine which include path to use for wxPython's *.i files
            # Options are:
            #    wxPython installed on a posix system
            #    the wxPython win32 devel tarball
            #    a wx source tree from a tarball where wxPython is in the wx dir
            #    a wx source tree from SVN where wxPython is a sibling of the wx dir
            WXPY_INCLUDE=`find_existing_dir \
                $WX_PREFIX/include/wx-2.9/wx/wxPython/i_files \
                $WX_PREFIX/include/wx-2.8/wx/wxPython/i_files \
                $WX_PREFIX/include/wx/wxPython/i_files \
                $WX_PREFIX/wxPython/src \
                $WX_PREFIX/../wxPython/src`
            if [ -z $WXPY_INCLUDE ]; then
                echo "ERROR: Unable to find wxPython's *.i files"
                exit 1
            fi
            
            # Run SWIG
            $SWIG $SWIG_FLAGS -I$WXPY_INCLUDE $WEBKIT_INCLUDE -o webview.cpp webview.i
            cp webview.py $WEBKITOUTPUTDIR/webview.py
                                   
            PY_INCLUDE=`python -c "import sys,distutils.sysconfig; sys.stdout.write(distutils.sysconfig.get_python_inc())"`
            
            if [ "${OSTYPE:0:6}" == "cygwin" ]; then
                PY_LIBDIR=`python -c "import distutils.sysconfig; import sys; sys.stdout.write(distutils.sysconfig.PREFIX)"`
                PY_LIBDIR="$PY_LIBDIR\\Libs"
                PY_LIB=`python -c "import sys; sys.stdout.write('python' + sys.version[:3])"`
                PY_LIB=`python -c "sys.stdout.write('$PY_LIB'.replace('.', ''))"`
            else
                PY_LIB=`python-config --libs`
                PY_LIBDIR=`python-config --ldflags`
            fi
            
            do_make $WK_ROOT/WebKit/wx/bindings/python "-DBUILDING_WX__=1 -DWXUSINGDLL=1 -DWXUSINGDLL_WEBKIT=1 -I$PY_INCLUDE -I$WX_PREFIX/wxPython/include -I$WX_PREFIX/../wxPython/include $WXGC_DEFINE $EXTRA_CPPFLAGS" \
                WX_DEBUG=$wxdebug DEBUG=$debug WEBKIT_ROOT=$WK_ROOTDIR PLATFORM_OS=$PLATFORM_OS PYTHON_LIB=$PY_LIB PYTHON_LIBDIR=$PY_LIBDIR $other_args
            if [ "${OSTYPE:0:6}" == "cygwin" ]; then
                if [ -f $WEBKITOUTPUTDIR/_webview.pyd -a -f $WEBKITOUTPUTDIR/_webview.dll ]; then
                    rm $WEBKITOUTPUTDIR/_webview.pyd
                    mv $WEBKITOUTPUTDIR/_webview.dll $WEBKITOUTPUTDIR/_webview.pyd
                fi
            fi
        fi
        
    
        if [ "$OSTYPE" == "cygwin" ]; then
            echo "Copying necessary DLLs to run test and sample applications..."
            cd $WK_ROOT
            cp $WINDEPS `cygpath -u $WEBKITOUTPUTDIR`
            chmod +x `cygpath -u $WEBKITOUTPUTDIR/`*.dll
	    if [ -e `cygpath -u $WEBKITOUTPUTDIR/_webview.dll` ]; then
		mv `cygpath -u $WEBKITOUTPUTDIR/_webview.dll` `cygpath -u $WEBKITOUTPUTDIR/_webview.pyd`
	    fi
        fi
        
        BROWSERAPP="wxBrowser"
        
        if [ "${OSTYPE:0:6}" == "darwin" ]; then
            BROWSERAPP="wxBrowser.app/Contents/MacOS/wxBrowser"
        fi
    
        echo ""
        echo ""
        echo "--- BUILD COMPLETE ---"
        echo ""
        echo "Next steps:"
        echo ""
        echo "-- Run '$WK_ROOT/WebKitTools/Scripts/run-javascriptcore-tests --wx' to ensure JSCore tests pass."
        echo ""
        echo "-- Run $WEBKITOUTPUTDIR/$BROWSERAPP to test your wxWebKit build."
        echo ""
        echo ""
    fi
fi

if [ $do_clean == 1 ]; then
    cd $WK_ROOT/WebKit/wx
    bakefile_gen --clean
fi

cd $olddir