#! /bin/bash
#
# This script is used to build slapos installer of windows. It's running
# only in the SlapOS Cygwin bootstrap node. The directory structures of
# bootstrap node looks like in the install path:
#
#   ./cygwin-packages       Cygwin local packages
#   ./setup.exe             Cygwin setup file
#   ./cygwin                The root path of cygwin
#
# In the cygwin bootstrap node, the following files are required:
#
#   /opt/inno-setup
#   /opt/images
#   /opt/openvpn/bin
#   /opt/openvpn/driver
#   Microsoft Visual C++ 2008 Express Edition or later version
#   Microsoft Windows SDK v7.0 if you're in 64-bits environments
#
# Before run this script, you need first run build-slapos.sh to update
# slapos node:
#
#    ./build-slapos.sh /opt/buildout
#
# Then
#
#    ./slapos-build-installer /opt/buildout
#
# The parameter /opt/buildout is the root path used to run buildout slapos.
#
# In this script, it will do:
#
#    * Prepare the sources required by installer
#
#        * pull slapos.package.git branch cygwin: /opt/git/slapos.package
#        * pull re6stnet.git branch cygwin: /opt/git/re6stnet
#        *
#
#    * Build ipwin/regpwd/ovpn-server/ovpn-client
#
#    * Make installer
#
export PATH=/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin:$PATH
if ! source /usr/share/csih/cygwin-service-installation-helper.sh ; then
    echo "Error: Missing csih package."
    exit 1
fi

# ======================================================================
# Functions
# ======================================================================
function check_os_is_wow64()
{
  [[ $(uname) == CYGWIN_NT-*-WOW64 ]]
}
readonly -f check_os_is_wow64

function show_usage()
{
    echo "Usage:"
    echo ""
    echo "  ./slapos-build-installer [slapos-path]"
    echo ""
    echo "     slapos-path: specify slapos root path, the buildout.cfg will be put in"
    echo "                  slapos-path/slapos. The default value is /opt/buildout"
    echo ""
}
readonly -f show_usage

# ======================================================================
# Start script
# ======================================================================
csih_inform "Starting build Slapos Windows installer ..."
echo ""

# -----------------------------------------------------------
# Start script
# -----------------------------------------------------------
while test $# -gt 0; do
    # Normalize the prefix.
    case "$1" in
    -*=*) optarg=`echo "$1" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
    *) optarg= ;;
    esac

    case "$1" in
    -h | --help)
    show_usage
    exit 0
    ;;
    *)
    ;;
    esac

    # Next please.
    shift
done

# ======================================================================
# Constants
# ======================================================================
declare -r cygwin_home=$(cygpath -m $(cygpath -w /)\\.. | sed -e "s%/$%%")
declare -r ISCC=$(cyypath -m /opt/inno-setup/ISCC.exe)
declare -r slapos_path=${1:-/opt/buildout}

# ======================================================================
# Sanity check
# ======================================================================
[[ -d ${slapos_path}/slapos ]] &&
csih_error "No slapos found in ${slapos_path}/slapos, you need run buildouut first"

if [[ ! -d /opt/images ]] ; then
    _filename=~/images.tar.gz
    [[ -f ${_filename} ]] ||
    wget -c http://www.dashingsoft.com/products/slapos/images.tar.gz -O ${_filename} ||
    csih_error "download ${_filename} failed"
    csih_inform "Got ${_filename}"

    csih_inform "extracting ${_filename} ..."
    (cd /opt ; tar xzf ${_filename} --no-same-owner) ||
    csih_error "extract ${_filename} failed"
fi

if [[ ! -d /opt/openvpn ]] ; then
    _filename=~/openvpn-driver.tar.gz
    if check_os_is_wow64 ; then
        _url=http://www.dashingsoft.com/products/slapos/openvpn-x64.tar.gz
    else
        _url=http://www.dashingsoft.com/products/slapos/openvpn-x86.tar.gz
    fi
    wget -c ${_url} -O ${_filename} ||
    csih_error_multi "download ${_filename} failed" "  from ${_url}"
    csih_inform "Got ${_filename}"
    csih_inform "  from ${_url}"

    csih_inform "extracting ${_filename} ..."
    (cd /opt ; tar xzf ${_filename} --no-same-owner) ||
    csih_error "extract ${_filename} failed"
fi

# -----------------------------------------------------------
# Prepare the sources used to build installer
# -----------------------------------------------------------
csih_inform "Preparing the sources used to build installer ..."

(cd ${slapos_path} ; tar czf slapos.tar.gz slapos/ ; mv slapos.tar.gz /opt/slapos) ||
csih_error "create slapos.tar.gz failed"
csih_inform "tar package /opt/slapos/slapos.tar.gz generated"

_filename=/opt/slapos/slapos.cfg.example
[[ -f ${_filename} ]] ||
wget -c http://git.erp5.org/gitweb/slapos.core.git/blob_plain/HEAD:/slapos.cfg.example -O ${_filename} ||
csih_error "download ${_filename} failed"
csih_inform "Got ${_filename}"

_filename=/opt/slapos/slapos-client.cfg.example
[[ -f ${_filename} ]] ||
wget -c http://git.erp5.org/gitweb/slapos.core.git/blob_plain/HEAD:/slapos-client.cfg.example -O ${_filename} ||
csih_error "download ${_filename} failed"
csih_inform "Got ${_filename}"

(cd /opt/git/slapos.package ; git pull) ||
(cd /opt/git ; git clone -b cygwin http://git.erp5.org/repos/slapos.package.git) ||
csih_error "clone http://git.erp5.org/repos/slapos.package.git failed"
csih_inform "clone/pull http://git.erp5.org/repos/slapos.package.git OK"

if check_os_is_wow64 ; then
    csih_inform "making babeld for vista or above ..."
    (cd /opt/git/slapos.package/windows/babeld ; WINVER=VISTA make) ||
    csih_error "make babeld failed"
else
    csih_inform "making babeld for xp ..."
    (cd /opt/git/slapos.package/windows/babeld ; WINVER=XP make) ||
    csih_error "make babeld failed"
fi

_filename=/opt/git/slapos.package/windows/scripts/regpwd.exe
(cd /opt/git/slapos.package/windows/scripts ; gcc -o regpwd.exe regpwd.c) ||
csih_error "make regpwd.exe failed"
csih_inform "make regpwd.exe"

_filename=/opt/downloads/pyOpenSSL-0.13.tar.gz
[[ -f ${_filename} ]] ||
wget -c --no-check-certificate https://pypi.python.org/packages/source/p/pyOpenSSL/pyOpenSSL-0.13.tar.gz#md5=767bca18a71178ca353dff9e10941929 -O ${_filename} ||
csih_error "download ${_filename} failed"
csih_inform "Got ${_filename}"

_filename=/opt/downloads/miniupnpc-1.8.tar.gz
[[ -f ${_filename} ]] ||
wget -c http://miniupnp.free.fr/files/download.php?file=miniupnpc-1.8.tar.gz -O ${_filename} ||
csih_error "download ${_filename} failed"
csih_inform "Got ${_filename}"

csih_inform "updating re6stnet.git ..."
(cd /opt/git/re6stnet ; git pull) ||
(cd /opt/git ; git clone -b cygwin http://git.erp5.org/repos/re6stnet.git) ||
csih_error "clone/pull re6stnet.git failed"

csih_inform "building ovpn-client and ovpn-server ..."
for _name in ovpn-client ovpn-server ; do
    (cd /opt/git/re6stnet/re6st ; i686-w64-mingw32-gcc -o ${_name}.exe ${_name}.c ovpn-pipe.c) ||
    csih_error "build ${_name}.exe failed"
    csih_inform "build ${_name}.exe OK"
done

csih_inform "creating re6stnet source package ..."
(cd /opt/git/re6stnet ; python setup.py sdist) ||
csih_error "create re6stnet source package failed"

_filename=/opt/git/slapos.package/windows/ipwin/ipwin/ipwin.exe
/opt/git/slapos.package/windows/ipwin/ipwin/build.bat "batch" ||
csih_error "build ipwin.exe failed"
csih_inform "build ${_filename} OK"

csih_inform "Prepare the sources OK"
echo ""

# -----------------------------------------------------------
# Generate installer
# -----------------------------------------------------------
_issfile=~/slapos.iss
_installer_name=slapos-windows-all-in-one
_output_dir=$(cygpath -a -w $(cygpath -w /opt/publish) | sed -e 's%\\%\\\\%g')
_source_dir=$(cygpath -a -w $(cygpath -w /)\\.. | sed -e 's%\\%\\\\%g')
_srcfile=/opt/git/slapos.package/windows/scripts/slapos-all-in-one.iss

csih_inform "Starting generate Windows installer ..."

[[ -x "$ISCC" ]] || csih_error "missing $ISCC"
csih_inform "copy ${_srcfile} to ${_issfile}"
cp ${_srcfile}  ${_issfile} || csih_error "copy failed"

csih_inform "patch ${_issfile} ..."
sed -i -e "s%^OutputBaseFilename=.*%OutputBaseFilename=${_installer_name}%" \
       -e "s%^OutputDir=.*%OutputDir=${_output_dir}%" \
       -e "s%^SourceDir=.*%SourceDir=${_source_dir}%" \
       -e "s%/etc/slapos/scripts/slapos-cygwin-bootstrap.sh%/etc/slapos/scripts/slapos-cygwin-bootstrap.sh --prefix=slaptest-%" \
    ${_issfile} || csih_error "patch failed"

csih_inform "run issc to build ${_issfile} ..."
$ISCC $(cygpath -w ${_issfile}) ||
csih_error "issc failed"

csih_inform "Generate Windows installer OK"
echo ""

# -----------------------------------------------------------
# End scirpt
# -----------------------------------------------------------
echo ""
csih_inform "Build Slapos Windows installer successfully."
echo ""

exit 0