#!/bin/bash
# Author: Steven Shiau <steven _at_ nchc org tw>
# License: GPL
# Description: This program is used to parse the latest Clonezilla live on the sourceforge repository.
#
DRBL_SCRIPT_PATH="${DRBL_SCRIPT_PATH:-/opt/drbl/}"

. $DRBL_SCRIPT_PATH/sbin/drbl-conf-functions

#
branches="stable testing alternative alternative_testing"
#
query_branch() {
  local i="$1"
  cz_tmp="$(mktemp /tmp/cz_ver.XXXXXX)"
  wget --quiet -O $cz_tmp http://sourceforge.net/projects/clonezilla/files/clonezilla_live_$i
  # The output to grep -iEo "clonezilla-live-.*.iso" might give results:
  # ====================
  # clonezilla-live-20101003-maverick.iso?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fclonezilla%2Ffiles%2Fclonezilla_live_stable%2F&amp;ts=1286159760&#39; }" href="http://sourceforge.net/projects/clonezilla/files/clonezilla_live_alternative_testing/20101003-maverick/clonezilla-live-20101003-maverick.iso/download" title="/clonezilla_live_alternative_testing/20101003-maverick/clonezilla-live-20101003-maverick.iso
  # clonezilla-live-1.2.6-24-i686.iso
  # ====================
  # We have skip the 1st one.
  cz_ver="$(LC_ALL=C grep -iEo "clonezilla-live-.*.iso" $cz_tmp | grep -Ev "(http|\?|\&|%)" | pkg-ver-latest | sed -r -e "s/^clonezilla-live-//g" -e "s/-(486|686|i486|i686|amd64)//g" -e "s/\.iso//g" -e "s/-nk$//g")"
  [ -e "$cz_tmp" ] && rm -f $cz_tmp
}
#
USAGE() {
  echo "Usage: $0 branch" 1>&2
  echo "Where branch is one of:" 1>&2
  echo "$branches" 1>&2
}

branch="$1"
if [ -z "$branch" ]; then
  echo "No branch specified!" 1>&2
  USAGE
  exit 1
fi
if [ -z "$(echo "$branches" | grep -wE "$branch")" ]; then
  echo "\"$branch\" is not an appropriate branch!" 1>&2
  USAGE
  exit 1
fi
query_branch $branch
if [ -n "$cz_ver" ]; then
  echo "$cz_ver"
  rc=0
else
  rc=1
fi

exit $rc
