#!/bin/sh

dh_testdir debian/get-latest-source|| exit 1

suf=dfsg1

version=$2 # can be called from uscan
origTarGz=$3

sourceLinkName=$(curl https://sourcesup.renater.fr/frs/?group_id=379 2>/dev/null | sed -n 's%.*\(/frs/download.php/file/[0-9]*/wims-[0-9][.0-9]*[a-z]*.tgz\)">\(.*\)</a>.*%\1 \2% p'|grep $version)

name=$(echo ${origTarGz}|sed s'%../\(.*\)_\(.*\)\.orig\.tar\.gz%\1-\2%')~${suf}
pkgroot=debian/temp-dir/${name}
wimshome=${pkgroot}/wims

echo name of the package: ${name}

rm -rf debian/temp-dir
mkdir -p ${wimshome}

echo -n untarring wims source...
tar xf ${origTarGz} -C ${wimshome}
echo " [Done]"

#### delete useless files
find ${wimshome} -name "*.bak" | xargs rm -f
find ${wimshome} -name .DS_Store | xargs rm -f
#### delete binaries ###
#### sourceless precompiles binaries
rm -f ${wimshome}/bin/true
rm -f ${wimshome}/bin/false
#### java binary files
find ${wimshome} -name "*.jar" | xargs rm -f
#### flash binaries
rm -f ${wimshome}/public_html/flash/*.swf
#### uglyfied javascript libraries
for d in jquery jsxgraph ; do
    rm -rf ${wimshome}/public_html/scripts/js/$d
done
#### jm.evers' uglyfied javascript files which will be cared during the build
for f in jqmath.js ; do
   rm -f ${wimshome}/public_html/scripts/authors/jm.evers/js/$f
done

#### ASCIIMathML.js and LaTeXMathML.js will be replaced by symlinks
#### during the build
rm -f ${wimshome}/public_html/scripts/js/ASCIIMathML.js \
   ${wimshome}/public_html/scripts/js/LaTeXMathML.js

#### mootools.js will be replaced by symlinks during the build
rm -f ${wimshome}/public_html/scripts/js/editor/scripts_1/mootools.js

#### ensure that dfsg-scripts patch is applied
quilt push -a

#### jquery.mb.extruder will be taken from github
/bin/sh dfsg-scripts/jquery.mb.extruder.sh --makesrc ${pkgroot}

#### what-input will be taken from github
/bin/sh dfsg-scripts/what-input.sh --makesrc ${pkgroot}

### delete symbols which will be generated during the post-installation ###
rm  -f ${wimshome}/public_html/gifs/symbols/20/*.gif

############## remove edit-area's uglified javascript
/bin/sh dfsg-scripts/edit_area.sh --makesrc ${pkgroot}

############## prettify deployggb.js
/bin/sh dfsg-scripts/geogebra.sh --makesrc ${pkgroot}

### create the new orig.tar.gz file ###

srcpackage=wims_${version}~${suf}.orig.tar.gz

(cd debian/temp-dir && tar pcf - ${name} | gzip -9 - > ../../../${srcpackage})

echo "Created ../${srcpackage}"

rm -rf debian/temp-dir

### remove applied patches
quilt pop -a
