#!/bin/bash 
# copyright: copyleft;  Diego.Saravia@gmail.com 2010
# upackname 
# works in bash and busybox

UPACKNAME_PROG_NAME=upackname
UPACKNAME_PROG_VERSION=0.1
UPACKNAME_PROG_LICENCE="AGPLv3+: GNU AGPL version 3 or later"


# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU  Affero General Public License as published by
# the Free Software Foundation; last version,  from 3 to  any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#



########################################################################### Configuration vars

upackname_vars(){
UPACKNAMESOURCED=1

if test x"$DIRBIN" = x ; then
 DIRBIN=$(summabase)
fi


#USER=`whoami`
#USER=dsa
#DIRBIN=/home/$USER/dsatex/ubuild/scripts
if test x"$SUMMABASESOURCED" != 1; then
  source $DIRBIN/summabase source
  summabase_vars
  msg 9 "Carga summabase en upackname"
fi

}

########################################################################### version
upackname_version(){
cat <<EOF
$UPACKNAME_PROG_NAME $UPACKNAME_PROG_VERSION
Copyright (C) 2010 Diego Saravia <dsa@unsa.edu.ar>
License: $UPACKNAME_PROG_LICENCE
<http://gnu.org/licenses/gpl.html>
EOF
}

########################################################################### usage

upackname_usage(){
cat <<EOF
Usage:
    upackname  PACKAGE
EOF
}

########################################################################### help
upackname_help(){
cat <<EOF
    upackname [-o] PACKAGE [REFPACK]

    Splits package string in name, version and extension
    
    If REFPACK, reports what is newer.
   
    REFPACK must be in canonical way
   
    -o print summary, only canonical name and order 
 
    upackname -o beagle-0.3.7-r1.tbz2 beagle_0.3.8_5.0__tbz2

    Prints
    PACKSTRING:  Complete file name
    PACKDIR:     Directories preceding file name
    PACKTYPE:    NOEXT|UNKNOWNPKGEXT|BINPKGEXT|LISTEXT|METAEXT 
    PACKEXT:     Extension (rpm, deb, ebuild, tbz2, etc)
    PACKSYSTEM:  i686, x86_64, hurd-i386, etc
    PACKNAME:    Packname
    PACKSUB:     Package Subtype (included, not separated from PACKNAME).
    PACKVERSION: Complete version
    PACKSV:      Source Version
    PACKRV:      Release Version   
    PACKRVORDER: Release Version in Gentoo transformed for comparisson.  
    PACKORIGIN:  Who makes the package (suse, redhat, ututo, etc), not usually detected
    PACKCOMPLETENAME:           without extension
    PACKCANONICALNAME: without extension in a normalized fashion

 if REFPACK

    ORDER:  -1, 0, 1 which version is first PACKAGE or REFPACK
              0: same version
             -1: PACKAGE is older, smaller version
              1: PACKAGE is newer, bigger version
    COMPPN:  REFPACK name
    COMPPV:  REFPACK version
    COMPPR:  REFPACK release
    COMPPS:  REFPACK system
    COMPPE:  REFPACK extension
    COMPPO:  REFPACK origin

Source

    upackname source, do nothing and aloud:
 
    source upackname source
    
    to use upackname funcionts, like: 

    upackname_main /ops/tar-doc-1.22-mdv2009.i386.rpm

Test
   
   pruebaupackname.pl ordena una lista de archivos
   
EOF
}
# si refpack no esta en forma canonica transformar
# resolver el caso de no deteccion en expresiones regulares con MM=

########################################################################### readcan

readcan(){
# puede ir a summabase.sh

local canonical=$1

local __var1=$2
local __var2=$3
local __var3=$4
local __var4=$5
local __var5=$6
local __var6=$7
local __var7=$8
local __var8=$9

# AGREGAR FILETYPE A CANONICAL PARA FACILITAR FILE INFO

`echo $canonical | sed -e 's/\(.*\)_\(.*\)_\(.*\)_\(.*\)_\(.*\)_\(.*\)_\(.*\)_\(.*\)$/export COMPPN\=\1 COMPPSUB=\2 COMPPV\=\3 COMPPR\=\4 PCOMPPS\=\5 COMPOR=\6 PCOMPPST\=\7 COMPPE\=\8/'`
# cambiar esto es feo de manejar los errores
if test x"$?" != x0 ;  then
       ERRORBYPASS="$ERRORBYPASS Error, variable $canonical is not canonical."
fi

#By default, $? only captures the exit status of the last command to run in a pipeline.
#A couple options:
#1. Put "set -o pipefail" near the start of your script, then $? will return any non-zero exit status from anywhere in the pipe.
#2. man bash. Look at the $PIPESTATUS array, if you actually want to be able to differentiate which command in the pipeline failed. 

COMPPST=`echo $PCOMPPST| sed -e 's/---/_/'`
COMPPS=`echo $PCOMPPS| tr . _`

eval $__var1="'$COMPPN'"
eval $__var2="'$COMPPSUB'"
eval $__var3="'$COMPPV'"
eval $__var4="'$COMPPR'"
eval $__var5="'$COMPPS'"
eval $__var6="'$COMPOR'"
eval $__var7="'$COMPPST'"
eval $__var8="'$COMPPE'"
}



#echo MMMMMMMMMM $ZZZ
#COMPPN
#COMPPSUB
#COMPPV
#COMPPR
#COMPPS
#COMPOR
#COMPPST
#COMPPE
#PACKNAME=$COMPPN
#PACKSUB=$COMPPSUB
#PACKSV=$COMPPV
#PACKRVORDER=$COMPPR
#PACKSYSTEM=$COMPPS
#PACKORIGIN=$COMPOR
#PACKSTRING=$COMPPST
#PACKEXT=$COMPPE


########################################################################### extsep

extsep(){
local PACKSTRING=$1

#devuelve PACKNOEXT PACKEXT PACKTYPE

#echo 1 $PACKEXT - $PACKNOEXT - $PACKSTRING - $PACKTYPE

# paquetes genericos con archivos
PACKTYPE=''
PACKNOEXT=$(echo $PACKSTRING| sed -e 's/\.\(tar\.gz\|tar\.bz\|tar\.bz2\|gz\|tar\|ZIP\|zip\|jar\|Z\|z\|bz2\|bz\|7Z\|7z\|RAR\|rar\|LHa\|LHA\|lha\|lzh\|a\|lzma\)$//')
#export PACKNOEXT\=\1 PACKEXT\=\2 PACKTYPE\=FILESET
# finalmente seran denominados FILESET

#echo 2 $PACKEXT - $PACKNOEXT - $PACKSTRING - $PACKTYPE

# paquetes con archivos  especiales, algunos fuentes otros binarios 
###########33 OJO NO FUNCIONA CON tar.bz2 usar metodo de arriba, mejorar todo esto
if test x"$PACKNOEXT" = x"$PACKSTRING" ; then 
   PACKEXT=$(echo $PACKSTRING| sed -e 's/\(.*\)\.\(src\.rpm\)$/\2/')
   if test x"$PACKEXT" = x"$PACKSTRING" ; then 
     PACKEXT=$(echo $PACKSTRING| sed -e 's/\(.*\)\.\(tbz2\|tgz\|txz\|deb\|rpm\)$/\2/')
   fi
   # seran PMS
   #echo MMMMM $PACKEXT - $PACKSTRING
  else
   PACKEXT=${PACKSTRING#${PACKNOEXT}.}
   PACKTYPE=FILESET
fi

#echo 3 $PACKEXT - $PACKNOEXT - $PACKSTRING - $PACKTYPE

# metaarchivos
if test  x"$PACKTYPE" = x ; then 
if test  x"$PACKEXT" = x"$PACKSTRING" ; then 
   PACKEXT=$(echo $PACKSTRING| sed -e 's/\(.*\)\.\(dsc\|ebuild\|ubuild\|summa\|uget\)$/\2/')
   #seran META
  else
   PACKNOEXT=${PACKSTRING%.${PACKEXT}}
   PACKTYPE=PMS
fi
fi

#echo 4 $PACKEXT - $PACKNOEXT - $PACKSTRING - $PACKTYPE
#listado de archivos
if test  x"$PACKTYPE" = x ; then 
if test  x"$PACKEXT" = x"$PACKSTRING" ; then 
  PACKEXT=$(echo $PACKSTRING| sed -e 's/\(.*\)\.\(lf\)$/\2/') 
  #FILENAMESET
  else
   PACKNOEXT=${PACKSTRING%.${PACKEXT}}
   PACKTYPE=META
fi
fi
if test  x"$PACKTYPE" = x ; then 
if test  x"$PACKEXT" = x"$PACKSTRING" ; then 
  PACKEXT=$(echo $PACKSTRING| sed -e 's/\(.*\)\.\(can\)$/\2/')  
  else
   PACKNOEXT=${PACKSTRING%.${PACKEXT}}
   PACKTYPE=FILENAMESET
fi
fi
# nombre canonicos
if test  x"$PACKTYPE" = x ; then 
 if test  x"$PACKEXT" = x"$PACKSTRING" ; then
  PACKEXT=`echo $PACKSTRING | awk -F. '{print $NF}'`
  PACKNOEXT=${PACKSTRING%.${PACKEXT}}
 else
  PACKNOEXT=${PACKSTRING%.${PACKEXT}}
  PACKTYPE=CANONICAL
 fi
fi

#echo 8 $PACKEXT - $PACKNOEXT - $PACKSTRING - $PACKTYPE

if test  x"$PACKTYPE" = x ; then 
if test x"$PACKEXT" = x ; then
    PACKNOEXT=$PACKSTRING
    PACKTYPE=NOEXT
  else
    PACKTYPE=UNKNOWNPKGEXT
fi
fi

#FILESET PMS META FILENAMESET CANONICAL UNKNOWNPKGEXT

}


########################################################################### anachar

anachar(){
local CADENA=$1
local char=$2


 estext=`expr "$char" : '\([a-zA-Z0\.]\)' 2>/dev/null`

#echo MMM{$estext}MMMM
# /dev/null cuando llega signo +, pasa en debian

if test x"$estext" != x ; then
    #echo CHAR $char
    ES=CHAR
    saca=$char
    nume= # no es necesario
   else

    nume=`expr "$CADENA" : '\([0-9]\+\)'`
    if test x"$nume" = x ; then
        saca=$char
        # lo pongo como char
        #ES=OTHER
         ES=CHAR
        #echo CHAR OTHER $char
        # es al vicio, solo preguntar por numeros
        #echo SEPARA $char
        #char=''
       else
         #echo NUM  $nume
         ES=NUMB
         saca=$nume
    fi
 fi


}

########################################################################### order
# ver caracter ~ en debian
order(){
# returns first as compared to second

#order apo1002300.001.45g.ui67 apo1002300.001.45g.ui68b

#echo OOO $ORDER
#exit


CADENA1=$1
CADENA2=$2
#echo 1: $CADENA1 - 2: $CADENA2

while true ; do
 char1=${CADENA1:0:1}
 char2=${CADENA2:0:1}
 #echo CHAR1: $char1 - CHAR2: $char2
 if test x"$char1" = x -a  x"$char2" = x ; then
  #echo "SON IGUALES"
  ORDER=0
  break
 elif test x"$char1" = x -a  x"$char2" != x ; then
  #echo "CADENA2 PRIMERO T"
  ORDER=-1
  break 
 elif test x"$char1" != x -a  x"$char2" = x ; then
  #echo "CADENA1 PRIMERO T"
  ORDER=1
  break 
 fi

 

 anachar $CADENA1 $char1

 CADENA1=${CADENA1#$saca}
 ES1=$ES

 nume1=$nume

 anachar $CADENA2 $char2
 CADENA2=${CADENA2#$saca}
 ES2=$ES
 nume2=$nume
 #RES="$ES1 - $ES2 - $char1 - $char2 - $nume1 - $nume2"
 #echo $RES

 if test x"$ES1" = xNUMB -a x"$ES2" = xNUMB ; then
  #echo MMMMMMMMMMMMM $nume1 - $nume2

  if test x"$nume1" = x"$nume2" ; then
    #echo continue IGUALES NUMB: $RES
    continue
   elif test $nume1 -gt $nume2; then
    #echo "CADENA2 PRI 2        : $RES"
    ORDER=1
   else
    #echo "CADENA1 PRI 2        : $RES"
    ORDER=-1
   fi

  break
 
 elif test x"$ES1" = xCHAR -a x"$ES2" = xCHAR ; then

  if test x"$char1" = x"$char2" ; then
   #echo continue IGUALES CHAR: $RES
   continue
  elif test x"$char1" > x"$char2"; then
    #echo "CADENA1 PRI 3        : $RES"
    ORDER=-1
  else
    #echo "CADENA2 PRI 3        : $RES"
    ORDER=1
  fi

  break

elif test x"$ES1" = xCHAR -a x"$ES2" = xNUMB ; then
 if test x"$char1" = x0 ; then
    #echo "CADENA1 PRI 4 0      : $RES"
    ORDER=-1
    break
   else
    #echo "CADENA2 PRI 4        : $RES"
    ORDER=1
  fi
  break 
elif test x"$ES1" = xNUMB -a x"$ES2" = xCHAR ; then
 if test x"$char2" = x0 ; then
    #echo "CADENA2 PRI 4 0      : $RES"
    ORDER=1
   else
    #echo "CADENA1 PRI 4        : $RES"
    ORDER=-1
   fi
  break 
fi

#echo lll $char - $nume - $EST - $estext - $CADENA1 -O $ORDER
done


}

########################################################################### parse_cmd_line


upackname_parse_cmd_line(){

create=0

local OL=0
while test $# -gt 0  ; do
        case "$1" in
	    -h|--help)
                upackname_help
                exit
		;;
	    -v|-V|--version)
	        upackname_version 
                exit
                ;;
            -u|--usage)
	        upackname_usage
                exit
		;;
            -o|--oneline)
	        OL=1
		;;
            -c|--create)
	        create=1
		;;
	    *)
                FILES=$@
                break
 		;;
        esac
	shift
done


if test x"$1" = x ; then
  upackname_usage
  exit
fi 

PACK=$1
COMPPACK=$2
ONELINE=$OL
}


# no usa sort -V que en algunas distros da problemas

########################################################################### createpackname

createpackname(){
#COMPPN COMPPSUB COMPPV COMPPR COMPPS COMPOR COMPPALL COMPPE
 
# poner packlets tambien para esto

###########local HOST=$5
#echo CN_PKGNAME=" NAME $1 EXT $8"
local COMPPE=$8
if test x"$COMPPE" = x ; then
   COMPPE=nada
fi
case $COMPPE in 
 nada)
  CN_PKGNAME=$1
  if test x"$2" != x ; then
     CN_PKGNAME=$1-$2
  fi
  if test x"$3" != x ; then
     CN_PKGNAME=$CN_PKGNAME-$3
  fi
  if test x"$4" != x ; then
     CN_PKGNAME=$CN_PKGNAME-$4
  fi
  if test x"$5" != x ; then
     CN_PKGNAME=$CN_PKGNAME.$5
  fi
  ;;
 dsc)
    CN_PKGNAME=$1
    if test x"$3" != x ; then
     CN_PKGNAME=${CN_PKGNAME}_$3
    fi
     CN_PKGNAME=${CN_PKGNAME}.$COMPPE
   ;;

deb)
 #DEB  <foo>_<VersionNumber>-<DebianRevisionNumber>_<DebianArchitecture>.deb
ARCH=$5 
RELEASE=$4
if test x"$ARCH" = xnoarch ; then
   ARCH=all
fi

if test x"$RELEASE" = x0 ; then
   RELEASE=0.1
fi
  CN_PKGNAME=$1
  if test x"$2" != x ; then
     CN_PKGNAME=$1-$2
  fi
  if test x"$3" != x ; then
     CN_PKGNAME=${CN_PKGNAME}_$3
  fi
  if test x"$RELEASE" != x ; then
     CN_PKGNAME=$CN_PKGNAME-$RELEASE
  fi
  if test x"$ARCH" != x ; then
     CN_PKGNAME=${CN_PKGNAME}_$ARCH
  fi
  CN_PKGNAME=$CN_PKGNAME.$COMPPE
  ;;
 src.rpm)
  #RPM <name>-<version>-<release>.<architecture>.rpm
  CN_PKGNAME=$1
  if test x"$3" != x ; then
     CN_PKGNAME=$CN_PKGNAME-$3
  fi
 
  CN_PKGNAME=$CN_PKGNAME.$COMPPE

  ;;
 rpm)
  #RPM <name>-<version>-<release>.<architecture>.rpm
  CN_PKGNAME=$1
  if test x"$2" != x ; then
     CN_PKGNAME=$1_$2
  fi
  if test x"$3" != x ; then
     CN_PKGNAME=$CN_PKGNAME-$3
  fi
  if test x"$4" != x ; then
     CN_PKGNAME=$CN_PKGNAME-$4
  fi
  if test x"$5" != x ; then
     CN_PKGNAME=$CN_PKGNAME.$5
  fi
  CN_PKGNAME=$CN_PKGNAME.$COMPPE

  ;;
tbz2)
  #TBZ2 pkg-ver{_suf{#}}{-r#}.ebuild, no es ebuild, se le agrega un -host de prepo al tbz2, 
  #luego del nombre-tipobin-host, antes de version
  # verificar que upackname los interpreta bien a estos sacha tbz2 
  # si molesta no usarlo
  REL=$4
  PRN=`echo $REL| sed -e 's/^[0-9]//'`
  if test x"$REL" = x0 ; then 
     REL=''
  elif test x"$REL" != x"$PRN"; then
     REL=-r$4
  else
     REL=_$4
  fi
  CN_PKGNAME=$1
  if test x"$2" != x ; then
     CN_PKGNAME=$1-$2
  fi
  if test x"$5" != x ; then
     CN_PKGNAME=${CN_PKGNAME}-$5
  fi
  if test x"$3" != x ; then
     CN_PKGNAME=$CN_PKGNAME-$3
  fi
  if test x"$4" != x ; then
     CN_PKGNAME=${CN_PKGNAME}$REL
  fi
  CN_PKGNAME=$CN_PKGNAME.$COMPPE 
  ;;
ubuild|ebuild)
  #TBZ2 pkg-ver{_suf{#}}{-r#}.ebuild,  
 
  REL=$4
  PRN=`echo $REL| sed -e 's/^[0-9]//'`
  if test x"$REL" = x0 ; then 
     REL=''
  elif test x"$REL" != x"$PRN"; then
     REL=-r$4
  else
     REL=_$4
  fi
  CN_PKGNAME=$1
  if test x"$3" != x ; then
     CN_PKGNAME=$CN_PKGNAME-$3
  fi
  if test x"$4" != x ; then
     CN_PKGNAME=${CN_PKGNAME}$REL
  fi
  CN_PKGNAME=$CN_PKGNAME.$COMPPE 
  ;;
tgz|txz) #slack

#A slackware package name consists of four parts, separated by hyphens.
#   1. The name
#   2. The version - For example 0.1 or 1.2.3 or 1.1pre2.
#   3. The architecture. - Usually i386 or i686 or noarch.
#   4. The build number. - Increment this if you want to make another (better?) package with the same name and version.
#Of these, only the name can contain hyphens. Sometimes you want a hyphen in the version number.
# Just use an underscore or (better) squash it together. For example, 0.1-beta becomes 0.1beta.
#Note that the name of the documentation directory should match the "name-version" of the package name,
# so if you squash the version in the package name, do so in the name of the documentation directory too.
# ojo no se si release puede ser 0???

  CN_PKGNAME=$1
  if test x"$2" != x ; then
     CN_PKGNAME=$1-$2
  fi
  if test x"$3" != x ; then
     CN_PKGNAME=$CN_PKGNAME-$3
  fi
  if test x"$5" != x ; then  
     CN_PKGNAME=$CN_PKGNAME-$5
  fi
  if test x"$4" != x ; then
     CN_PKGNAME=$CN_PKGNAME-$4
  fi

  CN_PKGNAME=$CN_PKGNAME.$COMPPE
  ;; 
*) # otros, si son fuentes no debieran venir con host, eso queda al que usa este programa
ARCH=$5
if test x"$ARCH" = x ; then
   ARCH=noarch
fi
  CN_PKGNAME=$1
  if test x"$2" != x ; then
     CN_PKGNAME=$1-$2
  fi
  if test x"$3" != x ; then
     CN_PKGNAME=$CN_PKGNAME-$3
  fi
  if test x"$4" != x ; then
     CN_PKGNAME=$CN_PKGNAME-$4
  fi
  if test x"$ARCH" != x ; then
     CN_PKGNAME=$CN_PKGNAME.$ARCH
  fi
  CN_PKGNAME=$CN_PKGNAME.$COMPPE 
  ;;

esac

}

########################################################################### create

upackname_create(){
readcan "$1"

createpackname "$COMPPN" "$COMPPSUB" "$COMPPV" "$COMPPR" "$COMPPS" "$COMPOR" "$COMPPALL" "$COMPPE"
}


########################################################################### MAIN
# funcion para llamar cuando se lo incluye a upackname


upackname_ppal(){

local PACK=$1
local COMPPACK=$2


#echo NNN $1 JJJ  $2 KKK
#PACKSTRING=`basename $PACK`
PACKSTRING=`echo $PACK | awk -F/ '{print $NF}'`
PACKDIRPRE=${PACK%${PACKSTRING}} # en dos pasos por si no tiene /

if test x"$PACKDIRPRE" = x/ ; then
  PACKDIR=/ 
 else
  PACKDIR=${PACKDIRPRE%/} 
fi




# packtype
PACKNAMEVERS=$PACKSTRING


PACKEXT=''

extsep $PACKSTRING


#echo mmmmmmmmmmmmmmm $PACKEXT
PACKERROR=''


################33
PACKNAME=''
PACKSV=''
PACKVORDER=''
MPACKSYSTEM=''
PACKSYSTEM=''
#echo ==================== PACEXT $PACKEXT
case $PACKEXT in 
can)
# contar cantidad de _ si hay mas protestar, pasa en x86_64 por ejemplo



readcan $PACKNOEXT


PACKNAME=$COMPPN
PACKSUB=$COMPPSUB
PACKSV=$COMPPV
PACKRVORDER=$COMPPR
PACKSYSTEM=$COMPPS
PACKORIGIN=$COMPOR
PACK=$COMPPALL
PACKEXT=$COMPPE

#  `echo $PACKNOEXT| sed 's/\(.*\)_\(.*\)_\(.*\)_\(.*\)_\(.*\)_\(.*\)_\(.*\)_\(.*\)$/export PACKNAME\=\1 PACKSUB=\2 PACKSV\=\3 PACKRVORDER\=\4 MPACKSYSTEM\=\5 PACKORIGIN\=\6 MPACKSTRING\=\7 PACKEXT\=\8/'`

#PACKSTRING=`echo $MPACKSTRING| sed -e '/---/_/'`
#PACKSYSTEM=`echo $MPACKSYSTEM| tr . _`
#echo "CAN $PACKNAME : $PACKSV : $PACKRVORDER : $PACKSYSTEM : $PACKEXT"
;;
ebuild|ubuild|tbz2|uget)
# summa no son gentoo, genericos, no llevan version, se podria hacer uno especial

# en build info o ebuild  no parece haber info sobre nombre o version

    #http://distfiles.gentoo.org/distfiles/pms-3.pdf

    `echo $PACKNOEXT | sed -e 's/\(.*\)-\(\([[:digit:]]\+\(\.[[:digit:]]\+\)*\+[a-z]\?\)\(\(_\(alpha\|beta\|pre\|rc\|p\)[[:digit:]]*\)*\(-r\([[:digit:]]\+\)\)\?\)\)$/export PACKNAME=\1 PACKVERSION=\2 PACKSV=\3 PACKRVPRE=\5 PACKGENTOOPRE=\6 PACKGENTOORE=\8 PACKGENTOORENUM=\9/'`

if test x"$PACKNAME" = x ; then
    echo ERROR, NO ES UN ARCHIVO GENTOO
    PACKERROR="No es Gentoo"
fi

if test x"$PACKGENTOOPRE" = x ; then
  #PACKRV=${PACKRVPRE#-} # no porque a veces debbiera agregar _ y otras -
 PACKSRORDER=5
 else
  #PACKRV=$PACKRVPRE
 PACKSRORDERPRE=`echo $PACKGENTOOPRE| sed -r -e "s/_alpha/1./" \
 -e "s/_beta/2./" \
 -e "s/_pre/3./" \
 -e "s/_rc/4./" \
 -e "s/_p/6./" `

 PACKSRORDER=`echo $PACKSRORDERPRE| sed  -e 's/\.$//' `

fi

PACKRV=$PACKRVPRE

if test x"$PACKGENTOORE" = x ; then
    PACKRVORDER=$PACKSRORDER.0
  else
    PACKRVORDER=$PACKSRORDER.$PACKGENTOORENUM
fi

#echo bbbbbbbbbbbbbbb $PACKGENTOOPRE  $PACKGENTOORE - $PACKGENTOORENUM - $PACKSRORDER -  $PACKSRORDERPRE - $PACKNAME - $PACKVERSION


    #PACKNAME=sed -e 's/(.*\)\(-[[:digit:]]\+\(\.[[:digit:]]\+\)*\+[a-z]\?\(_\(alpha\|beta\|pre\|rc\|p\)[[:digit:]]*\)*\(-r[[:digit:]]\+\)\?\)$//'`
    #PACKVERSION=`echo $PACK|cut -d- -f2-`
    #if test x"$PACKVERSION" =  x"$PACKNAME" ; then  # esto es raro,
    #    PACKVERSION=''
    #    # que el cut ponga el primer campo si no hay segundo ver
    #    #PACKVERSION=0
    # fi

    #sed 's/-[0-9]\{1,\}.*$//'
    ;;

#Ebuild file names consist of four logical subsections:

#pkg-ver{_suf{#}}{-r#}.ebuild

#Note: The brackets ({}) delineate optional fields and do not appear in the literal package name. # represents any non-zero positive integer.

#The first subsection, pkg, is the package name, which should only contain lowercase letters, the digits 0-9, and any number of single hyphen (-), underscore (_) or plus (+) characters. Examples: util-linux, sysklogd and gtk+. We have some packages in Portage that don't follow these rules, but your packages should.

#The second subsection, ver, is the version of the package, which should normally be same as the version on the main source tarball. The version is normally made up of two or three (or more) numbers separated by periods, such as 1.2 or 4.5.2, and may have a single letter immediately following the last digit; e.g., 1.4b or 2.6h. The package version is joined to the package name with a hyphen. For example: foo-1.0, bar-2.4.6.

#Important: If you're thinking of using a trailing letter in your version string, note that the trailing letter should not be used to signify alpha or beta status for the package, since alphas and betas are prereleases and letter revisions are newer versions. This is an important distinction because Portage uses an ebuild's version number to determine if it is newer or older than other packages with the same category and name. It's very important that version numbers faithfully represent the version of the package so that Portage properly performs its dependency checking duties.

#The third subsection, {_suf{#}}, is optional and may contain one of these predefined suffixes, listed in least-recent to most-recent order:
#Suffix 	Meaning
#_alpha 	Alpha release
#_beta 	Beta release
#_pre 	Prerelease
#_rc 	Release candidate
#(none) 	Normal release
#_p 	Patch level (normally accompanied by trailing integer)

#Any of these suffixes may be immediately followed by a non-zero positive integer, e.g., linux-2.4.0_pre10. Assuming identical version parts, the suffixes are ordered as follows (lower means older): _alpha < _beta < _pre < _rc < (no suffix) < _p.

#When comparing identical suffixes with trailing integers, the one with the larger integer will be considered most recent. Example: foo-1.0_alpha4 is more recent than foo-1.0_alpha3.

#The fourth subsection of the package name is the Gentoo Linux-specific revision number ({-r#}). This subsection, like the suffix, is also optional. # is a non-zero positive integer; e.g., package-4.5.3-r3.

#This revision number is independent of the version of the source tarball and is used to inform people that a new and improved Gentoo Linux revision of a particular package is available. Initial releases of ebuilds must have no revision number; e.g., package-4.5.3 and are considered by Portage to have a revision number of zero. This means that counting goes as follows: 1.0 (initial version), 1.0-r1, 1.0-r2, etc.

#If you make non-trivial improvements to an existing ebuild file, you should copy the ebuild file to a new file with the revision number incremented by 1. Remember to always make mentions of your changes in the ChangeLog when you bump a revision and in your CVS commit message; not doing so is against policy.

#... and I suppose that we actually have a fifth section of the ebuild name as well -- the .ebuild extension itself. 
src.rpm)
    PACKSV=`echo $PACKNOEXT | awk -F- '{print $NF}'`
    PACKNAME=${PACKNOEXT%-${PACKSV}}
    PACKRV=''
    PACKVERSION=$PACKSV
    PACKNOSYSTEM=$PACKNAME-$PACKVERSION
    PACKSYSTEM=''
;;
rpm)


# the rpmfind.net buscando un paquete y luego con awk sobre la primera columna, cambiando html por rpm

# spec si hay nombre, version y release, verificar que esto funcione bien al abrir cada paquete


PACKSYSTEMNEG=`echo $PACKNOEXT | sed 's/\.\(\(darwin\|freebsd\|netbsd\|kfreebsd\|knetbsd\|openbsd\|hurd\|gnu\|linux\)-\)\?\(noarch\|src\|i486\|i586\|i686\|athlon\|ppc\|x86_64\|i386\|ia64\|alpha\|amd64\|armeb\|arm\|hppa\|m32r\|m68k\|mips\|mipsel\|powerpc\|ppc64\|s390\|s390x\|sh3\|sh3eb\|sh4\|sh4eb\|sparc\)$//'`
    PACKSYSTEMPRE=${PACKNOEXT#${PACKSYSTEMNEG}} 
    PACKSYSTEM=${PACKSYSTEMPRE#.} 

    PACKRV=`echo $PACKSYSTEMNEG | awk -F- '{print $NF}'`
    PACKRVNEG=${PACKSYSTEMNEG%-${PACKRV}} 

    PACKSV=`echo $PACKRVNEG | awk -F- '{print $NF}'`

   PACKNAME=${PACKRVNEG%-${PACKSV}}
 
#    PACKNAME=`echo $PACKNOEXT |sed 's/-[^-]*-[^-]*$//'`

#  echo MMMMMMMMMMM $PACKNOEXT - $PACKSYSTEMNEG - $PACKSV - $PACKRV - $PACKRVNEG - $PACKNAME

 #   PACKNAME=`echo $PACKNOEXT |sed 's/-[^-]*-.*$//'`
 #   PACKVERSIONPRE=${PACKNOEXT#${PACKNAME}} # primero el nombre por si es todo
 #   PACKVERSIONSYS=${PACKVERSIONPRE#-} 


if test x"$PACKNAME" = x ; then
    echo ERROR, NO ES UN ARCHIVO RPM
    PACKERROR="No es RPM"
fi

PACKVERSION=$PACKSV-$PACKRV

PACKNOSYSTEM=$PACKNAME-$PACKVERSION

 #   `echo $PACKVERSION| sed 's/\([^-]*\)-\(.*\)$/export PACKSV\=\1 PACKRV\=\2/'`






#    echo KKKK $PACKSV   KKKKK $PACKSYSTEM KKKKKK $PACKRV



    # `echo $PACKNOEXT | sed -e 's/\([a-zA-Z0-9_\-\+]*\)-\([a-zA-Z0-9_\.]*\)-\([a-zA-Z0-9_\.]*\)\.\(noarch\|src\|i386\|i686\|athlon\|ppc\|x86_64\)$/export PACKNAME\="\1"  PACKVERSION\="\2-\3.\4"  PACKOV\="\2" PACKRV\="\3" PACKARCH\="\4"/'`

    #older systems do not have arch part, see
    #        my $name = $1;
    #        my $version = $2;
    #        my $release = $3;
    #        my $arch = $4;

    #$ rpm -qp --qf '%{NAME}' some.rpm

    #rpm -qa|sed 's/-[^-]*-[^-]*$//'

    #RPM <name>-<version>-<release>.<architecture>.rpm nano-0.98-2.i386.rpm  libgnomeuimm-2.0-2.0.0-3.src.rpm

    #A package label is contained within the file and does not necessarily
    #need to match the name of the file.

    #Additionally, libraries are distributed in two separate packages for
    #each version. One contains the precompiled code, while the second one
    #contains the development files such as headers, static library files,
    #etc. for the library in question. Those packages have "-devel" appended to their name field. Users need to carefully check so that
    #the version of the development package matches that of the binary
    #package, otherwise the library may not work very well.
    ;;

dsc) # tambien tar.gz
    PACKNAME=`echo $PACKNOEXT | awk -F_ '{print $1}'`
    PACKVERSIONSYSPRE=${PACKNOEXT#${PACKNAME}}  # en dos pasos por si el nombre debian esta mal y no usa _
    PACKVERSIONSYS=${PACKVERSIONSYSPRE#_}

    PACKVERSION=$PACKVERSIONSYS
 
if test x"$PACKNAME" = x ; then
    echo ERROR, NO ES UN ARCHIVO DEB NAME
    PACKERROR="No es deb"
fi

    PACKNOSYSTEM=$PACKNAME_$PACKVERSION
    #echo MMMMM $PACKVERSION  - $PACKNOSYSTEM
  
    PACKSYSTEM="" 

PACKSV=$PACKVERSION

PACKRV=''

# creo que corregido

if test x"$PACKSV" = x ; then
#    echo ERROR, NO ES UN ARCHIVO DEB SV
#    PACKERROR="No es deb"
# lo anterior es falso, puede ser deb sin release
     PACKSV=$PACKVERSION
     PACKRV=''
fi



;;
deb)

# en control parece haber info sobre el nombre, no sobre las versiones, usar para verificar

    #DEB  <foo>_<VersionNumber>-<DebianRevisionNumber>_<DebianArchitecture>.deb

#debian/pool/main
#ls  -1 */*/ |grep ".deb$">poolpkg
# to get list of packages

    PACKNAME=`echo $PACKNOEXT | awk -F_ '{print $1}'`
    PACKVERSIONSYSPRE=${PACKNOEXT#${PACKNAME}}  # en dos pasos por si el nombre debian esta mal y no usa _
    PACKVERSIONSYS=${PACKVERSIONSYSPRE#_}

if test x"$PACKNAME" = x ; then
    echo ERROR, NO ES UN ARCHIVO DEB NAME
    PACKERROR="No es deb"
fi

    #echo MMMMM $PACKVERSION
    #igual que el rpm con _ en vez de .
    PACKVERSION=`echo $PACKVERSIONSYS | sed 's/_\(\(darwin\|freebsd\|netbsd\|kfreebsd\|knetbsd\|openbsd\|hurd\|gnu\|linux\)-\)\?\(all\|noarch\|src\|i486\|i586\|i686\|athlon\|ppc\|x86_64\|i386\|ia64\|alpha\|amd64\|armeb\|arm\|hppa\|m32r\|m68k\|mips\|mipsel\|powerpc\|ppc64\|s390\|s390x\|sh3\|sh3eb\|sh4\|sh4eb\|sparc\)$//'`

if test x"$PACKVERSION" = x ; then
    echo ERROR, NO ES UN ARCHIVO DEB VERSION
    PACKERROR="No es deb"
fi

    PACKNOSYSTEM=$PACKNAME_$PACKVERSION
    #echo MMMMM $PACKVERSION  - $PACKNOSYSTEM
    PACKSYSTEMPRE=${PACKVERSIONSYS#${PACKVERSION}} # primero el nombre por si es todo
    PACKSYSTEM=${PACKSYSTEMPRE#_} 

`echo $PACKVERSION| sed 's/\([^-]*\)\(-\(.*\)\)\?$/export PACKSV\=\1 PACKRV\=\3/'` # /mal si no reconoce, ver cuando no hay Release en debian

# creo que corregido

if test x"$PACKSV" = x ; then
#    echo ERROR, NO ES UN ARCHIVO DEB SV
#    PACKERROR="No es deb"
# lo anterior es falso, puede ser deb sin release
     PACKSV=$PACKVERSION
     PACKRV=''
fi

    # echo KKKK $PACKSV   KKKKK $PACKSYSTEM KKKKKK $PACKRV KKKK $PACKNOSYSTEM

     #\([a-z][a-z0-9\+\-\.]+\)_\([a-zA-Z0-9_\.]*\)-\([0-9a-zA-Z\+\.\~]+\)_\(noarch\|src\|i386\|i686\|athlon\|ppc\|x86_64\)

     #The name of the package itself (not the filename, just the name of the package) can contain lowercase letters, numbers, and the "-" and "+" characters.
     #debian_revision

     #This part of the version number specifies the version of the Debian package based on the upstream version.
     #It may contain only alphanumerics and the characters + . ~ (plus, full stop, tilde) and is compared in the same way as the upstream_version is.
     #It is optional; if it isn't present then the upstream_version may not contain a hyphen. 
     #This format represents the case where a piece of software was written specifically to be turned into a Debian package, 
     #and so there is only one "debianisation" of it and therefore no revision indication is required.
     #It is conventional to restart the debian_revision at 1 each time the upstream_version is increased.
     #The package management system will break the version number apart at the last hyphen in the string 
     #(if there is one) to determine the upstream_version and debian_revision. The absence of a debian_revision is equivalent to a debian_revision of 0

     #The VVV component is the version number specified by the upstream
     #developer. There are no standards in place here, so the version number
     #may have formats as different as "19990513" and "1.3.8pre1".

     #The RRR component is the Debian revision number, and is specified by
     #the Debian developer (or an individual user if he chooses to build the
     #package himself). This number corresponds to the revision level of the
     #Debian package, thus, a new revision level usually signifies changes
     #in the Debian Makefile (debian/rules), the Debian control file
     #(debian/control), the installation or removal scripts (debian/p*), or
     #in the configuration files used with the package.

     #The AAA component identifies the processor for which the package was
     #built. This is commonly i386, which refers to chips compatible to
     #Intel's 386 or later versions. For other possibilities review Debian's
     #FTP directory structure at What are all those directories at the
     #Debian FTP archives?, Section 6.7. For details, see the description of
     #"Debian architecture" in the manual page dpkg-architecture(1).

     #

     #i386 ia64 alpha amd64 armeb arm hppa m32r m68k mips mipsel powerpc ppc64 s390 s390x sh3 sh3eb sh4 sh4eb sparc darwin-i386 darwin-ia64 darwin-alpha darwin-amd64 darwin-armeb darwin-arm darwin-hppa darwin-m32r darwin-m68k darwin-mips darwin-mipsel darwin-powerpc darwin-ppc64 darwin-s390 darwin-s390x darwin-sh3 darwin-sh3eb darwin-sh4 darwin-sh4eb darwin-sparc freebsd-i386 freebsd-ia64 freebsd-alpha freebsd-amd64 freebsd-armeb freebsd-arm freebsd-hppa freebsd-m32r freebsd-m68k freebsd-mips freebsd-mipsel freebsd-powerpc freebsd-ppc64 freebsd-s390 freebsd-s390x freebsd-sh3 freebsd-sh3eb freebsd-sh4 freebsd-sh4eb freebsd-sparc kfreebsd-i386 kfreebsd-ia64 kfreebsd-alpha kfreebsd-amd64 kfreebsd-armeb kfreebsd-arm kfreebsd-hppa kfreebsd-m32r kfreebsd-m68k kfreebsd-mips kfreebsd-mipsel kfreebsd-powerpc kfreebsd-ppc64 kfreebsd-s390 kfreebsd-s390x kfreebsd-sh3 kfreebsd-sh3eb kfreebsd-sh4 kfreebsd-sh4eb kfreebsd-sparc knetbsd-i386 knetbsd-ia64 knetbsd-alpha knetbsd-amd64 knetbsd-armeb knetbsd-arm knetbsd-hppa knetbsd-m32r knetbsd-m68k knetbsd-mips knetbsd-mipsel knetbsd-powerpc knetbsd-ppc64 knetbsd-s390 knetbsd-s390x knetbsd-sh3 knetbsd-sh3eb knetbsd-sh4 knetbsd-sh4eb knetbsd-sparc netbsd-i386 netbsd-ia64 netbsd-alpha netbsd-amd64 netbsd-armeb netbsd-arm netbsd-hppa netbsd-m32r netbsd-m68k netbsd-mips netbsd-mipsel netbsd-powerpc netbsd-ppc64 netbsd-s390 netbsd-s390x netbsd-sh3 netbsd-sh3eb netbsd-sh4 netbsd-sh4eb netbsd-sparc openbsd-i386 openbsd-ia64 openbsd-alpha openbsd-amd64 openbsd-armeb openbsd-arm openbsd-hppa openbsd-m32r openbsd-m68k openbsd-mips openbsd-mipsel openbsd-powerpc openbsd-ppc64 openbsd-s390 openbsd-s390x openbsd-sh3 openbsd-sh3eb openbsd-sh4 openbsd-sh4eb openbsd-sparc hurd-i386 hurd-ia64 hurd-alpha hurd-amd64 hurd-armeb hurd-arm hurd-hppa hurd-m32r hurd-m68k hurd-mips hurd-mipsel hurd-powerpc hurd-ppc64 hurd-s390 hurd-s390x hurd-sh3 hurd-sh3eb hurd-sh4 hurd-sh4eb hurd-sparc ;;



    ;;

esac
#\(\(darwin\|freebsd\|netbsd\|kfreebsd\|knetbsd\|openbsd\|hurd\|gnu\|linux\)-\)\?
### aqui seguro tenemos PACKNOEXT


#echo PACKSYSTEM $PACKSYSTEM

## si no tenemos PACKNOSYSTEM lo buscamos
if test x"$PACKSYSTEM" = x ; then
    PACKNOSYSTEM=`echo $PACKNOEXT | sed 's/[\._-]\(all\|noarch\|src\|i486\|i586\|i686\|athlon\|ppc\|x86_64\|i386\|ia64\|alpha\|amd64\|armeb\|arm\|hppa\|m32r\|m68k\|mips\|mipsel\|powerpc\|ppc64\|s390\|s390x\|sh3\|sh3eb\|sh4\|sh4eb\|sparc\)$//'`

# if apears something identifing origin as ubuntu, ututo, pacman etc must be extracted here



#echo MMMM $PACKNAME - $PACKNOSYSTEM -$PACKNOEXT
    PACKSYSTEMPRE=${PACKNOEXT#${PACKNOSYSTEM}} # primero el nombre por si es todo
    PACKSYSTEMPRE3=${PACKSYSTEMPRE#-} 
    PACKSYSTEMPRE2=${PACKSYSTEMPRE3#_} 
    PACKSYSTEM=${PACKSYSTEMPRE2#.} 


fi

if test x"$PACKNOSYSTEM" = x ; then
   PACKNOSYSTEM=$PACKNOEXT
fi

# aqui seguro tenemos PACKNOSYSTEM
# si no tenemos PACKVERSION (PACKNONAME) lo buscamos
 
#echo MMMM $PACKNAME - $PACKNOSYSTEM -$PACKNOEXT


if test x"$PACKNAME" = x ; then
    PACKVERSION=`echo $PACKNOSYSTEM | awk -F- '{print $NF}'`
    if test x"$PACKVERSION" = x"$PACKNOSYSTEM" ; then
       PACKVERSION=''
    fi
    # Si version no tiene numeros se rechaza, no es version, sino parte del nombre
    #echo PPPPPPPPPPPPPP $PACKVERSION - $PACKNOSYSTEM 
    SINUNNUMERO=`echo $PACKVERSION |sed -e 's/[0-9]//'`
    if test x"$SINUNNUMERO" = x"$PACKVERSION" ; then 
          #no es version
          PACKVERSION=''
    fi

 
    #echo PPPPPPPPPPPPPP $PACKVERSION - $PACKNOSYSTEM - $SINUNNUMERO
    PACKNAMEPRE=${PACKNOSYSTEM%${PACKVERSION}} # en dos pasos por si no tiene -
    PACKNAME=${PACKNAMEPRE%-} 

#echo MMMM $PACKNAME
fi

## si no conseguimos una PACKNAME diferente la buscamos de nuevo
if test x"$PACKNAME" = x"$PACKNOSYSTEM" ; then
   PACKVERSION=`echo $PACKNOSYSTEM | awk -F- '{print $NF}'`
    if test x"$PACKVERSION" = x"$PACKNOSYSTEM" ; then
       PACKVERSION=''
    fi
    SINUNNUMERO=`echo $PACKVERSION |sed -e 's/[0-9]//'`
    if test x"$SINUNNUMERO" = x"$PACKVERSION" ; then 
          #no es version
          PACKVERSION=''
    fi

    PACKNAMEPRE=${PACKNOSYSTEM%${PACKVERSION}} # en dos pasos por si no tiene -
    PACKNAME=${PACKNAMEPRE%_} 
fi

#echo MMM $PACKSV
if test x"$PACKSV" = x -a x"$PACKVERSION" != x ; then

    PACKRV=''
    PACKSV=`echo $PACKVERSION| sed 's/_\(.*\)$//'`    
    if test x"$PACKVERSION" = x"$PACKSV" ; then
        ### PACKSV='' # no better to have this as VERSION if not RV
        :
       else
        PACKRVPRE=${PACKVERSION%$PACKSV}
        PACKRV=${PACKRVPRE%$_}
    fi

fi

if test x"$PACKRVORDER" = x ; then
     PACKRVORDER=$PACKRV
fi


SLASH=_
#if test x"$PACKSV" = x ; then
#   SLASH=''
#fi
SSLASH=_
#if test x"$PACKRVORDER" = x ; then
#   SSLASH=''
#fi

PACKSUB=''
PACKSUBNEG=$(echo $PACKNAME| sed  -e 's/\(-devel\|-doc\|-src\|-debug\|-lang\|-dev\|-dbg\)$//')
if test x"$PACKSUBNEG" != x"$PACKNAME" ; then
   PACKSUB=${PACKNAME#$PACKSUBNEG-}
fi
#debian
#PACKSUB=$(echo $PACKNAME| sed  -e 's/\(.*\)-\(dev\|doc\|dbg\)$/\2/')
#suse
#PACKSUB=$(echo $PACKNAME| sed  -e 's/-\(devel\|doc\|src\|debug\|lang\)$//')


#-X11
#-kde4
#-kde3
#-gnome
PACKORIGIN='' # para expander y colocar el repositorio o el creador del paquete
# 
PACKORIGIN=$(echo $PACKRV| sed  -e 's/^\(fc\|mdv\|el\|\)\(.*\)/\1/')

#echo PPPPPPPPPPPPPPPPPPPPPPP $PACKSUB - $PACKORIGIN
#Fedora comienza con fc(VERSION) ej fc10. fc11
#bash-3.2-30.fc10.i386
#
#mandriva comienza con mdv(año) ej mdv2009 mdv2010
#bash-3.2.48-3mdv2009.1.src#
#
#Epel Server
#el5
#amarok-1.4.10-7.20090624svn.el5.
#echo JJJJJJJJJJJJ $PACKSTRING

###################
#en release

#opensuse, gentoo y debian: nada
#mandriva mdv
#fedora fc
#asp asp

# que pasa con srpm?



MPACKSTRING=`echo $PACK| sed -e 's/_/---/'`
MPACKSYSTEM=`echo $PACKSYSTEM| tr _ .`
PACKCOMPLETENORMALIZEDNAME="$PACKNAME$SLASH$PACKSUB$SLASH$PACKSV$SSLASH${PACKRVORDER}$SLASH${MPACKSYSTEM}$SLASH$PACKORIGIN$SLASH$MPACKSTRING$SLASH$PACKEXT"

if test x"$COMPPACK" != x ; then
      
     readcan $COMPPACK  COMPPN COMPPSUB COMPPV COMPPR COMPPS COMPOR COMPPALL COMPPE


#echo COMP $COMPPV  - $COMPPR 
#echo PACK $PACKSV - $PACKRVORDER

order ${PACKSV}_$PACKRVORDER ${COMPPV}_$COMPPR

fi

}
############ NO HAY CODIGO DE ERROR, PONER


upackname_main(){

local PACK=$1
local COMPPACK=$2
local ONELINE=$3

upackname_ppal $PACK $COMPPACK $ONLINE

if test x"$ONELINE" != x1 ; then 

# ojo ver que pasa si las cadenas tienen blancos
echo "export PACKALL=$PACK"
echo "export PACKSTRING=$PACKSTRING"
echo "export PACKDIR=$PACKDIR"
echo "export PACKNAME=$PACKNAME"
echo "export PACKVERSION=$PACKVERSION" #version and release
# no: si no hay version , version debe ser 0
echo "export PACKEXT=$PACKEXT"
echo "export PACKTYPE=$PACKTYPE"
echo "export PACKCOMPLETENAME=$PACKNOSYSTEM" # without system
echo "export PACKNOEXT=$PACKNOEXT" # without extension
echo "export PACKSYSTEM=$PACKSYSTEM"
echo "export PACKSV=$PACKSV"
echo "export PACKRV=$PACKRV"
echo "export PACKERROR=$PACKERROR"
echo "export PACKRVORDER=$PACKRVORDER"

echo "export PACKCANONICALNAME=$PACKCOMPLETENORMALIZEDNAME" # without extension
echo "export PACKORIGIN=$PACKORIGIN"
echo "export PACKSUB=$PACKSUB"
echo "export ORDER=$ORDER"
echo "export COMPPN=$COMPPN"
echo "export COMPPSUB=$COMPPSUB"
echo "export COMPPV=$COMPPV"
echo "export COMPPR=$COMPPR"
echo "export COMPPS=$COMPPS"
echo "export COMPOR=$COMPOR"
echo "export COMPPALL=$COMPPALL"
echo "export COMPPE=$COMPPE"
else

#echo "$PACKNAME:$PACKSV:$PACKRVORDER:$PACKTYPE"
 if test x"$ORDER" != x ; then
   echo "$PACKCOMPLETENORMALIZEDNAME $ORDER"
  else
   echo "$PACKCOMPLETENORMALIZEDNAME"
 fi
fi
}

########################################################################### MAIN_END

if test x"$1" != xsource ; then 

    upackname_vars

    upackname_parse_cmd_line "$@"

    #echo upackname_main $PACK $COMPPACK
    if test x"$create" = x0 ; then
      upackname_main "$PACK" "$COMPPACK" "$ONELINE"
     else
      upackname_create "$PACK"
    fi
    if test x"$ERRORBYPASS" != x ;  then
       msg 4 "ERRORBYPASS: $ERRORBYPASS"
       ERRORBYPASS=''
    fi
fi

########################################################################### MAIN_END


#No me fije en otros sistemas, pero los paquetes versionados al estilo
#gentoo tiene una dificultad cuando corresponden a releases,
#prereleases, betas, etc. Salvo por eso, se ordenarían fácilmente con
#ls -v , que compara versiones numéricas en los nombres de archivos.
#Pero cuando las versiones son cosas como paquete-0.3.7-alpha1 y
#paquete-0.3.7 allí falla.

#Lo que hice para resolver eso es previamente hacer una lista de los
#archivos a ordenar, en la lista reemplazar esas cosas por números,
#para que el ls los pueda ordenar, así:

#sed -r -e "s/(-[0-9.]+)_alpha/\1_000_/" \
# -e "s/(-[0-9.]+)_beta/\1_001_/" \
# -e "s/(-[0-9.]+)_pre/\1_002_/" \
# -e "s/(-[0-9.]+)_rc/\1_003_/" \
# -e "s/(-[0-9.]+)_p/\1_004_/")
#On Sunday 07 September 2008 08:28:11 Jim Meyering wrote:
#> IMHO, changing sort -V to produce more intuitively-correct results
#> is the way to go.
#>
#> With ls -v, I'm willing to make the change as well, *assuming*
#> no one produces a counterargument.
#>
#> The question is what ordering function to use.
#> The more generally-useful the better.  i.e., I hope
#> it can be compatible with both the rpm and deb version sorters.
#I made an investigation of existing functions which sort version strings:
#strverscmp - from glibc (now with its equivalent in gnulib)
#rpmvercmp - from rpm
#ververcmp - from dpkg##

#The main problem of all these functions is dealing with suffixes. So I
#modified them to drop the suffixes. So it is 6 implementations together (3
#original + 3 modified).

#Then I ran a few series of tests with all implementations. I think the
#modified version of ververcmp (from dpkg) gives the best results - consider
#attached results of an example - results.tar.bz2#

#So I propose a new function filevercmp (attachment filevercmp.c) as the
#predicate function for new sort --version-sort.

#In the attachment is also the whole "testing framework" which I used to
#compare these functions - strverscmp.tar.bz2 - follow the steps in README
#inside archive. It is developed a bit quickly but I hope it could be
#useful :-)#


#Kamil 
#http://www.opensubscriber.com/message/bug-coreutils@gnu.org/10201323.html

#http://old.nabble.com/Possible-bug-in-sort--V-td26804985.html

#> cat a | /build/toolchain/lin32/coreutils-8.2/bin/sort -V
#> kernel-2.6.18-164.2.1.el5.x86_64.rpm
#> kernel-2.6.18-164.6.1.el5.x86_64.rpm
#> kernel-2.6.18-164.el5.x86_64.rpm
#>
#> The result should be
#> kernel-2.6.18-164.el5.x86_64.rpm
#> kernel-2.6.18-164.2.1.el5.x86_64.rpm
#> kernel-2.6.18-164.6.1.el5.x86_64.rpm
#>
#> Is it a bug is sort -V?


#I agree the behavior is pretty awkward. Nevertheless the behavior
#is well documented:

#http://www.gnu.org/software/coreutils/manual/html_node/Details-about-version-sort.html

#The "bug" is triggered by the underscore in "x86_64". It's not treated as file
#suffix in that case. However it works fairly well when you replace "x86_64" by
#"i686".
#From 3069d50b766a2db8b86406904b7327e5de5e315f Mon Sep 17 00:00:00 2001
#From: =?utf-8?q?P=C3=A1draig=20Brady?= <P@...>
#Date: Thu, 17 Dec 2009 10:48:54 +0000
#Subject: [PATCH] doc: enhance and reference info about version comparison

#* doc/coreutils.texi (sort invocation): Reference the additional
#info about filevercmp rather than the unused strverscmp.
#(Details about version sort): Add some examples that are not
#handled well by fileversmp.
#* src/ls.c: Change a comment referencing the now unused strverscmp.
#---
# doc/coreutils.texi |   33 ++++++++++++++++++++++++---------
# src/ls.c           |    2 +-
# 2 files changed, 25 insertions(+), 10 deletions(-)

#-This functionality is implemented using gnulib's @code{filevercmp} function.
#-One result of that implementation decision is that @samp{ls -v}
#-and @samp{sort -V} do not use the locale category, @env{LC_COLLATE},
#-which means non-numeric prefixes are sorted as if @env{LC_COLLATE} were set
#-to @samp{C}.
#+This functionality is implemented using gnulib's @code{filevercmp} function,
#+which has some caveats worth noting.
#+
#+@itemize @bullet
#+@item @env{LC_COLLATE} is ignored, which means @samp{ls -v} and @samp{sort -V}
#+will sort non-numeric prefixes as if the @env{LC_COLLATE} locale category
#+was set to @samp{C}.
#+@item Some suffixes will not be matched by the regular
#+expression mentioned above.  Consequently these examples may
#+not sort as you expect:
#+
#+@example
#+abc-1.2.3.4.7z
#+abc-1.2.3.7z
#+@end example
#+
#+@example
#+abc-1.2.3.4.x86_64.rpm
#+abc-1.2.3.x86_64.rpm
#+@end example
#+@end itemize
 
# @node General output formatting
# @subsection General output formatting
#diff --git a/src/ls.c b/src/ls.c
#index aeaa584..5c7f6aa 100644
#--- a/src/ls.c
#+++ b/src/ls.c
#@@ -3272,7 +3272,7 @@ DEFINE_SORT_FUNCTIONS (extension, cmp_extension)
#    All the other sort options, in fact, need xstrcoll and strcmp variants,
#    because they all use a string comparison (either as the primary or secondary
#    sort key), and xstrcoll has the ability to do a longjmp if strcoll fails for
#-   locale reasons.  Last, strverscmp is ALWAYS available in coreutils,
#+   locale reasons.  Last, filevercmp is ALWAYS available in coreutils,
#    thanks to the gnulib library. */
# static inline int
# cmp_version (struct fileinfo const *a, struct fileinfo const *b)
#-- 
#1.6.2.5

#como compilar a partir de un ebuild, de un spec y de un control
#category no esta en ebuild, si en ubuild

#http://www.redhat.com/archives/rpm-list/2003-January/msg00006.html









#RES1=`echo ".$CADENA1" |sed -e 's/[^0-9a-zA-Z]\+/./g'| sed -e 's/\([a-zA-Z]\+\)/\1:./g' | sed -e 's/\([0-9]\+\)/\1;./g' | sed -e 's/.\([0]\+\)/.\1:./g'`
#RES2=`echo ".$CADENA2" |sed -e 's/[^0-9a-zA-Z]\+/./g'| sed -e 's/\([a-zA-Z]\+\)/\1:./g' | sed -e 's/\([0-9]\+\)/\1;./g' | sed -e 's/.\([0]\+\)/.\1:./g'`
#echo $RES1
#echo $RES2

#FIN=0
##IFS=.


 


#RES1=${RES1#.}
#RES2=${RES2#.}
#coma=`echo "$RES1" |sed -e 's/\..\+$//'`
#RES1=${RES1#$coma}

#comb=`echo "$RES2" |sed -e 's/\..\+$//'`
#RES2=${RES2#$comb}

#echo $coma $comb - $RES1 $RES2
#if test x"$coma" != x"$comb" ; then
#   echo SON DISTINTOS $coma $comb
#   FIN=1
#fi#

#if test x"$RES1" = x -o x"$RES2" = x  ; then
# echo junto termino: $coma - $comb
#   FIN=1
#fi
#bbb=s
#
# if test x"$item" != x; then 
# echo $item

# fi

#done




# if FILESET, ver si son fuentes analizando directorios /bin /usr, etc si alguno no lo es no es binario
# no es cosa del nombre



# 4 kind: file list (lf), metapacks (ebuild ubuild suma), binary packs, source packs
#METAEXT="ebuild ubuild summa"
#LISTEXT="lf can"  
# esto no es asi, cambiar

#KNOWN:
# primero mas grandes#
#BINPKGEXT="tgz tbz2 tbz deb rpm"
#SEE:
#PKGEXT="tar.gz tgz tar.bz tar.bz2 tbz tbz2 ZIP zip jar gz Z z bz2 bz 7Z 7z RAR rar LHa LHA lha lzh a deb lzma xz rpm"

#PACKTYPE=0 # EXIST EXTENSION


#echo MMMMMMMMMMMMMMMMMMMMMMMMMMM

########################################3 test sobre archivos reales, ver que pasa si no se quiere esto
# o sea proveer 


# basename?

#extsep $PACKSTRING "$BINPKGEXT" BINPKGEXT

#echo MMMMMMMMMMMMM $PACKNOEXT -  $PACKEXT

#if test x"$PACKEXT" = x ; then
  # extsep $PACKSTRING "$LISTEXT" LISTEXT
#fi
#if test x"$PACKEXT" = x ; then
#   extsep $PACKSTRING "$METAEXT" METAEXT
#fi

#extension separation
# for ext in $2 ; do
#   rext=`echo $ext | sed  's|\.|\\\.|' `
#   first=`echo $1 | sed "s/\.$rext\$//"` 
#   if test "x$first" != "x$1"; then
#      PACKEXT=$ext
#      PACKTYPE=$3
#      PACKNOEXT=$first
#      break
#   fi
# done


#For more flexibility, you may want to write your functions so that they combine both result variables and command substitution:

#function myfunc()
#{
#    local  __resultvar=$1
#    local  myresult='some value'
#    if [[ "$__resultvar" ]]; then
#        eval $__resultvar="'$myresult'"
#    else
#        echo "$myresult"
#    fi
#}

#myfunc result
#echo $result
#result2=$(myfunc)
#echo $result2
