#!/bin/bash

URL="https://mibbrowser.online/mibs"
#WORKDIR=/dev/shm
WORKDIR=$(pwd)
DELAY=${WORKDIR}/sleep.time

# SSH servers list for work
SERVER=(
s1
s2
s3
s4
s5
s6
s7
)

LIST=$(mktemp -p ${WORKDIR})
O2=$(mktemp -p ${WORKDIR})

[ ! -f $DELAY ] && echo 10 > $DELAY

wget -q -O $LIST "https://mibbrowser.online/mibdb_search.php?all=1"
[ $? -ne 0 ] && echo "Can't download MIB list" && exit 1
[ ! -s $LIST ] && echo "URL file is empty" && exit 1
[ ! -d ${WORKDIR}/mibs ] && mkdir -p ${WORKDIR}/mibs

cat $LIST | \
	sed -e 's/<a href=/\n<a href=/g' -e 's!</a><br>!</a><br>\n!g' | \
	grep "\"mibdb_search.php?mib=" | \
	sed 's!<a href="mibdb_search.php?mib=\(.*\)" >.*</a><br>!\1!g' \
	> ${LIST}-rez

S=0
for MIB in $(cat ${LIST}-rez); do
	[ -z "$MIB" ] && continue
	[ -s ${WORKDIR}/mibs/$MIB.mib ] && continue
	UUID=$(cat /proc/sys/kernel/random/uuid)
	SLEEP=$(cat $DELAY)

	FAIL=0
	SKIP=0
	while [ 1 ]; do
		[ $S -ge ${#SERVER[@]} ] && S=0
		ssh ${SERVER[S]} "wget -q -O - $URL/$MIB.mib" 1> ${WORKDIR}/$UUID.mib 2> $O2
		if [ $? -ne 0 ]; then
			echo "Failed wget on ${SERVER[S]} with $MIB"
			cat $O2
			if grep -q 404 $O2 ; then
				echo "!!! get 404 for $MIB"
				rm -f ${WORKDIR}/$UUID.mib
				SKIP=1
			else
				FAIL=1
			fi
		else
			[ -s ${WORKDIR}/$UUID.mib ] \
				&& mv ${WORKDIR}/$UUID.mib ${WORKDIR}/mibs/$MIB.mib \
				&& echo "Load $MIB.mib via ${SERVER[S]}"
		fi
		S=$((S+1))
		[ $FAIL -eq 0 -o $SKIP -eq 1 ] && break
	done

	if [ $SLEEP -gt 0 ]; then
		echo "Sleep $SLEEP"
		sleep $SLEEP
	fi
done

rm ${LIST} ${LIST}-rez $O2
