#!/bin/sh

## This program is not part of PSPP but is used to help build PSPP
## Copyright (C) 2021 John Darrington
##
## This program is free software: you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program.  If not, see <http://www.gnu.org/licenses/>.

# This script downloads (if necessary) and builds the required
# dependencies of PSPP. You may find it useful when cross building.
# Sadly, it it very likely that you'll have to tweak the order of the
# packages, the versions of the packages, their CFLAGS and other
# details in order to succesfully build for any particular
# architecture.  In its current form, it has been tweaked for building
# for mingw archs.

required_native_programs="awk sha256sum tar sed gtk-encode-symbolic-svg ninja meson cat grep pkg-config"

for p in $required_native_programs; do
    if ! type "$p" > /dev/null; then
        echo $p must be installed and in PATH;
        exit 1
    fi
done

while test $# -gt 0; do
    case $1 in
        --arch=*)
            arch=${1##--arch=};;
        --sandbox=*)
            SANDBOX=${1##--sandbox=};;
        --tarballs=*)
            SRC_TARBALL_DIR=${1##--tarballs=};;
        --no-clean)
            noclean=yes;;
        *)
            printf "Usage: $0 --arch=<arch> --sandbox=<dir> [--tarballs=<dir>]\n";
            exit 1;
        ;;
    esac
    shift 1;
done

if test -z "$SANDBOX" -o -z "$arch"; then
            printf "Usage: $0 --arch=<arch> --sandbox=<dir> [--tarballs=<dir>]\n";
    exit 1;
fi

SANDBOX=`eval echo $SANDBOX`

if test -z "$SRC_TARBALL_DIR"; then
    SRC_TARBALL_DIR="$SANDBOX/tarballs"
fi

SRC_TARBALL_DIR=`eval echo $SRC_TARBALL_DIR`

test "x$noclean" = "xyes" || rm -rIf $SANDBOX

default_build_procs=$(expr $(cat /proc/cpuinfo | grep -c '^processor') + 1)

mkdir -p $SRC_TARBALL_DIR

mkdir -p $SANDBOX

export DESTDIR=""

cat > $SANDBOX/cross-file.txt <<EOF
[host_machine]
system = 'windows'
cpu_family = 'x86_64'
cpu = 'x86_64'
endian = 'little'

[binaries]
c = '$arch-gcc'
cpp = '$arch-g++'
ar = '$arch-ar'
ld = '$arch-ld'
objcopy = '$arch-objcopy'
strip = '$arch-strip'
pkgconfig = 'pkg-config'
windres = '$arch-windres'
EOF

tarballs="zlib-1.2.11.tar.gz"
tarballs="$tarballs libiconv-1.16.tar.gz"
tarballs="$tarballs gettext-0.21.tar.xz"
tarballs="$tarballs libffi-3.3.tar.gz"
tarballs="$tarballs pixman-0.40.0.tar.gz"
tarballs="$tarballs libpng-1.6.37.tar.gz"
tarballs="$tarballs libxml2-2.9.10.tar.gz"
tarballs="$tarballs freetype-2.10.4.tar.xz"
tarballs="$tarballs fribidi-1.0.10.tar.xz"
tarballs="$tarballs harfbuzz-2.7.4.tar.xz"
tarballs="$tarballs glib-2.67.6.tar.xz"
tarballs="$tarballs cairo-1.17.4.tar.xz"
tarballs="$tarballs pango-1.48.0.tar.xz"
tarballs="$tarballs atk-2.36.0.tar.xz"
tarballs="$tarballs gdk-pixbuf-2.42.2.tar.xz"
tarballs="$tarballs libepoxy-1.5.5.tar.xz"
tarballs="$tarballs gtk+-3.24.27.tar.xz"
tarballs="$tarballs gsl-2.6.tar.gz"
tarballs="$tarballs gtksourceview-3.24.9.tar.xz"
tarballs="$tarballs spread-sheet-widget-0.8.tar.gz"
tarballs="$tarballs hicolor-icon-theme-0.17.tar.xz"
tarballs="$tarballs adwaita-icon-theme-3.38.0.tar.xz"

mkdir -p $SANDBOX/Source
for t in $tarballs ; do
    url=""
    case $t in
        ncurses-6.2.tar.gz)
            url="ftp://ftp.gnu.org/gnu/ncurses/ncurses-6.2.tar.gz";
            hash=30306e0c76e0f9f1f0de987cf1c82a5c21e1ce6568b9227f7da5b71cbea86c9d;;
        readline-8.1.tar.gz)
            url="ftp://ftp.gnu.org/gnu/readline/readline-8.1.tar.gz";
            hash=f8ceb4ee131e3232226a17f51b164afc46cd0b9e6cef344be87c65962cb82b02;;
        termcap-1.3.1.tar.gz)
            url="ftp://ftp.gnu.org/gnu/termcap/termcap-1.3.1.tar.gz";
            hash=91a0e22e5387ca4467b5bcb18edf1c51b930262fd466d5fda396dd9d26719100;;
        fontconfig-2.12.6.tar.bz2)
            url="https://www.freedesktop.org/software/fontconfig/release/fontconfig-2.12.6.tar.bz2";
            hash=cf0c30807d08f6a28ab46c61b8dbd55c97d2f292cf88f3a07d3384687f31f017;;
        adwaita-icon-theme-3.38.0.tar.xz)
            url="https://download.gnome.org/sources/adwaita-icon-theme/3.38/adwaita-icon-theme-3.38.0.tar.xz";
            hash=6683a1aaf2430ccd9ea638dd4bfe1002bc92b412050c3dba20e480f979faaf97;;
        librsvg-2.31.0.tar.bz2)
            url="https://ftp.acc.umu.se/pub/GNOME/sources/librsvg/2.31/librsvg-2.31.0.tar.bz2";
            hash=320b61ef5e6d65624f3733a83134df012a4156ed7f7ae38a6ed19febe1bfa732;;
        librsvg-2.49.5.tar.xz)
            url="https://download.gnome.org/sources/librsvg/2.49/librsvg-2.49.5.tar.xz";
            hash=daa64941bb4732bdf51b902a72c6e04063235cfce6986d910ba0759c76917795;;
        librsvg-2.51.0.tar.xz)
            url="https://ftp.acc.umu.se/pub/GNOME/sources/librsvg/2.51/librsvg-2.51.0.tar.xz";
            hash=89d32e38445025e1b1d9af3dd9d3aeb9f6fce527aeecbecf38b369b34c80c038;;
        hicolor-icon-theme-0.17.tar.xz)
            url="https://icon-theme.freedesktop.org/releases/hicolor-icon-theme-0.17.tar.xz";
            hash=317484352271d18cbbcfac3868eab798d67fff1b8402e740baa6ff41d588a9d8;;
        gettext-0.21.tar.xz)
            url="https://ftp.gnu.org/gnu/gettext/gettext-0.21.tar.xz";
            hash=d20fcbb537e02dcf1383197ba05bd0734ef7bf5db06bdb241eb69b7d16b73192;;
        spread-sheet-widget-0.8.tar.gz)
            url="https://alpha.gnu.org/gnu/ssw/spread-sheet-widget-0.8.tar.gz"
            hash=8589d8298fcf3b5850d0968b04801a4f40faf0555544f6cc9d954b0162e9954b;;
        gtksourceview-3.24.9.tar.xz)
            url="https://download.gnome.org/sources/gtksourceview/3.24/gtksourceview-3.24.9.tar.xz"
            hash=699d76a453e6a3d3331906346e3dbfa25f2cbc9ec090e46635e9c6bb595e07c2;;
        libepoxy-1.5.5.tar.xz)
            url="https://github.com/anholt/libepoxy/releases/download/1.5.5/libepoxy-1.5.5.tar.xz"
            hash=261663db21bcc1cc232b07ea683252ee6992982276536924271535875f5b0556;;
        gdk-pixbuf-2.42.2.tar.xz)
            url="https://download.gnome.org/sources/gdk-pixbuf/2.42/gdk-pixbuf-2.42.2.tar.xz";
            hash=83c66a1cfd591d7680c144d2922c5955d38b4db336d7cd3ee109f7bcf9afef15;;
        gobject-introspection-1.67.1.tar.xz)
            url="https://download.gnome.org/sources/gobject-introspection/1.67/gobject-introspection-1.67.1.tar.xz";
            ;;
        atk-2.36.0.tar.xz)
            url="https://download.gnome.org/sources/atk/2.36/atk-2.36.0.tar.xz";
            hash=fb76247e369402be23f1f5c65d38a9639c1164d934e40f6a9cf3c9e96b652788;;
        gtk+-3.24.27.tar.xz)
            url="https://download.gnome.org/sources/gtk+/3.24/gtk%2B-3.24.27.tar.xz";
            hash=f71c067570339f9f8efac7bb87717a2c52279cb50223fb8b5ba7085930757a26;;
        cairo-1.17.4.tar.xz)
            url="https://cairographics.org/snapshots/cairo-1.17.4.tar.xz";
            hash=74b24c1ed436bbe87499179a3b27c43f4143b8676d8ad237a6fa787401959705;;
        harfbuzz-2.7.4.tar.xz)
            url="https://github.com/harfbuzz/harfbuzz/releases/download/2.7.4/harfbuzz-2.7.4.tar.xz";
            hash=6ad11d653347bd25d8317589df4e431a2de372c0cf9be3543368e07ec23bb8e7;;
        fribidi-1.0.10.tar.xz)
            url="https://github.com/fribidi/fribidi/releases/download/v1.0.10/fribidi-1.0.10.tar.xz";
            hash=7f1c687c7831499bcacae5e8675945a39bacbad16ecaa945e9454a32df653c01;;
        fontconfig-2.13.0.tar.bz2)
            url="https://www.freedesktop.org/software/fontconfig/release/fontconfig-2.13.0.tar.bz2";
            hash=91dde8492155b7f34bb95079e79be92f1df353fcc682c19be90762fd3e12eeb9;;
        libffi-3.3.tar.gz)
            url="ftp://sourceware.org/pub/libffi/libffi-3.3.tar.gz";
            hash=72fba7922703ddfa7a028d513ac15a85c8d54c8d67f55fa5a4802885dc652056;;
        zlib-1.2.11.tar.gz)
            url="https://zlib.net/fossils/zlib-1.2.11.tar.gz";
            hash=c3e5e9fdd5004dcb542feda5ee4f0ff0744628baf8ed2dd5d66f8ca1197cb1a1;;
        pixman-0.40.0.tar.gz)
            url="https://www.cairographics.org/releases/pixman-0.40.0.tar.gz";
            hash=6d200dec3740d9ec4ec8d1180e25779c00bc749f94278c8b9021f5534db223fc;;
        libpng-1.6.37.tar.gz)
            url="https://download.sourceforge.net/libpng/libpng-1.6.37.tar.gz";
            hash=daeb2620d829575513e35fecc83f0d3791a620b9b93d800b763542ece9390fb4;;
        freetype-2.10.4.tar.xz)
            url="https://download.savannah.gnu.org/releases/freetype/freetype-2.10.4.tar.xz";
            hash=86a854d8905b19698bbc8f23b860bc104246ce4854dcea8e3b0fb21284f75784;;
        glib-2.67.6.tar.xz)
            url="https://download.gnome.org/sources/glib/2.67/glib-2.67.6.tar.xz";
            hash=dd7f563509b410e8f94ef2d4cc7f74620a6b29d7c5d529fedec53c5e8018d9c5;;
        pango-1.48.0.tar.xz)
            url="https://download.gnome.org/sources/pango/1.48/pango-1.48.0.tar.xz";
            hash=391f26f3341c2d7053e0fb26a956bd42360dadd825efe7088b1e9340a65e74e6;;
        pango-1.40.0.tar.xz)
            hash=da17985df314cb07d066ab5424f59c21ce973ece05b7de4df04d798ec8511c8b;;
        gsl-2.6.tar.gz)
            url="https://ftp.gnu.org/gnu/gsl/gsl-2.6.tar.gz";
            hash=b782339fc7a38fe17689cb39966c4d821236c28018b6593ddb6fd59ee40786a8;;
        libiconv-1.16.tar.gz)
            url="https://ftp.gnu.org/gnu/libiconv/libiconv-1.16.tar.gz";
            hash=e6a1b1b589654277ee790cce3734f07876ac4ccfaecbee8afa0b649cf529cc04;;
        libxml2-2.9.10.tar.gz)
            url="ftp://xmlsoft.org/libxml2/libxml2-2.9.10.tar.gz";
            hash=aafee193ffb8fe0c82d4afef6ef91972cbaf5feea100edc2f262750611b4be1f;;
        *) hash=XX;;
    esac

    # Fetch the tarball if we don't already have it.
    if ! test -e $SRC_TARBALL_DIR/$t; then
        (cd $SRC_TARBALL_DIR && wget $url)
    fi

    case $t in
        pspp-*)
            # Don't check the hash for this since it's changing rapidly
        ;;
        *)    # Check that it hasn't been corrupted or compromised
              h=`(cd $SRC_TARBALL_DIR && sha256sum $t) | awk '{print $1}'`
              if ! test "$hash" = $h ; then
                  echo "Hash for $t is invalid" ;
                  exit 1
              fi
              ;;
    esac
done

# No network access should be necessary after this point
for t in $tarballs ; do
    # Unpack the tarballs into the Source directory
    case $t in
        *.zip)
            pkg=${t%%.zip}
            unarch="unzip -o"
            ;;
        *.tar.xz)
            pkg=${t%%.tar.xz}
            unarch="tar -xJf"
            ;;
        *.tar.gz)
            pkg=${t%%.tar.gz}
            unarch="tar -xzf"
            ;;
        *.tar.bz2)
            pkg=${t%%.tar.bz2}
            unarch="tar -xjf"
            ;;
        *)
            echo "Unknown archive suffix: $t";
            exit 1;
            ;;
    esac

    (cd $SANDBOX/Source && $unarch  $SRC_TARBALL_DIR/$t)

    # Build the package
    rm  -rf $SANDBOX/Build/$pkg
    mkdir -p $SANDBOX/Build/$pkg
    build_procs=$default_build_procs
    case $pkg in
        # Deal with the special cases here
        zlib-*)
            cd $SANDBOX/Build/$pkg && \
                CC=$arch-gcc LDSHAREDLIBC="" $SANDBOX/Source/$pkg/configure --prefix="$SANDBOX/Install" && \
                make -j $build_procs && make install
            ;;
        # And now the generic cases
        *)
            depdir=$SANDBOX/Install
            build_system="autoconf"
            pre_configure=""
            prefix=$SANDBOX/Install
            case $pkg in
                cairo-*)
                    extra_cflags="-fstack-protector";;
                gsl-*)
                    extra_config_flags="GSL_LDFLAGS=-XCClinker -fstack-protector";
                    extra_cflags="-fstack-protector";;
                librsvg-*)
                    extra_config_flags="--disable-tools --enable-introspection=no --disable-gtk-doc-html"
                    build_procs=1
                    ;;
                libepoxy-*)
                    build_system="meson";
                    ;;
                gtk+-*)
                    build_system="meson";
                    meson_opts="-Dintrospection=false -Dtests=false -Ddemos=false -Dexamples=false";
                    ;;
                gdk-pixbuf-*)
                    build_system="meson";
                    meson_opts="-Dintrospection=disabled -Dbuiltin_loaders=all -Dnative_windows_loaders=true -Dinstalled_tests=false -Dman=false";
                    ;;
                gobject-introspection-*)
                    build_system="meson";
                    meson_opts=-Dpython=python3;
                    ;;
                atk-*)
                    build_system="meson";
                    meson_opts=-Dintrospection=false;
                    ;;
                glib-*)
                    build_system="meson";
                    meson_opts="-Dtests=false";
                    extra_cflags=-Wno-format;  #no-format seems to be necessary for 32 bit builds
                    ;;
                harfbuzz*)
                    build_system="meson";
                    meson_opts=-Dglib=disabled;
                    ;;
                freetype-*)
                    extra_config_flags="--enable-static=no";
                    ;;
                fontconfig-*)
                    extra_config_flags="--enable-libxml2 --disable-docs";
                    ;;
                libxml2-*)
                    extra_config_flags=--without-python;
                    ;;
                gettext*)
                    extra_config_flags="--enable-shared=yes";
                    # We only need gettext-runtime
                    pre_configure="sed -i -e /^SUBDIRS/s/libtextstyle.gettext-tools// $SANDBOX/Source/$pkg/Makefile.in";
                    ;;
                pango-1.48.*)
                    build_system="meson";
                    extra_cflags="-fstack-protector";
                    extra_ldflags="-fstack-protector";
                    ;;
                spread-sheet-widget-*)
                    ;;
                pspp-*)
                    extra_config_flags="--enable-relocatable";
                    extra_build="make -j $build_procs install-html install-pdf";
                    prefix=$SANDBOX/Bundle;
                    ;;
            esac
            case $build_system in
                meson)
                    PKG_CONFIG_LIBDIR="$SANDBOX/Install/lib/pkgconfig" \
                                     meson setup --prefix=$prefix \
                                     --libdir=lib \
                                     --cross-file=$SANDBOX/cross-file.txt \
                                     -Dc_link_args="-L$SANDBOX/Install/lib $extra_ldflags" \
                                     -Dc_args="-I$SANDBOX/Install/include $extra_cflags" \
                                     --wrap-mode=nodownload \
                                     $meson_opts \
                                     $SANDBOX/Source/$pkg $SANDBOX/Build/$pkg &&
                        ninja -j $build_procs -C $SANDBOX/Build/$pkg &&
                        meson install -C $SANDBOX/Build/$pkg
                    ;;
                autoconf)
                    $pre_configure && \
                        cd $SANDBOX/Build/$pkg && \
                        $SANDBOX/Source/$pkg/configure \
                            --host="$arch" \
                            --prefix="$prefix" \
                            "$extra_config_flags" \
                            CFLAGS="$extra_cflags" \
                            CPPFLAGS="-I $depdir/include $extra_cppflags" \
                            LDFLAGS="-L$depdir/lib $extra_ldflags" \
                            PKG_CONFIG_LIBDIR="$depdir/lib/pkgconfig" &&
                        make -j $build_procs && make install && $extra_build
                    ;;
                *)
                    echo I have no idea how to build $SANDBOX/Source/$pkg
                    false
            esac
            ;;
    esac || exit 1;
echo Done $pkg;
done


printf "You can now configure pspp with a command similar to:\n"
printf "configure --host=\"$arch\" CPPFLAGS=\"-I $SANDBOX/Install/include\" LDFLAGS=\"-L$SANDBOX/Install/lib\" PKG_CONFIG_LIBDIR=\"$SANDBOX/Install/lib/pkgconfig\"\n"
