#!/bin/bash
#
# General options
IMAGE_PATH='/usr/share/mirrorbrain/famfamfam_flag_icons/png'
HEADER_FILE='/home/mirrorbrain/openSUSE_html_header'
TARGET_PATH='/srv/www/vhosts/mirrors.opensuse.org'
TIMESTAMP_FILE="$TARGET_PATH/.timestamp"
CONFIG='/etc/sysconfig/mirrorbrain-webpages'
FILTER_REGEX_0=''
TITLE_REGEX_0='All Mirrors'
CAPTION_REGEX_0='All Mirrors from this MirrorBrain instance. Please choose the closest one to your location.'
DO_ECHO=''
MB='/usr/bin/mb'
#
# Le's overwrite them
if [ -r "$CONFIG" ]; then
	. "$CONFIG"
else
	echo "ERROR: Could not read $CONFIG" >&2
	exit 1
fi
#
# Test if everything is setup to start...
test -d "$IMAGE_PATH"  || {
	echo "$IMAGE_PATH not found" >&2
	exit 1
}
test -r "$HEADER_FILE" || {
	echo "$HEADER_FILE does not exist or is not readable" >&2
	exit 1
}
test -d "$TARGET_PATH" || {
	echo "$TARGET_PATH does not exist - creating now" >&2
	mkdir -p "$TARGET_PATH" || exit 1
} 

ARGS_COMMON="-f xhtml -H $HEADER_FILE -I $IMAGE_PATH"
ARGS_COMMON_TXT="-f txt"

for i in {0..99}; do
    regex=FILTER_REGEX_$i
    eval regex=\$$regex
    title=TITLE_REGEX_$i
    eval title=\$$title
    caption=CAPTION_REGEX_$i
    eval caption=\$$caption
    skip_empty=SKIP_EMPTY_REGEX_$i
    eval skip_empty=\$$skip_empty
    if [ -n "$title" ]; then
		case $regex in
			'')
				output='all'
				FILTER=''
			;;
			*)
				output=$(echo ${regex} | tr '[:upper:]' '[:lower:]')
				FILTER="-F ${regex}"
			;;
		esac
		case $skip_empty in
			[Yy][Ee][Ss]) SKIP='-s' ;;
			*) SKIP='' ;;
		esac
		$DO_ECHO $MB mirrorlist $ARGS_COMMON $FILTER $SKIP -t "$title" -c "$caption" -o "$TARGET_PATH/${output}.html"
		$DO_ECHO $MB mirrorlist $ARGS_COMMON_TXT $FILTER $SKIP -o "$TARGET_PATH/${output}.txt"
		unset regex
	fi
done
date +"%Y-%m-%d %H:%M:%S" > "$TIMESTAMP_FILE"

