#!/bin/sh
set -e

# I can no longer ship all the rdp_classifier data in the DEB package.  This script
# will help you install it.
enterkey() {
    read -p "Press ENTER to continue, Ctrl+C to exit..." -r ignored
    echo
}

if echo "$*" | grep -wq -- --here ; then
    echo "Downloading to ./classifier as --here was specified."
elif [ "`id -u`" = 0 ] ; then
    echo "Data will be downloaded to /usr/share/rdp-classifier/data/classifier"
    cd /usr/share/rdp-classifier
    umask 022
    enterkey
else
    echo "Data will be downloaded to $HOME/rdp_classifier/data/classifier"
    enterkey
    mkdir -p "$HOME/rdp_classifier/data/classifier"
    cd "$HOME/rdp_classifier/data/classifier"
    cd ../..
fi

# Fetch the fungal data into the [data/]classifier directory in the current directory.
# The following only really makes sense if --here was set.
classifier=classifier
if [ ! -d $classifier ] ; then
    classifier=data/classifier
    if [ ! -d $classifier ] ; then
	echo "There is no data/classifier subdirectory here."
	echo "You normally want to run this in /usr/share/rdp-classifier/."
	exit 1
    fi
fi

#Let us fetch!
#This version of the URL does not bounce us back to sf.net, which is good.
zip_url='http://www.mirrorservice.org/sites/download.sourceforge.net/pub/sourceforge/r/rd/rdp-classifier/rdp-classifier/rdp_classifier_2.9.zip'
zip_file=`echo "$zip_url" | sed 's,.*/,,'`

#If the file was already there then this script probably shouldn't delete it.
file_was_already_there=no
if [ -e "$zip_file" ] ; then
    file_was_already_there=yes
fi

tmpdir=`mktemp -d ./tmp.XXXX`
[ "${tmpdir#./}" != "$tmpdir" ]
cd $tmpdir ; cd ..   #Be really sure we really made the tmpdir.

# It would be nice to grab rdp_classifier_2.9.zip and unzip it on the fly, but this can't be done
# as zip files have the crucial info at the end, so we do need to save the file, and likewise the
# .jar file
wget -c "$zip_url"
cd $tmpdir
unzip -j ../"$zip_file" '*/dist/classifier.jar'
[ $file_was_already_there = no ] && rm ../"$zip_file"
jar xvf classifier.jar 'data/classifier'

#At this point, I want to overwrite files not found in a package but leave packaged files.
echo "Scrubbing non-package-owned files from $classifier"

# Note - this is not robust.
# Also this looks like the kind of one-liner that can eat your precious files if there
# is some small bug in this script.
# find "`readlink -e ../"$classifier"`" -type f -print0 | xargs -0 dpkg-query -S 2>&1 >/dev/null | sed 's,[^/]*,,' \
#     | xargs -r -d'\n' rm -v --

# Yeah, here is a better looking one:
find "`readlink -e ../"$classifier"`" -type f \( -exec dpkg-query -S '{}' ';' -or -delete \) >/dev/null

echo "Copying in new data files."
cp -vrn data/classifier ../"$classifier"/..
cd ..

rm -r $tmpdir

echo DONE
