#!/bin/sh
# Author: Steven Shiau <steven _at_ nchc org tw>
# License: GPL
# Description: Find the url in yum repository setting.
# parameter: yum_repo_set releasever ARCH

yum_repo_set="$1"
# TODO! find a method to get this
releasever="$2"
#basearch="$3"
ARCH="$3"

[ -f "$yum_repo_set" ] || exit 1
[ -n "$releasever" ] || exit 1
[ -n "$ARCH" ] || exit 1

get_yum_block() {
     local CFG_FILE=$1
     local block="$2"
     [ -f "$CFG_FILE" ] || exit 1
     # By using
     # grep -n "^\[.*\]" yum.conf |grep -A1 "\[base\]"                 
     # We can get the results like:
     # 175:[base]
     # 210:[update]
     # so we know we can replace the one between line no. 175 and 210
     between_lines=$(grep -ni "^\[.*\]" $CFG_FILE |grep -i -A1 "\[$block\]" | cut -d":" -f1)
     begin_line=$(echo $between_lines | awk -F" " '{print $1}')
     end_line=$(echo $between_lines | awk -F" " '{print $2}')
     # if end_line is nothing, it must be the last block, i.e. we can not find the next [.*]
     if [ -z "$end_line" ]; then
       end_line=$(wc -l $CFG_FILE | awk -F" " '{print $1}')
     else
       # if not nothing, backword one line
       end_line=$(($end_line - 1))
     fi
     echo "$begin_line $end_line"
}

#
convert_url_os_path() {
  local url="$1"
  [ -n "$url" ] || exit 1
  # url_os_coreroot="$url_os/fedora/linux/core/"
  # os_ayo_path="fedora/apt/fedora/linux/$FC_VER/i386"
  url_os_coreroot="$(echo $baseurl | sed -e "s|\$releasever/.*||g")"
  os_ayo_path="$(echo $url_os_coreroot | sed -re "s|(http\|ftp)://[^/]*/||g")"
  url_os="$(echo $url_os_coreroot | sed -e "s|$os_ayo_path||g")"
  # strip the /$releasever/$ARCH/os if found...
  os_ayo_path="$(echo $os_ayo_path | sed -re "s|/$releasever/$ARCH/.*||g")"
  echo $url_os $os_ayo_path
}

# for yum
lines="$(get_yum_block $yum_repo_set base)"
begin_line=$(echo $lines | awk -F" " '{print $1}')
end_line=$(echo $lines | awk -F" " '{print $2}')
chk_cmd="if ($begin_line..$end_line) {print}"
baseurl="$(perl -n -e "$chk_cmd" $yum_repo_set | grep -Ei "^[[:space:]]*baseurl=" | sed -e "s/^[[:space:]]*baseurl=//gi")"
if [ -n "$baseurl" ]; then
  # case 1, baseurl exists
  convert_url_os_path $baseurl
else
  # try to find mirrorlist
  mirrorlist="$(perl -n -e "$chk_cmd" $yum_repo_set | grep -Ei "^[[:space:]]*mirrorlist=" | sed -e "s/^[[:space:]]*mirrorlist=//gi")"
  eval mirrorlist=$mirrorlist
  # use wget or lynx ? wget is almost installed...
  #tmp_dir="$(mktemp -d /tmp/yummirror_tmp.XXXXXX)"
  #wget -r -l1 --no-parent --passive-ftp -e robots=off -q -nd --retr-symlinks -P "$tmp_dir" $mirrorlist
  #mirror_file=`basename $mirrorlist`
  #baseurl="$(head -n 1 $tmp_dir/$mirror_file)"
  #[ -d "$tmp_dir" ] && rm -rf $tmp_dir
  baseurl="$(lynx -dump $mirrorlist | head -n1)"
  eval baseurl=$baseurl
  convert_url_os_path $baseurl
fi
