#!/bin/bash

function dl_if_needed() {
	local TARGET="$1"
	local LINK="$2"
	local FILENAME=$(basename $TARGET)

	[ -e "$TARGET" ] && return;

	local EXISTING=$(find . -name "$FILENAME" -type f)
	if [ ! -z "$EXISTING" ]; then
		RELPATH=$(dirname $TARGET | sed -e 's|[^/]*|..|g')
		ln -s $(echo "$EXISTING" | sed -e "s|^\.|$RELPATH|g") "$TARGET"
		return;
	fi
	wget -q -O "$TARGET" "$LINK"
}

#curl https://web.archive.org/web/20180116225033/http://www.supermicro.com:80/support/resources/bios_ipmi.php | \
cat bios_ipmi.php | \
	grep '<tr>	<td align="left">' | sed -e 's:<tr>::g' -e 's:</tr>:\n:g' -e 's:</td>:|:g' -e 's:<td align="[^"]*">:|:g' -e 's:</a><br><a:</a>;<a:g' -e 's:<br>::g' | \
while IFS='$\n' read -r line; do
	DATA=$(echo $line | sed -re 's:<a href="[^"]*">([^<]*)</a>:\1:g' | \
		sed -re 's:<a href="([^"]*\.cfm\?[^"]*)" target="_blank">([^<]*)</a>:\1 \2:g' | \
		sed -re 's: *\| *:|:g' | \
		sed -e 's:||*:|:g' | \
		sed -e 's:&amp;:\&:g' | \
		sed -re 's:<font[^>]*>([^<]*)</font>:\1:g')

	TYPE=$(echo $DATA | cut -f6 -d '|')
	if [[ "$TYPE" == BIOS* ]]; then
		TYPE="BIOS"
	elif [[ "$TYPE" == IPMI* ]]; then
		TYPE="IPMI"
	fi
	[ "$TYPE" != "BIOS" ] && [ "$TYPE" != "IPMI" ] && continue;

	BOARDS=$(echo $DATA | cut -f2 -d '|')
	LINK=$(echo $DATA | cut -f4 -d '|')
	RELNOTES=$(echo $DATA | cut -f5 -d '|')
	REV=$(echo $DATA | cut -f3 -d '|' | sed 's/^R //g')

	# Only X10 series
	[[ "$BOARDS" != X10* ]] && continue;

	for BOARD in $(echo $BOARDS | sed 's/;/ /g'); do
		mkdir -p $TYPE/$BOARD/$REV
		dl_if_needed $TYPE/$BOARD/$REV/$(echo $LINK | cut -f2 -d ' ') $(echo $LINK | cut -f1 -d ' ' | sed -re 's|.*disclaimer\.cfm|https://www.supermicro.com/support/resources/getfile.php|g')
		if [ ! -z "$(echo $RELNOTES | cut -f2 -d ' ')" ] && [ -z "$(echo $RELNOTES | cut -f2 -d ' ' | grep disclaimer.cfm)" ]; then
			dl_if_needed $TYPE/$BOARD/$REV/$(echo $RELNOTES | cut -f2 -d ' ') $(echo $RELNOTES | cut -f1 -d ' ' | sed -re 's|.*disclaimer\.cfm|https://www.supermicro.com/support/resources/getfile.php|g')
		fi
	done
done
