#!/bin/sh

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

suf=dfsg1

if [ $# -lt 1 ]; then
    echo the suffix of repackaged file will be dfsg1.
    echo if you want some other suffix, please give it as an argument
    echo
else
    suf=$1
fi

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'|sort -k 2| tail -1)

link=$(echo ${sourceLinkName}| awk '{print $1}')
name=$(echo ${sourceLinkName}| awk '{print $2}')
name=$(echo ${name} | sed s/.tgz//)~${suf}
version=$(echo ${name} | sed s/wims-//)
wimshome=debian/temp-dir/${name}/wims

echo URL to download from: https://sourcesup.cru.fr${link}
echo name of the package: ${name}

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

echo -n Downloading wims source...
curl https://sourcesup.renater.fr${link} 2>/dev/null | gzip -cd | tar xf - -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
#### uglyfied javascript files
for f in jqmath.js ; do
   rm -f ${wimshome}/public_html/scripts/authors/jm.evers/js/$f
done

rm -f ${wimshome}/public_html/scripts/js/ASCIIMathML.js \
   ${wimshome}/public_html/scripts/js/LaTeXMathML.js

rm -f ${wimshome}/public_html/scripts/js/editor/scripts_1/mootools.js

rm -rf ${wimshome}/public_html/scripts/js/bower_components/jquery.mb.extruder
rm -rf ${wimshome}/public_html/scripts/js/bower_components/what-input

### 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
rm -f ${wimshome}/public_html/scripts/js/edit_area/*full*


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

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

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

echo "Created ../${srcpackage}"

rm -rf debian/temp-dir
