#!/bin/sh
#
# Copyright (C) 2000-2022 Kern Sibbald
# License: BSD 2-Clause; see file LICENSE-FOSS
#
#  This file may help you build the dependency packages that
#  are needed to cross compile the Win64 bit version of the Bacula
#  File daemon.  This file is provided as is, and we don't guarantee
#  that it will work. We run it only on Ubuntu Hardy.  Trying to use
#  it on any other GNU/Linux distro will probably require changes.
#
#  This file is driven by the parameters that are defined in
#    the file External-mingw-w64
#

usage()
{
   echo "usage: $0 [-h] [-C] [<dependency 1>] [<dependency 2>] ..."
   echo "       -h      Displays this usage"
   echo "       -C      Clobbers (overwrites) the source code by "
   echo "               reextracting the archive and reapplying the"
   echo "               patches."
   echo ""
   echo "<dependency N> Optional dependency, If none are given then all"
   echo "               of them will be built."
   echo ""
   echo "Valid dependencies are:"
   grep -v '^#' < External-mingw-w64 | cut -d'|' -f1 | cut -d'_' -f1 | tr A-Z a-z | sort -u | awk '{ print "        " $1 }'
}

CLOBBER_SOURCE=

while getopts "hHC" opt; do
   case ${opt} in
   H|h|\?) usage;exit 1;;
   C)      CLOBBER_SOURCE=true;;
   esac
done

[ ${OPTIND} -gt 1 ] && shift `expr ${OPTIND} - 1`

cwd=`pwd`
cd `dirname $0`
SCRIPT_DIR=`pwd`

cd ../../..
TOP_DIR=`pwd`
TOP_DIR=${DEPKGS:-${TOP_DIR}}

if [ -e ${TOP_DIR}/cross-tools/mingw-w64/bin/x86_64-pc-mingw32-gcc ]
then
   cd ${TOP_DIR}/cross-tools/mingw-w64/bin
   BIN_DIR=`pwd`

elif which x86_64-w64-mingw32-gcc > /dev/null; then
   BIN_DIR=
   BASE=x86_64-w64-mingw32

else
   echo "The GCC cross compiler is not installed."
   echo "You must run build-win64-cross-tools first"
   exit 1
fi

[ ! -e ${TOP_DIR}/depkgs-mingw-w64 ] && mkdir ${TOP_DIR}/depkgs-mingw-w64
cd ${TOP_DIR}/depkgs-mingw-w64
DEPPKG_DIR=`pwd`
DEPKGS_DIR=`pwd`

export PATH=${BIN_DIR}:${PATH}

[ ! -e bin ] && mkdir bin
[ ! -e src ] && mkdir src
[ ! -e include ] && mkdir include
[ ! -e lib ] && mkdir lib

OLD_IFS=${IFS};IFS="|";
while read package url dir mkd; do
   echo "Got package ${package}"
   case ${package} in
   \#*) ;;
   *) eval "URL_${package}=${url};DIR_${package}=${dir};MKD_${package}=${mkd}";;
        esac
done < ${SCRIPT_DIR}/External-mingw-w64
IFS=${OLD_IFS};unset OLD_IFS

get_source()
{
   URL=$1
   SRC_DIR=$2
   MAKE_DIR=$3
   echo "Processing ${URL}"
   ARCHIVE=`basename ${URL}`
   
   case ${ARCHIVE} in
   *.tar.gz)       ARCHIVER="tar xzf";    [ -z "${SRC_DIR}" ] && SRC_DIR=`expr "${ARCHIVE}" : '\(.*\)\.tar\.gz'`;;
   *.tar.bz2)      ARCHIVER="tar xjf";    [ -z "${SRC_DIR}" ] && SRC_DIR=`expr "${ARCHIVE}" : '\(.*\)\.tar\.bz2'`;;
   *.zip)          ARCHIVER="unzip -d .";   [ -z "${SRC_DIR}" ] && SRC_DIR=`expr "${ARCHIVE}" : '\(.*\)\.zip'`;;
   *.exe)          ARCHIVER="";           [ -z "${SRC_DIR}" ] && SRC_DIR=`expr "${ARCHIVE}" : '\(.*\)\.zip'`;;
   *.xz)       ARCHIVER="tar xf";    [ -z "${SRC_DIR}" ] && SRC_DIR=`expr "${ARCHIVE}" : '\(.*\)\.tar\.xz'`;;
   *)              echo Unsupported archive type - $ARCHIVE; exit 1;;
   esac
   
   cd ${DEPPKG_DIR}/src
   
   if [ ! -e "${ARCHIVE}" ]
   then 
      echo Downloading "${URL}"
      if wget --passive-ftp "${URL}"
      then
         :
      else
         echo Unable to download ${ARCHIVE}
         exit 1
      fi
   fi

   [ -z "${ARCHIVER}" ] && return 0

   if [ ! -e "${SRC_DIR}" -o "${CLOBBER_SOURCE}" = "true" ]
   then
      rm -rf ${SRC_DIR}
      echo Extracting ${ARCHIVE}
      if [ "${MAKE_DIR}" = "true" ]
      then
         mkdir ${SRC_DIR}
         cd ${SRC_DIR}
         ${ARCHIVER} ../${ARCHIVE} > ../${ARCHIVE}.log 2>&1
      else
         ${ARCHIVER} ${ARCHIVE} > ${ARCHIVE}.log 2>&1
         cd ${SRC_DIR}
      fi
      return 0
   fi

   cd ${SRC_DIR}
   return 1
}

parse_output()
{
   sed -ne '/\\$/N' -e 's/\\\n//' -e 's/\t\+/ /g' -e 's/ \+/ /g' \
       -e '/ error: /p' \
       -e "s%.*Entering directory[ ]\\+.${DEPPKG_DIR}/\\([^ ]\+\).%Entering \\1%p" \
       -e "s%.*Leaving directory[ ]\\+.${DEPPKG_DIR}/\\([^ ]\+.\).%Leaving \\1%p" \
       -e '/gcc \|g\+\+ \|ar /!d' \
       -e 's/ \(\.\.\/\)\+/ /g' \
       -e 's/.* \([^ ]\+\(\.c\|\.cpp\|\.cc\|\.cxx\)\)\( .*\|\)$/Compiling \1/p' \
       -e 's/.* \([^ ]\+\.s\)\( .*\|\)$/Assembling \1/p' \
       -e 's/.*ar [^ ]\+ \([^ ]\+\)\(\( [^ ]\+\.o\)\+\)/Updating \1 -\2/p' \
       -e 's/.* -o \([^ ]\+\)\( .*\|\)$/Linking \1/p'
}

do_patch()
{
   PATCH_FILE=${SCRIPT_DIR}/patches/$1; shift
   
   if patch -f -p0 "$@" >>patch.log < ${PATCH_FILE}
   then
      :
   else
      echo "Patch failed - Check `pwd`/patch.log" > /dev/tty
      exit 1
   fi
}

do_make()
{
   if make -f "$@" 2>&1
   then
      :
   else
      echo "Make failed - Check `pwd`/make.log" > /dev/tty
      exit 1
   fi | tee -a make.log | parse_output
}

process_zlib()
{
   if get_source "${URL_ZLIB}" "${DIR_ZLIB}" "${MKD_ZLIB}"
   then
      true
   fi
   echo Building zlib
   > make.log
   do_make win32/Makefile.gcc PREFIX=${BASE}-  DESTDIR=${DEPPKG_DIR}/ all
   echo Installing zlib
   do_make win32/Makefile.gcc PREFIX=${BASE}-  DESTDIR=${DEPPKG_DIR}/ LIBRARY_PATH=lib BINARY_PATH=bin INCLUDE_PATH=include SHARED_MODE=1 install
}

process_pcre()
{
   if get_source "${URL_PCRE}" "${DIR_PCRE}" "${MKD_PCRE}"
   then
           echo Patching PCRE
           >patch.log
           do_patch pcre.patch
           echo Configuring PCRE
           ./configure CC_FOR_BUILD=gcc \
                       CXX_FOR_BUILD=g++ \
                       --host=${BASE} \
                       --prefix=${DEPPKG_DIR} \
                       --enable-utf8 \
                       --enable-unicode-properties >make.log 2>&1
   fi
   echo Building PCRE
   do_make Makefile PREFIX=${DEPPKG_DIR} all
   echo Installing PCRE
   do_make Makefile PREFIX=${DEPPKG_DIR} install
}

process_db()
{
   if get_source "${URL_DB}" "${DIR_DB}" "${MKD_DB}"
   then
          echo "No patch needed for this package"
   fi
   cd build_unix
   ../dist/configure --host=${BASE} --enable-mingw --prefix=${DEPPKG_DIR}
   > make.log
   echo Building DB
   do_make Makefile
   echo Installing DB
   do_make Makefile install_setup install_include install_lib
}

process_pthreads()
{
   if get_source "${URL_PTHREADS}" "${DIR_PTHREADS}" "${MKD_PTHREADS}"
   then
      echo "No patch needed for this package"
   fi
   echo Building pthreads
   > make.log
   do_make GNUmakefile CROSS=${BASE}- clean GCE-inlined
   echo Installing pthreads
   rm -rf ${DEPPKG_DIR}/include/pthreads
   mkdir ${DEPPKG_DIR}/include/pthreads
   cp -p *.h ${DEPPKG_DIR}/include/pthreads
   cp -p *.dll ${DEPPKG_DIR}/bin
   cp -p *.a ${DEPPKG_DIR}/lib
}

process_openssl()
{
   if get_source "${URL_OPENSSL}" "${DIR_OPENSSL}" "${MKD_OPENSSL}"
   then
           echo Configuring openssl
           CROSS_COMPILE=${BASE}- ./Configure --prefix=${DEPPKG_DIR} \
                       shared zlib-dynamic \
                       threads \
                       --with-zlib-include=${DEPPKG_DIR}/include \
                       mingw64 > make.log 2>&1
   fi
   echo Patching openssl
   sed -i "s;OPENSSLDIR_dev=C:;OPENSSLDIR_dev=;" Makefile
   sed -i "s;OPENSSLDIR_dir=.*;OPENSSLDIR_dir=${DEPPKG_DIR}/openssl;" Makefile
   echo Building openssl
   do_make Makefile all
   echo Installing openssl
   do_make Makefile -k install_sw install
   cp *.dll ${DEPPKG_DIR}/bin
   mkdir -p ${DEPPKG_DIR}/ssl
   cp -f apps/openssl.cnf ${DEPPKG_DIR}/ssl
}

process_lzo()
{
   if get_source "${URL_LZO}" "${DIR_LZO}" "${MKD_LZO}"
   then
        sed -i s/-lwinmm// configure
   fi
   echo Building lzo
   ./configure --host=${BASE} --prefix=${DEPPKG_DIR}/
   echo Installing lzo
   do_make Makefile -k PREFIX=${DEPPKG_DIR}/ all
   do_make Makefile -k PREFIX=${DEPPKG_DIR}/ install
}

process_qt5()
{
    # Required libz.dll.a, zlib.h and zconf.h for proper Qt build purpose
   process_zlib
   process_openssl

   if get_source "${URL_Qt5}" "${DIR_Qt5}" "${MKD_Qt5}"
   then
       echo Patching Qt5
   fi
   if [ -f done ]; then
        return
   fi
   echo "Configuring Qt5"
   export OPENSSL_LIBS="-lssl -lcrypto"
   echo y | ./configure \
-xplatform win32-g++  \
-device-option CROSS_COMPILE=/usr/bin/x86_64-w64-mingw32-  \
-prefix ${DEPKGS_DIR}/  \
-opensource -confirm-license \
-no-compile-examples -nomake examples -nomake tests \
-skip qtactiveqt -skip qtcharts -skip qtdoc -skip qtlocation \
-skip qtremoteobjects -skip qtserialbus -skip qtwebchannel \
-skip qtwebview -skip qtandroidextras -skip qtconnectivity \
-skip qtgamepad -skip qtmacextras -skip qtpurchasing -skip qtscript \
-skip qttranslations -skip qtwebengine -skip qtwinextras \
-skip qtdatavis3d -skip qtgraphicaleffects -skip qtmultimedia \
-skip qtquickcontrols -skip qtscxml -skip qtspeech \
-skip qtvirtualkeyboard -skip qtwebglplugin -skip qtx11extras \
-skip qt3d -skip qtcanvas3d -skip qtdeclarative \
-skip qtimageformats -skip qtquickcontrols2  -no-opengl \
-skip qtsensors -skip qtwayland -skip qtwebsockets -I ${DEPKGS_DIR}/include -L ${DEPKGS_DIR}/lib

   make
   make install
   
   echo "Installing Qt5"
   # TODO: Not working
   cd qtbase
   cp -f ./plugins/platforms/qwindows.dll $DEPPKG_DIR/bin
   cp -r ./plugins/platforms $DEPPKG_DIR/bin
   cp -r ./plugins/platforms $DEPPKG_DIR/lib
   cp -rf src/corelib ${DEPPKG_DIR}/src/
   cp -rf src/gui ${DEPPKG_DIR}/src/
   cp -rf src/network ${DEPPKG_DIR}/src/
   cd $DEPPKG_DIR/src
}


process_mingw()
{
   if test -f /usr/lib/gcc/${BASE}/*posix/libstdc++-6.dll; then
      cp /usr/lib/gcc/${BASE}/*posix/libstdc++-6.dll ${DEPPKG_DIR}/bin
      cp /usr/lib/gcc/${BASE}/*posix/libgcc*dll ${DEPPKG_DIR}/bin
   elif test -f /usr/lib/gcc/${BASE}/*/libstdc++-6.dll; then
      cp /usr/lib/gcc/${BASE}/*/libstdc++-6.dll ${DEPPKG_DIR}/bin
      cp /usr/lib/gcc/${BASE}/*/libgcc*dll ${DEPPKG_DIR}/bin
   elif test -f /usr/${BASE}/lib/libstdc++-6.dll; then
      cp /usr/${BASE}/lib/libstdc++-6.dll ${DEPPKG_DIR}/bin
      cp /usr/${BASE}/lib/libgcc*dll ${DEPPKG_DIR}/bin
   else
      echo "ERROR: Unable to find ${BASE} on this system"
   fi
   if test -f /usr/$BASE/lib/libwinpthread-1.dll; then
      cp /usr/$BASE/lib/libwinpthread-1.dll ${DEPPKG_DIR}/bin
   fi

}

process_mtx()
{
   if get_source "${URL_MTX}" "${DIR_MTX}" "${MKD_MTX}"
   then
           echo Patching mtx
           # We can't run configure in a cross-compile environment so we
           # patch the files to the correct values
           cp -f config.h.in config.h
           cp -f Makefile.in Makefile
           rm -f configure
           >patch.log
           do_patch mtx.patch
   fi
   echo Building mtx
   do_make Makefile prefix=${DEPPKG_DIR} all
   echo Installing mtx
   do_make Makefile prefix=${DEPPKG_DIR} install
}

process_mt()
{
   if get_source "${URL_MT}" "${DIR_MT}" "${MKD_MT}"
   then
           echo "Patching mt"
           >patch.log
           do_patch mt.patch
   fi
   echo "Building mt"
   do_make Makefile PREFIX=${DEPPKG_DIR} all
   echo Installing mt
   do_make Makefile PREFIX=${DEPPKG_DIR} install
}

process_sed()
{
   if get_source "${URL_SED}" "${DIR_SED}" "${MKD_SED}"
   then
           echo Patching sed
           >patch.log
           do_patch sed.patch
           echo Configuring sed
           ./configure --host=$BASE \
                       --prefix=${DEPPKG_DIR} \
                       --disable-nls >make.log 2>&1
   fi
   echo Building sed
   do_make Makefile all
   echo Installing sed
   do_make Makefile install
}

process_cmd_utils()
{
   if get_source "${URL_CMD_UTILS}" "${DIR_CMD_UTILS}" "${MKD_CMD_UTILS}"
   then
           # echo Patching cmd-utils
           # >patch.log
           # do_patch cmd-utils.patch
           sed -i "s:strrchr:NULL;//:" expr64/expr64.cpp
           echo Configuring cmd-utils
           ./configure --host=$BASE \
                       --prefix=${DEPPKG_DIR} \
                       >make.log 2>&1
   fi
   echo Building cmd-utils
   do_make Makefile 
   echo Installing cmd-utils
   do_make Makefile install
}


if [ "$#" -eq 0 ]
then
   process_mingw
   process_lzo
   process_zlib
#   process_pcre
#   process_pthreads
   process_openssl
   process_qt5
   process_sed
   process_cmd_utils
#   process_mtx
#   process_mt
else
   for dependency in "$@"
   do
      eval "process_${dependency}"
   done
fi
#vss
#Need to download from Microsoft
