#!/bin/bash

usage()
{
	echo "Usage $0 script"
	echo "$0 download_filename.iso inputfile.iso"
	echo "	Where inputfile.iso is the file you already have that's similar to the one you download"
	echo
	echo "$0 download_filename.iso"
	echo "	This command format will search automatically for the most recent MX*x64.iso file in the current folder"
	exit
}

[[ "$1" == "--help" || "$1" == "-h" ]] && usage


TARGET="$1"
[[ -z "$1" ]] && {
	echo "You need to specify a file name to download. exiting..."
	echo
	usage
}
echo "Downloading \"$1\" file"

grep "x64" <<< "$1" && ARCH="x64" || ARCH="386"

# add available local ISO-sources here - newest first
# check latest ISO-sources are available
SOURCE="$2"

[[ -f "$SOURCE" ]] && echo "Using input file:" "$SOURCE" || {
	[[ "$SOURCE" == "" ]] && echo "Input source not specified, trying to find a useful ISO in current path"
	[[ "$SOURCE" != "" ]] && echo "Input file \"$SOURCE\" not found, trying to find a useful ISO in current path"
	SOURCE=$(find . -iname "MX*$ARCH*.iso" -printf "%T+\t%p\n" | sort -r | head -1 | cut -f2)
	[[ "$SOURCE" != "" ]] && echo "Using "$SOURCE" source file" || {
		echo "Could not found an appropriate input file, exiting..."
		echo
		usage
	}
}

# do we have zsync
command -v zsync >&- || {
	# opps we need to and install zsync
	sudo apt-get update
	sudo apt-get install zsync
}

ZSYNC="${TARGET}".zsync

# get closest sourceforge server for zsync
DOWNLD=https://sourceforge.net/projects/mx-linux/files/Snapshots/Community_Respins/"${ZSYNC}"/download
SPIDER=$(wget -nv --spider "${DOWNLD}" 2>&1 | grep -Eo https.*iso.zsync | sed 's/https/http/')

[[ -z "$SPIDER" ]] && {
	 echo; echo "Could not find \"$1\" file on SourceForge server, please check the name. Exiting..."
	 echo
	 usage
}

# let's do zsync
[[ -f "${TARGET}" ]] || echo; echo "Executing zsync command"; zsync -i "$SOURCE" "${SPIDER}" || {
	echo
	usage
}

