# -*- shell-script -*-
# Emscripten compilation instructions

# Copyright (C) 2018, 2019  Sylvain Beucler

# This file is part of GNU FreeDink

# GNU FreeDink 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.

# GNU FreeDink 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/>.

# It'd make sense to place everything in emscripten/system/local/ ,
# but I'm compiling several projects with different versions of SDL,
# so I need a separate root for each.  Or maybe I should setup
# multiple emscripten envs...

set -ex

#MODE=devel
MODE=optim

PREFIX=$(pwd)/$MODE
PATH=$(pwd)/$MODE/bin:$PATH  # freetype-config

# only seems to make a perf difference in asmjs...
if [ "$MODE" = "devel" ]; then
    # -g3/-g4 -> symbols in webassembly stacktrace
    CFLAGS='-s ASSERTIONS=2'
    CXXFLAGS='-s ASSERTIONS=2'
    LDFLAGS='-g4 -s DEMANGLE_SUPPORT=1'
else
    # -s ASSERTIONS=0 -> not worth it
    CFLAGS=-O3
    CXXFLAGS=-O3
    LDFLAGS=-O3
fi


WGET=${WGET:-wget -c}
EMBUILDER=$(dirname $(which emcc))/embuilder.py
FILE_PACKAGER="python $(dirname $(which emcc))/tools/file_packager.py"


# Avoid issues with binaryen built during emmake/emconfigure
$EMBUILDER build binaryen

# Attempting generally with emconfigure+emmake which tries to pass as
# a local build, so without cross-compilation.  If necessary, replace
# config.sub and config.guess with the ones from SDL2 which support
# '--host asmjs-unknown-emscripten' and cross-compile anyway.

# TODO: --disable-shared everywhere for good measure
# TODO: build/ -> cross-emscripten/

# TODO: SDL2 seems to pick native libiconv incorrectly
# Note: now using -s USE_SDL=2 instead as Emscripten 1.38.27 only works with their current SDL2 "port"
$WGET http://libsdl.org/release/SDL2-2.0.8.tar.gz
tar xf SDL2-2.0.8.tar.gz
(
    cd SDL2-2.0.8/
    patch -p1 <<'EOF'
https://bugzilla.libsdl.org/show_bug.cgi?id=4176
diff -ru SDL2-2.0.8/src/audio/emscripten/SDL_emscriptenaudio.c ../src/audio/emscripten/SDL_emscriptenaudio.c
--- SDL2-2.0.8/src/audio/emscripten/SDL_emscriptenaudio.c	2018-03-01 17:34:42.000000000 +0100
+++ ../src/audio/emscripten/SDL_emscriptenaudio.c	2018-05-26 16:09:37.263108635 +0200
@@ -246,6 +246,7 @@
     }
     SDL_zerop(this->hidden);
 #endif
+    this->hidden = (struct SDL_PrivateAudioData *)0x1;
 
     /* limit to native freq */
     this->spec.freq = EM_ASM_INT_V({ return SDL2.audioContext.sampleRate; });
EOF
    patch -p1 <<'EOF'
https://bugzilla.libsdl.org/show_bug.cgi?id=4179
--- SDL2-2.0.8/src/video/SDL_surface.c-dist	2018-07-05 18:42:10.905476195 +0200
+++ SDL2-2.0.8/src/video/SDL_surface.c	2018-07-05 18:42:21.337384944 +0200
@@ -300,7 +300,7 @@
     }
 
     if (!(surface->map->info.flags & SDL_COPY_COLORKEY)) {
-        return SDL_SetError("Surface doesn't have a colorkey");
+        return -1;
     }
 
     if (key) {
EOF
    patch -p1 <<'EOF'
commit 74a5d8e0552bc9fb9d105f8ec715b7a86009a8c6
Author: Charlie Birks <charlie@daftgames.net>
Date:   Fri Jan 11 15:49:24 2019 +0000

    Emscripten: call emscripten_sample_gamepad_data

diff --git a/src/joystick/emscripten/SDL_sysjoystick.c b/src/joystick/emscripten/SDL_sysjoystick.c
index cd2fd56a4..a0926c538 100644
--- a/src/joystick/emscripten/SDL_sysjoystick.c
+++ b/src/joystick/emscripten/SDL_sysjoystick.c
@@ -166,13 +166,16 @@ SDL_SYS_JoystickInit(void)
     EmscriptenGamepadEvent gamepadState;
 
     numjoysticks = 0;
-    numjs = emscripten_get_num_gamepads();
+
+    retval = emscripten_sample_gamepad_data();
 
     /* Check if gamepad is supported by browser */
-    if (numjs == EMSCRIPTEN_RESULT_NOT_SUPPORTED) {
+    if (retval == EMSCRIPTEN_RESULT_NOT_SUPPORTED) {
         return SDL_SetError("Gamepads not supported");
     }
 
+    numjs = emscripten_get_num_gamepads();
+
     /* handle already connected gamepads */
     if (numjs > 0) {
         for(i = 0; i < numjs; i++) {
@@ -313,6 +316,8 @@ SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
     SDL_joylist_item *item = (SDL_joylist_item *) joystick->hwdata;
     int i, result, buttonState;
 
+    emscripten_sample_gamepad_data();
+
     if (item) {
         result = emscripten_get_gamepad_status(item->index, &gamepadState);
         if( result == EMSCRIPTEN_RESULT_SUCCESS) {
EOF
    patch -p1 <<'EOF'
--- a/src/video/emscripten/SDL_emscriptenopengles.c     2018-03-01 17:34:42.000000000 +0100
+++ b/src/video/emscripten/SDL_emscriptenopengles.c     2019-01-22 16:57:56.270005327 +0100
@@ -87,7 +87,7 @@
     ES2 renderer resets state on init anyway, clearing the canvas should be enough
     */
 
-    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
+    //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
 
     SDL_EGL_DeleteContext(_this, context);
 }
EOF
    mkdir -p cross-emscripten-$MODE
    cd cross-emscripten-$MODE/
    emconfigure ../configure --host=asmjs-unknown-emscripten \
      --disable-assembly --disable-threads --disable-cpuinfo \
       CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS" \
      --prefix $PREFIX
    emmake make -j$(nproc)
    emmake make install
)

$WGET http://prdownloads.sourceforge.net/libpng/zlib-1.2.11.tar.gz
tar xf zlib-1.2.11.tar.gz
(
    cd zlib-1.2.11/
    mkdir -p cross-emscripten-$MODE
    cd cross-emscripten-$MODE/
    emconfigure env CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS" ../configure --prefix $PREFIX
    emmake make -j$(nproc)
    emmake make install
)    

$WGET http://prdownloads.sourceforge.net/libpng/libpng-1.6.34.tar.gz
tar xf libpng-1.6.34.tar.gz
(
    cd libpng-1.6.34/
    mkdir -p cross-emscripten-$MODE
    cd cross-emscripten-$MODE/
    emconfigure ../configure --prefix $PREFIX \
      CPPFLAGS="-I$PREFIX/include" CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS -L$PREFIX/lib"
    emmake make -j$(nproc)
    emmake make install
)

$WGET http://libsdl.org/projects/SDL_image/release/SDL2_image-2.0.3.tar.gz
tar xf SDL2_image-2.0.3.tar.gz
(
    cd SDL2_image-2.0.3/
    mkdir -p cross-emscripten-$MODE
    cd cross-emscripten-$MODE/
    EMCONFIGURE_JS=1 emconfigure ../configure --prefix $PREFIX \
      --disable-shared \
      --enable-bmp --enable-xpm --enable-png \
        --disable-gif --disable-jpg --disable-jpg-shared --disable-lbm --disable-pcx \
        --disable-png-shared --disable-svg --disable-tga --disable-tif --disable-tif-shared \
        --disable-xcf --disable-webp --disable-webp-shared \
      CPPFLAGS="-I$PREFIX/include" CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS -L$PREFIX/lib"
    emmake make -j$(nproc)
    emmake make install
)


# MOD
$WGET https://sourceforge.net/projects/modplug-xmms/files/libmodplug/0.8.9.0/libmodplug-0.8.9.0.tar.gz
tar xf libmodplug-0.8.9.0.tar.gz
(
    cd libmodplug-0.8.9.0/
    mkdir -p cross-emscripten-$MODE
    cd cross-emscripten-$MODE/
    emconfigure ../configure --prefix $PREFIX \
      CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS"
    emmake make -j$(nproc)
    emmake make install
)

$WGET http://downloads.xiph.org/releases/ogg/libogg-1.3.3.tar.gz
tar xf libogg-1.3.3.tar.gz
(
    cd libogg-1.3.3/
    mkdir -p cross-emscripten-$MODE
    cd cross-emscripten-$MODE/
    emconfigure ../configure --prefix $PREFIX \
      CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS"
    emmake make -j$(nproc)
    emmake make install
)

$WGET http://downloads.xiph.org/releases/vorbis/libvorbis-1.3.6.tar.gz
tar xf libvorbis-1.3.6.tar.gz
(
    cd libvorbis-1.3.6/
    mkdir -p cross-emscripten-$MODE
    cd cross-emscripten-$MODE/
    emconfigure ../configure --prefix $PREFIX \
      CPPFLAGS="-I$PREFIX/include" CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS -L$PREFIX/lib"
    emmake make -j$(nproc)
    emmake make install
)

$WGET http://libsdl.org/projects/SDL_mixer/release/SDL2_mixer-2.0.2.tar.gz
tar xf SDL2_mixer-2.0.2.tar.gz
# With 2.0.1 I get no sound at all; 2.0.2 uses SDL_AudioStream from
# newer SDL2 and works
# TODO: MP3
(
    cd SDL2_mixer-2.0.2/
    mkdir -p cross-emscripten-$MODE
    cd cross-emscripten-$MODE/
    EMCONFIGURE_JS=1 emconfigure ../configure \
      --prefix $PREFIX \
      --enable-music-wave \
      --disable-music-ogg-shared --enable-music-ogg \
      --enable-music-midi --enable-music-midi-timidity \
      --disable-music-midi-native --disable-music-midi-fluidsynth --disable-music-midi-fluidsynth-shared \
      --enable-music-mod-modplug --disable-music-mod-modplug-shared \
      --disable-music-mod --disable-music-mod-mikmod-shared \
      --disable-music-cmd \
      --disable-music-flac --disable-music-flac-shared \
      --disable-music-mp3 --disable-music-mp3-smpeg --disable-music-mp3-smpeg-shared --disable-smpegtest \
      CPPFLAGS="-I$PREFIX/include" CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS -L$PREFIX/lib"
    emmake make -j$(nproc)
    emmake make install
)

#https://www.freedesktop.org/software/harfbuzz/release/harfbuzz-1.7.6.tar.bz2
$WGET https://download.savannah.gnu.org/releases/freetype/freetype-2.9.tar.gz
tar xf freetype-2.9.tar.gz
(
    cd freetype-2.9/
    \cp -a ../SDL2-2.0.8/build-scripts/config.{guess,sub} builds/unix/
    mkdir -p cross-emscripten-$MODE
    cd cross-emscripten-$MODE/
    # not enabling bzip/png until we have examples of when that's needed
    # not enable harfbuzz because I don't think we'll need that for now + one dependencies fewer
    # cross-compiling because the native install target relies on a locally built 'apinames' tool
    emconfigure ../configure --prefix $PREFIX \
      --host asmjs-unknown-emscripten --build $(sh ../builds/unix/config.guess) \
      --with-zlib=yes --with-bzip2=no --with-png=no --with-harfbuzz=no \
      CPPFLAGS="-I$PREFIX/include" CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS -L$PREFIX/lib"
    emmake make -j$(nproc)
    emmake make install
)

$WGET http://libsdl.org/projects/SDL_ttf/release/SDL2_ttf-2.0.14.tar.gz
tar xf SDL2_ttf-2.0.14.tar.gz
(
    cd SDL2_ttf-2.0.14/
    mkdir -p cross-emscripten-$MODE
    cd cross-emscripten-$MODE/
    EMCONFIGURE_JS=1 emconfigure ../configure --prefix $PREFIX \
      --disable-shared \
      PKG_CONFIG_LIBDIR=$PREFIX/lib/pkgconfig \
      CPPFLAGS="-I$PREFIX/include" CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS -L$PREFIX/lib"
    emmake make -j$(nproc)
    emmake make install
)

$WGET http://www.ferzkopp.net/Software/SDL2_gfx/SDL2_gfx-1.0.4.tar.gz
tar xf SDL2_gfx-1.0.4.tar.gz
(
    cd SDL2_gfx-1.0.4/
    mkdir -p cross-emscripten-$MODE
    cd cross-emscripten-$MODE/
    EMCONFIGURE_JS=1 emconfigure ../configure --prefix $PREFIX \
      --disable-shared --disable-mmx \
      CPPFLAGS="-I$PREFIX/include" CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS -L$PREFIX/lib"
    emmake make -j$(nproc)
    emmake make install
)


# Still not building libintl.a
#$WGET https://ftp.gnu.org/pub/gnu/gettext/gettext-0.19.8.tar.xz
#tar xf gettext-0.19.8.tar.xz
#(
#    cd gettext-0.19.8/
#    cp -a ../SDL2-2.0.8/build-scripts/config.* build-aux/
#    cd gettext-runtime/
#    mkdir build
#    cd build/
#    # cross-compiling to try and avoid gettext/libtool confusing itself
#    emconfigure ../configure --prefix $PREFIX \
#      --host asmjs-unknown-emscripten --build $(sh ../../build-aux/config.guess) \
#      --disable-shared \
#      "${TARGETFLAGS[@]}"
#    emmake make -j$(nproc)
#    emmake make install
#)
$WGET http://ftp.gnu.org/pub/gnu/gettext/gettext-0.19.5.tar.gz
tar xf gettext-0.19.5.tar.gz
(
    cd gettext-0.19.5/
    cd gettext-runtime/
    mkdir -p cross-emscripten-$MODE
    cd cross-emscripten-$MODE/
    emconfigure ../configure --prefix $PREFIX \
      --disable-shared \
      CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS"
    emmake make -j$(nproc)
    emmake make install
)

$WGET https://github.com/g-truc/glm/archive/0.9.8.5.tar.gz
tar xf 0.9.8.5.tar.gz
(
  cd glm-0.9.8.5/
  cp -a glm $PREFIX/include/
)

$WGET https://sourceforge.net/projects/cxxtest/files/cxxtest/4.4/cxxtest-4.4.tar.gz -O cxxtest-4.4.tar.gz
tar xf cxxtest-4.4.tar.gz
(
    cd cxxtest-4.4/
    cp -a cxxtest $PREFIX/include/
)

$WGET https://sourceforge.net/projects/bzip2/files/bzip2-1.0.6.tar.gz
tar xf bzip2-1.0.6.tar.gz
(
    cd bzip2-1.0.6/
    emmake make CC=emcc libbz2.a CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS"
    touch bzip2 bzip2.o bzip2recover bzip2recover.o
    emmake make CC=emcc CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS" PREFIX=$PREFIX install 
)

$WGET https://libzip.org/download/libzip-1.5.1.tar.gz
tar xf libzip-1.5.1.tar.gz
(
    cd libzip-1.5.1/
    # This thing can't properly set its own LIBS (-lz), disable executables generation
    sed -i -e 's/ADD_SUBDIRECTORY(man)/#&/' CMakeLists.txt
    sed -i -e 's/ADD_SUBDIRECTORY(src)/#&/' CMakeLists.txt
    sed -i -e 's/ADD_SUBDIRECTORY(regress)/#&/' CMakeLists.txt
    sed -i -e 's/ADD_SUBDIRECTORY(examples)/#&/' CMakeLists.txt
    mkdir -p cross-emscripten-$MODE
    cd cross-emscripten-$MODE/
    CPPFLAGS="-I$PREFIX/include" CFLAGS="$CFLAGS" LDFLAGS="$LDFLAGS -L$PREFIX/lib" \
      emcmake cmake \
        -D CMAKE_INSTALL_PREFIX=$PREFIX \
        -D ENABLE_GNUTLS=false -D ENABLE_OPENSSL=false -D ENABLE_COMMONCRYPTO=false \
        -D BUILD_SHARED_LIBS=false \
        -D ZLIB_LIBRARY=$PREFIX/lib -D ZLIB_INCLUDE_DIR=$PREFIX/include \
        ..
    sed -i -e 's/^#define SIZEOF_OFF_T 7/#define SIZEOF_OFF_T 4/' config.h
    emmake make -j$(nproc)
    emmake make install
)

exit 0

(
  cd .../freedink-data/
  make update-gmo
  make install DESTDIR=$(pwd)/destdir
  rm -f $(pwd)/destdir/usr/local/share/dink/dink/Story/key-67.c
  rm -f $(pwd)/destdir/usr/local/share/dink/dink/save*.dat

  (cd destdir; mkdir -p etc etc/timidity usr/share usr/share/midi/)
  \cp -a /usr/share/midi/freepats destdir/usr/share/midi/
  \cp -a /etc/timidity/freepats.cfg destdir/etc/timidity/timidity.cfg
)

(
  cd freedink/
  cp -a .../SDL2/build-scripts/config.* autotools/
  mkdir -p cross-emscripten-$MODE
  cd cross-emscripten-$MODE/
  # cross-compiling to disable fontconfig dependency
  emconfigure ../configure \
    --host asmjs-unknown-emscripten --build $(sh ../autotools/config.guess) \
    PKG_CONFIG_LIBDIR=$PREFIX/lib/pkgconfig:$(emconfigure env|grep ^PKG_CONFIG_LIBDIR|sed 's/^PKG_CONFIG_LIBDIR=//') \
    CPPFLAGS="-I$PREFIX/include -s USE_SDL=2" \
    CFLAGS="$CFLAGS -s USE_SDL=2" \
    LDFLAGS="$LDFLAGS -L$PREFIX/lib -s USE_SDL=2"
  emmake make -j$(nproc)
  (cd share/ && emmake make install -k DESTDIR=$PREFIX/../freedink-data/destdir/)
  (cd po/ && emmake make update-gmo && emmake make install -k DESTDIR=$PREFIX/../freedink-data/destdir/)
  mkdir -p t
  # -s DISABLE_EXCEPTION_CATCHING=1 (default) + -fno-exceptions -fno-rtti (in CXXFLAGS)
  # -s NO_EXIT_RUNTIME=0: no, can't re-run the app
  # EXTRA_EXPORTED_RUNTIME_METHODS:ccall/cwrap: for calling exported functions from JS
  # EXTRA_EXPORTED_RUNTIME_METHODS:Pointer_stringify: for SDL2
  # EXTRA_EXPORTED_RUNTIME_METHODS:GetValue: for D-Mod extraction return string
  # TOTAL_MEMORY=192MB: for Dink and the initial FS (128MB crashes w/o memory growth)
  # ALLOW_MEMORY_GROWTH=0/1: in case there's a large D-Mod; I get performance warnings about FS being copied again but only in debug mode; I get performance / sound lag issues with WASM=0 though
  # --use-preload-cache: stores the large .data in a IndexDB cache (invalidates when .data uuid changes aka at each new upload)
  ln -nfs freedink src/freedink.bc
  # avoid regenerating the tarball (and forcing a re-download) each time
  # base: include sound effects in the base archive (preloaded on startup)
  $FILE_PACKAGER \
    t/freedink-data.data --js-output=t/freedink-data-data.js \
    --preload $PREFIX/../freedink-data/destdir/@/ \
    --exclude '*/usr/share/midi/*' \
    --exclude '*/usr/local/share/dink/dink/Sound/*.ogg' \
    --use-preload-cache
  # the following are loaded separately so the data files are cacheable
  # under Firefox' browser.cache.disk.capacity/8 =~ 43.5MB
  # https://developer.mozilla.org/en-US/docs/Mozilla/Preferences/Mozilla_networking_preferences
  # soundfonts: freepats files - loadable on demand but required to play e.g. a D-Mod intro music
  $FILE_PACKAGER \
    t/soundfonts.data --js-output=t/soundfonts-data.js \
    --preload $PREFIX/../freedink-data/destdir/usr/share/midi/@/usr/share/midi/ \
    --use-preload-cache
  # bgm: .ogg music (loadable on demand)
  $FILE_PACKAGER \
    t/freedink-data-bgm-ogg.data --js-output=t/freedink-data-bgm-ogg-data.js \
    --preload $PREFIX/../freedink-data/destdir/usr/local/share/dink/dink/Sound/@/usr/local/share/dink/dink/Sound/ \
    --exclude '*/usr/local/share/dink/dink/Sound/*.wav' \
    --exclude '*/usr/local/share/dink/dink/Sound/*.mid' \
    --use-preload-cache
  # compile!
  emcc -c -I$PREFIX/include ../emscripten/extract.c -o extract.bc $CFLAGS
  emcc -c -I$PREFIX/include ../emscripten/importexport.c -o importexport.bc $CFLAGS
  emcc src/freedink.bc extract.bc importexport.bc -o t/index.html \
    $LDFLAGS -L$PREFIX/lib -lintl -s USE_SDL=2 -lSDL2_image -lSDL2_ttf -lSDL2_mixer \
      -lvorbisfile -lvorbis -logg -lfreetype -lpng -lzip -lz -lbz2 \
    -s CASE_INSENSITIVE_FS=1 \
    -s FORCE_FILESYSTEM=1 \
    -s TOTAL_MEMORY=192MB -s ALLOW_MEMORY_GROWTH=1 \
    -s EXTRA_EXPORTED_RUNTIME_METHODS='["ccall", "cwrap", "Pointer_stringify", "getValue"]' \
    -s EXPORTED_FUNCTIONS='["_main", "_emDmodExtract", "_emSavegamesImport", "_emSavegamesExport"]' \
    --pre-js ../emscripten/pre.js \
    --post-js ../emscripten/post.js \
    --shell-file ../emscripten/shell.html
  sed -i -e '1ecat' t/index.js <<-EOF
// @license magnet:?xt=urn:btih:1f739d935676111cfff4b4693e3816e664797050&dn=gpl-3.0.txt GPL-3.0
EOF
  echo "// @license-end" >> t/index.js
  mkdir -p t/asmjs/
  emcc src/freedink.bc extract.bc importexport.bc -o t/asmjs/index.html -s WASM=0 \
    $LDFLAGS -L$PREFIX/lib -lintl -lSDL2 -lSDL2_image -lSDL2_ttf -lSDL2_mixer \
      -lvorbisfile -lvorbis -logg -lfreetype -lpng -lzip -lz -lbz2 \
    -s CASE_INSENSITIVE_FS=1 \
    -s FORCE_FILESYSTEM=1 \
    -s TOTAL_MEMORY=256MB -s ALLOW_MEMORY_GROWTH=0 \
    -s EXTRA_EXPORTED_RUNTIME_METHODS='["ccall", "cwrap", "Pointer_stringify", "getValue"]' \
    -s EXPORTED_FUNCTIONS='["_main", "_emDmodExtract", "_emSavegamesImport", "_emSavegamesExport"]' \
    --pre-js ../emscripten/pre.js \
    --post-js ../emscripten/post.js \
    --shell-file ../emscripten/shell.html
  sed -i -e '1ecat' t/asmjs/index.js <<-EOF
// @license magnet:?xt=urn:btih:1f739d935676111cfff4b4693e3816e664797050&dn=gpl-3.0.txt GPL-3.0
EOF
  echo "// @license-end" >> t/asmjs/index.js
  mkdir -p t/source/
  \cp -a ../emscripten/source.html t/source/index.html
  \cp -a ../emscripten/background.jpg t/
  \cp -a ../emscripten/background.jpg t/asmjs/
)

exit 0

# Sample test suite item:
emmake make check; emcc src/TestIOGfxDisplay.bc -o t/test.html "$LDFLAGS" -L$PREFIX/lib -lintl -lSDL2 -lSDL2_image -lSDL2_ttf -lSDL2_mixer       -lvorbisfile -lvorbis -logg -lfreetype -lpng -lz -lbz2     --preload-file $PREFIX/../freedink-data/destdir/@/ --use-preload-cache     -s CASE_INSENSITIVE_FS=1     -s TOTAL_MEMORY=268435456     -s EXTRA_EXPORTED_RUNTIME_METHODS='["ccall", "cwrap", "Pointer_stringify"]'



# Apache
# Compress on the fly -> way too heavy 100% CPU for a single download
# This breaks the download progress bar though
echo <<'EOF' > .htaccess
#SetOutputFilter DEFLATE
#SetEnvIfNoCase Request_URI "\.(?:gif|jpe?g|png)$" no-gzip

#AddType application/wasm .wasm
#AddOutputFilterByType DEFLATE application/wasm
EOF
# Pre-compress -> .data.gz & .wasm.gz & .js.gz ; not .html.gz
# MultiViews does the internal redirection
# Set application/octet-stream otherwise no content negotiation
# RemoteType .gz so it's Content-Type: application/x-gzip doesn't override the base file's
echo <<'EOF' > .htaccess
# Options Multiviews
#RemoveType .gz
AddEncoding x-gzip .gz
AddType application/octet-stream .data
AddType application/octet-stream .em
AddType application/wasm .wasm
EOF


# itch.io: no MultiViews so no automagically appending .gz
# trying by patching the built files...
# index.js.gz -> not supported, no content-encoding, just 'Content-Type: application/gzip' resulting in SyntaxError: illegal character / index.js.gz:1
# index.wasm.gz -> id., "failed to asynchronously prepare wasm: CompileError: wasm validation error: at offset 4: failed to match magic number"
# index.data.gz -> id., corrupted FS
# needs a relative link to source/index.html + a pre-generated index.html


/*
  gcc -ggdb extract.c -lbz2 -o extract -DTEST && ./extract

  emmake make CC=emcc libbz2.a
  touch bzip2 bzip2recover
  emmake make install PREFIX=$HOME/emscripten-prefix

  emcc -I$HOME/emscripten-prefix/include -L$HOME/emscripten-prefix/lib extract.c -o t/extract.html -lbz2 -s EXPORTED_FUNCTIONS='["_emDmodExtract"]' -s EXTRA_EXPORTED_RUNTIME_METHODS='["ccall", "cwrap"]' --preload-file testdmod.dmod -s ALLOW_MEMORY_GROWTH=1 -s TOTAL_MEMORY=268435456

  Module.ccall('emDmodExtract', 'number', ['string','string'], ['testdmod.dmod', '/usr/local/share/dink']);

  new TextDecoder('utf-8').decode(FS.readFile('/usr/local/share/dink/emsources/emscripten/AUTHORS'))

  FS.writeFile('test2.dmod', '')

  reader = new FileReader();
  reader.onload = function(e) { console.log(e.target.result); FS.writeFile('test2.dmod', new Uint8Array(e.target.result)); }
  reader.readAsArrayBuffer(input.files[0])
 */


# LGPL
mkdir -p t/source/
(cd ../../freedink-deps && tar czf gettext-0.19.5-runtime.tar.gz --exclude build gettext-0.19.5/gettext-runtime/)
cp -a ../../freedink-deps/gettext-0.19.5-runtime.tar.gz t/source/
# Reproduce notice along with binaries
cp -a ../../freedink-deps/freetype-2.9/docs/FTL.TXT t/source/freetype-2.9-FTL.TXT
cp -a ../../freedink-deps/libogg-1.3.3/COPYING t/source/libogg-1.3.3-COPYING.txt
cp -a ../../freedink-deps/libvorbis-1.3.6/COPYING t/source/libvorbis-1.3.6-COPYING.txt
cp -a ../../freedink-deps/libpng-1.6.34/LICENSE t/source/libpng-1.6.34-LICENSE.txt
cp -a ../../freedink-deps/glm-0.9.8.5/copying.txt t/source/glm-0.9.8.5-copying.txt
cp -a ../../freedink-deps/libzip-1.5.1/LICENSE t/source/libzip-1.5.1-LICENSE.txt
# SDL*, zlib: no attribution required in binary form (check dependencies though)
# TiMIDIty++ (Artistic/LGPL/GPL) (Artistic too vague and considered ~non-free)
(cd ../../freedink-deps && tar czf SDL2_mixer-2.0.2-timidity.tar.gz SDL2_mixer-2.0.2/timidity/)
cp -a ../../freedink-deps/SDL2_mixer-2.0.2-timidity.tar.gz t/source/SDL2_mixer-2.0.2-timidity.tar.gz
# freepats: GPL but there's no binary form 
zcat /usr/share/doc/freepats/README.gz > t/source/freepats-README.txt
# modplug: public domain
# Dink data:
cp -a ../../freedink-data/COPYING t/source/freedink-data-COPYING.txt
cp -a ../../freedink-data/README.txt t/source/freedink-data-README.txt
# FreeDink data:
#tar czf freedink-data-copyleft.tar.gz freedink-data/src/5.mid/Untitled3.mscz freedink-data/src/7.mid/clockwork.rg freedink-data/src/12.mid/dink-castle.rg freedink-data/src/18.mid/mystery-game.rg
cp -a ../../freedink-data/README-REPLACEMENTS.txt t/source/freedink-data-README-REPLACEMENTS.txt
cp -a ../../freedink-data-copyleft.tar.gz t/source/freedink-data-copyleft.tar.gz
# emscripten
cp -a ../../emsource/emscripten-freedink/LICENSE t/source/emscripten-LICENSE.txt


# GPL :)
cp -a freedink-109.3.tar.gz t/source/

gzip -f t/{freedink-data,freedink-data-bgm-ogg,soundfonts}{.data,-data.js}
gzip -f t/index.{js,wasm}
gzip -f t/asmjs/index.{js,html.mem}
#scp -P2211 -pr t/* freedinkplay@beuc.net:www/
rsync -e 'ssh -p2211' -nav t/* freedinkplay@beuc.net:www/


# SDL2_mixer .ogg music test:
# playmus.c: comment the inner 'while( !next_track...)' loop as well as the CleanUp(0)
# works quite well
echo 'Module.arguments=["test.ogg"];' > post.js
emcc -s USE_SDL=2 -s USE_OGG=1 -s USE_VORBIS=1 playmus.c -o t/playmus.html -I$PREFIX/include -L$PREFIX/lib -lSDL2_mixer --preload-file freedink-data/src/denube.mid/An_der_schönem_blauen_Donau.ogg@test.ogg --post-js post.js
echo 'Module.arguments=["test.wav"];' > post.js
emcc -s USE_SDL=2 -s USE_OGG=1 -s USE_VORBIS=1 playmus.c -o t/playmus.html -I$PREFIX/include -L$PREFIX/lib -lSDL2_mixer --preload-file freedink-data/dink/Sound/wscream.wav@test.wav --post-js post.js
