#! /bin/sh
# The sort file by serial number for GUARDIAN series installer Ver. 1.0.05
# Copyright (c) 2008 Canon IT Solutions Inc.
#

# check shell and set PATH environment variable
#
PATH=/bin:/usr/bin
export PATH || (echo "You must use sh to run this script"; kill $$)
if [ ! -t 0 ]; then
    echo "Say 'sh `basename $0`', not 'sh < `basename $0`'"
    exit 1
fi

# script usage message print function
#
Usage()
{
    cat << END_OF_USAGE
usage:
  `basename $0` [-w|--with-hidden] <directory> [-h|--help]

    <directory>      :    specify the directory
    -w, --with-hidden:    display with hidden *.ini file
    -h, --help       :    print this help message and script exit
END_OF_USAGE
}

# check number of parameters
#
if [ $# -gt 2 ]; then
    echo "ERROR: too many parameters." 1>&2
    Usage
    exit 1
fi

# hold original IFS
#
ORG_IFS="$IFS"

# parse command line options
#
DIRECTORY="."
WHDN=0
while [ $# -ne 0 ]
do
    case $1 in
    '')
        break
        ;;
    '-w'|'--with-hidden')
        WHDN=1
        ;;
    '-h'|'--help')
        Usage
        exit 0
        ;;
    *)
        DIRECTORY=$1
        ;;
    esac
    shift
done
if [ ! -d ${DIRECTORY} ]; then
    echo "ERROR: not a directory[${DIRECTORY}]." 1>&2
    exit 1
fi

if [ "X${UNAME}" = "X" ]; then
    UNAME=`uname -s`
fi
if [ "X${PKG_IF}" = "X" ]; then
    if [ ${UNAME} = "Linux" ]; then
        PKG_IF="rpm -q"
    else
        PKG_IF="pkginfo -q"
    fi
fi

PARSER="`dirname $0`/parser"
if [ ${WHDN} != 1 ]; then
    INILIST=`ls ${DIRECTORY}/*.ini 2>&1`
else
    INILIST=`ls ${DIRECTORY}/*.ini ${DIRECTORY}/.*.ini 2>&1`
fi
if [ $? -ne 0 ]; then
    echo "ERROR: file not found." 1>&2
    exit 1
fi

for f in ${INILIST}
do
    CHKOS=`${PARSER} -F $f -s COMMON -v OS_TYPE 2>&1`
    if [ $? -eq 0 -a "${CHKOS}" != "${UNAME}" ]; then
        continue
    fi
    CHKPG=`${PARSER} -F $f -s COMMON -v NED_PACKAGE 2>&1`
    if [ $? -eq 0 -a "X${CHKPG}" != "X" ]; then
        IFS=:
        for p in ${CHKPG}
        do
            IFS="$ORG_IFS"
            ${PKG_IF} $p >/dev/null 2>&1
            if [ $? -ne 0 ]; then
                continue 2
            fi
        done
        IFS="$ORG_IFS"
    fi
    CHKPG=`${PARSER} -F $f -s COMMON -v UND_PACKAGE 2>&1`
    if [ $? -eq 0 -a "X${CHKPG}" != "X" ]; then
        IFS=:
        for p in ${CHKPG}
        do
            IFS="$ORG_IFS"
            ${PKG_IF} $p >/dev/null 2>&1
            if [ $? -eq 0 ]; then
                continue 2
            fi
        done
        IFS="$ORG_IFS"
    fi
    echo "$f:`${PARSER} -F $f -s COMMON -v SERIAL`"
done | sort -b -n -t: -k 2 | sed -e 's/:.*$//'

# End of this script
#
exit 0
