#!/bin/sh -e

BDIR=`cd ..; pwd`
TOPDIR="`cd $(dirname $0) && pwd`"
read VERSION < ${TOPDIR}/VERSION

QT="$BDIR"/qt/`ls "$BDIR"/qt/ |tail -n1`

LIBS="libcrypto.a libltdl.a"
INCS="openssl/opensslv.h ltdl.h"

for l in $LIBS; do
  if test -f "$INSTALL_DIR/lib/$l"; then
    echo found "$INSTALL_DIR/lib/$l"
  else
    echo NOT found "$INSTALL_DIR/lib/$l"
  fi
done

for i in $INCS; do
  if test -f "$INSTALL_DIR/include/$i"; then
    echo found "$INSTALL_DIR/include/$i"
  else
    echo NOT found "$INSTALL_DIR/include/$i"
  fi
done

echo "QT:      '$QT'"
if test -z "$QT"; then
  cat << EOF
OpenSSL or QT not found:
please look at INSTALL.w32
EOF
fi

if test -x "`which osslsigncode`" && test -f "${HOME}/Christian_Hohnstaedt.p12"; then
  OSSLSIGN=osslsigncode
fi

cat > Local.mak << EOF
export TOPDIR=$TOPDIR
export VERSION=$VERSION
export HOST=w32
BDIR=$BDIR
QTDIR=$QT
INSTALL_DIR=$INSTALL_DIR
MAKENSIS=makensis
CROSS=$CROSS

CONSOLE=-mwindows
#CONSOLE=-mconsole

CPPFLAGS=-I\$(TOPDIR) -I\$(QTDIR)/include/QtGui -I\$(QTDIR)/include/QtCore -I\$(QTDIR)/include/QtWidgets -I\$(QTDIR)/include -I\$(INSTALL_DIR)/include -I\$(BUILD) -I\$(BUILD)/ui
CFLAGS=-Wall -g -O2 -mthreads  \$(CONSOLE) -mnop-fun-dllimport -Wno-strict-aliasing -std=c++11

LDFLAGS= -L\$(QTDIR)/lib -L\$(INSTALL_DIR)/lib \
        -Wl,-enable-stdcall-fixup -Wl,-enable-auto-import \
        -Wl,-enable-runtime-pseudo-reloc \
        -static-libgcc -static-libstdc++

# list of dynamic libraries
LIBS=-lQt5Gui -lQt5Core -lQt5Widgets -lcrypto -lltdl

# As long as the linux uic and moc are version compatible to the W32 ones
# we use the native tools, because they are much faster than the wine's
USE_HOSTTOOLS=yes
ifneq (\$(USE_HOSTTOOLS), yes)
MOC=wine \$(QTDIR)/bin/moc
UIC=wine \$(QTDIR)/bin/uic
RCC=wine \$(QTDIR)/bin/rcc
LRELEASE=wine \$(QTDIR)/bin/lrelease
else
MOC=moc
UIC=uic
RCC=rcc
LRELEASE=lrelease
endif

CC=\$(CROSS)g++
LD=\$(CROSS)ld
STRIP=\$(CROSS)strip
WINDRES=\$(CROSS)windres
SUFFIX=.exe
DOCTOOL=linuxdoc -B html
OSSLSIGN=$OSSLSIGN

prefix=
basedir=

EOF

cat > local.h <<EOF
#define PACKAGE_VERSION "${VERSION}"
#define PACKAGE_TARNAME "xca"
#define PACKAGE_NAME "X Certificate and Key management"
EOF


test -f Makefile || ln -s ${TOPDIR}/Makefile
