#!/bin/bash

rpmsort () {
local unsorted str1 str2 tmp tmpo tmpe lines i
tmpo="$(mktemp tmp.XXX)"
tmpe="$(mktemp tmp.XXX)"
unsorted=1
while ((unsorted)); do
  unsorted=0
  str2=
  lines="$(sed -n "$=" "$1")"
  for ((i=1; i<=lines; i++)); do
    str1="$(sed "$i"'!d' "$1")"
    [ -z "$str1" ] && continue
    if [ -z "$str2" ]; then
      str2="$str1"
      continue
    fi
    if [ "$(rpmevrcmp "$str1" "$str2")" -gt 0 ]; then
      unsorted=1
#       echo "tmpo"
      echo "$str1" >> "$tmpo"
    else
#       echo "tmpo"
      echo "$str2" >> "$tmpo"
      str2="$str1"
    fi
#       echo "tmpe"
    echo "$str2" > "$tmpe"
  done
  echo "$str2" >> "$tmpo"
  cat "$tmpo" >"$1"
  :>"$tmpo"
done
rm -f "$tmpo" "$tmpe"
}

prn () {
  local lines i str1 str2 con tmp
#   echo -n "$(sed '1!d' "$1")"
  lines="$(sed -n "$=" "$1")"
  for ((i=1; i<=lines; i++)); do
    str1="$(sed "$i"'!d' "$1")"
    [ -z "$str1" ] && continue
    if [ -z "$str2" ]; then
      str2="$str1"
      continue
    fi
    echo -n "$str2"
    con="$(rpmevrcmp "$str1" "$str2")"
#    tmp=">=<"
#    echo -n "${tmp:con+1:1}"
     [ "$con" -lt 0 ] && echo -n ">"
     [ "$con" -eq 0 ] && echo -n "="
     [ "$con" -gt 0 ] && echo -n "<"
    str2="$str1"
  done
  echo "$str2"
}

tmp="$(mktemp tmp.XXX)"
tmpa="$(mktemp tmp.XXX)"
tmpo="$(mktemp tmp.XXX)"
for rel in alt1.10 alt1.p3 alt1.9 alt1.9.1 alt1.10.1 alt1.svn20090812 alt1.svn20090812.10 alt1.10.1 alt1.svn20090812.11; do
  echo -n "$rel: "
  :>"$tmp"
  for br in "" M50 M41 M40; do
    for ((branch_release_num=1;branch_release_num<=2;branch_release_num++)); do
      rpm --define "branch_release_num \"$branch_release_num\"" --define "branch_switch \"$br\"" --eval "%branch_release $rel" >>"$tmp"
    done
  done
  rpmsort "$tmp"
  prn "$tmp"
  echo
# sed ':a;N;s/\n/ /;ta' "$tmp"
  cat "$tmpa" "$tmp" > "$tmpo"
  cp -f "$tmpo" "$tmpa"
done

rpmsort "$tmpo"
prn "$tmpo"
echo

cat <<EOF >"$tmp"
alt1.10
alt0.10.M50.1
alt0.10.M41.1
alt0.10.M40.1
alt0.10.M50.2
alt0.10.M41.2
alt0.10.M40.2

EOF
rpmsort "$tmp"
prn "$tmp"
echo

rm -f "$tmp" "$tmpo" "$tmpa"
exit

file /var/www/html/lightsquid/user_month.cgi from install of lightsquid-admin-1.8.0.1-alt2.11 conflicts with file from package lightsquid-1.8-alt2
