#!/bin/bash

#z="http://spring.unknown-files.net/file/1715/Plateau_Divide_v3/"
z=$1

curl -s $z > tmp/page.html
mirror=`cat tmp/page.html | awk '/form name/,/\/form/ {print $0}' | grep hidden | grep value | sed -e 's/value=./\n/g' | grep -v input | sed -e 's/.>$//g'`

echo $mirror
mirror_array=($mirror)
nummir=`expr $RANDOM % ${#mirror_array[@]}`

selected_mirror=${mirror_array[$nummir]}

url=`wget -S --post-data="Download=Download&id=$selected_mirror" http://spring.unknown-files.net/page/getfile/ -O /dev/null 2>&1 | grep Refresh | sed -e 's/url=/\n/g' | grep http`
md5sum=`echo $url | sed -e 's/md5=/\n/g' | tail -n 1`
mapname=`echo $url | sed -e 's/&md5=/\n/g' | grep file | sed -e 's/file=/file\n/g' | grep -v file`

echo $url
echo "Mapname        : $mapname"
echo "Md5sum         : $md5sum"
echo "Selected mirror: $selected_mirror"

echo ""
echo "Downloading $mapname in 5 seconds"
sleep 5

curl "${url}" > tmp/${mapname}
md5sum tmp/${mapname}
echo ${md5sum}
if [ "${md5sum}" == "`md5sum tmp/${mapname} | awk '{print $1}'`" ]; then
    echo "md5sum matches"
    echo "move tmp/${mapname} to ~/.spring/maps/"
    mv tmp/${mapname} ~/.spring/maps/
fi
