#!/bin/sh
#
# For move old packages to old dir
# copy it to /var/cache/apt/arcvives
# and if need run it :-)

LOG=0rmlist.log
ERR=0rmerror.log
OLD=old
RPMERR=0rpmerr.log

mkdir -p old

genlist()
{
   #rm_list=""
   Ver_old="0"
   Rel_old="0"
   pack_old=""
   Name0=$1
   ver_res=0
   rel_res=0
      
   for j in ${Name0}_*.rpm
   do
    #echo $j
    
     if [ ! -f $j ] ; then 
      return
     fi
     
     Name=`rpm -qp $j --queryformat %{NAME} 2>>$RPMERR`
     Ver_current=`rpm -qp $j --queryformat %{VERSION} 2>>$RPMERR` 
     Rel_current=`rpm -qp $j --queryformat %{RELEASE} 2>>$RPMERR`
     ver_res=`rpmvercmp $Ver_current $Ver_old`
     rel_res=`rpmvercmp $Rel_current $Rel_old`
     #echo "rpmvercmp $Ver_current $Ver_old"
     if [ "$ver_res" -gt 0 ] ; then
       Ver_old=$Ver_current         
       rmlist="$rmlist $pack_old"
       #echo 1 - $rmlist
     elif [ "$ver_res" -lt 0 ] ; then
       rmlist="$rmlist $j"
     elif [ "$ver_res" -eq 0 ] ; then
       if [ "$rel_res" -gt 0 ] ; then
          Rel_old=$Rel_current  
	  rmlist="$rmlist $pack_old"       
       elif [ "$rel_res" -lt 0 ] ; then
          rmlist="$rmlist $j"
       elif [ "$rel_res" -eq 0 ] ; then             
       echo ERROR!!!!!!!!
       exit
      fi             
     fi
     pack_old=$j
     
     #echo $Name
     #echo $Ver_current
     #echo $Rel_current
     
   done
   
   #echo $rmlist
}


dublicate()
{
Name=""
rmlist=""
flag=0

for i in *.rpm 
do

if [ ! -f $i ] ; then 
  continue
fi


Name0=`rpm -qp $i --queryformat %{NAME} | sed -e s/_/%5f/g 2>>$ERR` 
#echo --------Name0=$Name0 -- Name=$Name-------------------
echo $i


if [ "$Name0" = "$Name" ];  then

   if [ "$flag" = "1" ] ; then     
    continue
   fi
   
   echo ------------$Name0----------------   >>$LOG
   genlist $Name0
   echo RMLIST IS: $rmlist >>$LOG
   mv $rmlist $OLD 2>>$ERR
   rmlist=""      
   echo ----------------------------------------- >>$LOG  
   flag=1
else
 flag=0
fi

Name=$Name0


done
#exit
}

#-------------------------------------------------------------
# main()

date >>$LOG

dublicate

#exit

