#!/sbin/installer/sh

get_version() {
    local old_name=`cat /var/log/packages/$1 | grep "^PACKAGE NAME" | cut -f2 -d':' `
    local old_vers=`echo $old_name | cut -f2 -d'-'`
    echo  $old_vers
}
get_build() {
    local old_name=`cat /var/log/packages/$1 | grep "^PACKAGE NAME" | cut -f2 -d':' `
    local old_build=`echo $old_name | cut -f4 -d'-' `
    echo  $old_build
}
    

check_vers() {
    local old=$1
    local new=$2

    if [ "$old" = "$new" ]; then
	return 1
    else
	# いったん /tmp/chk.$$ にバージョンストリングを書き込んで
	# sort の -V オプションで比較するようにしてみた．
	chkfile="/tmp/chk.$$"
	echo $old > $chkfile
	echo $new >> $chkfile
	sort -Vc $chkfile >& /dev/null
	chk=$?
	# echo "chk:$chk"
	rm -f $chkfile
	if [ "$chk" -eq 0 ] ; then
	    return 2
	else
	    return 0
	fi
    fi
}

check_build() {
    local old=`echo $1 | sed "s/[PBM]//" `
    local new=`echo $2 | sed "s/[PBM]//" `
    echo "old:$old, new:$new"
    if [ $new -gt $old ]; then
	return 1
    else
	return 0
    fi
}

usage() {
    echo "usage: $0 [-f] [-v] [-h] package(s)"
    echo "    -f force install mode(without version check)"
    echo "    -h help(this message)"
    echo 
    echo "non-canonical-versioned package(such as \"x264-20100716_git-i586-P1.tgz\")"
    echo " are cannot version-checked automatically. You need -f option to update such package(s)."
    echo
    exit
}

for opt in  $*
do
    case $opt in
	-f)
	    force_flag=1 ; shift ;;
	-h)
	    usage ;;
    esac
done

if [ $# = 0 ]; then
    usage
fi

for tmppkg in $* ; do
    pkg=`basename $tmppkg`
    base=`echo $pkg | cut -f1 -d'-'`
    vers=`echo $pkg | cut -f2 -d'-'`
    build=`echo $pkg | cut -f4 -d'-' | cut -f1 -d'.' `
    chk=`ls /var/log/packages | grep "^$base$" `

    if [ "$chk.x" != ".x" ]; then
	old_vers=`get_version $base`
	old_build=`get_build $base`
	ob=`echo $old_build | tr -d [0-9]`
	nb=`echo $build | tr -d [0-9]`
	if [ "$ob" = "P" -a "$nb" = "B" ]; then  # Bxx は Pxx に優先する
	    force_flag=1
	fi

	if [ "$force_flag.x" != ".x" ]; then
	    /sbin/removepkg $base
	else
	    # check_vers の返り値:
	    #   2 : 引数に指定した方が新しいのでupdateする
	    #   1 : check_vers では同じなのでビルド番号チェック
	    #   0 : 引数に指定した方が旧いか同じバージョンなのでupdateしない
	    check_vers $old_vers $vers
	    ver_test=$?
	    # echo "ver_test:$ver_test"
	    if [ $ver_test = "2" ]; then
		echo "removing $base-$old_vers"
		/sbin/removepkg $base
	    elif [ $ver_test = "0" ]; then
		echo "same or newer vesion($base-$old_vers) has been installed."
		echo "installation stopped for $tmppkg"	    
		continue
	    else
		check_build $old_build $build
		build_test=$?
		if [ $build_test != "0" ]; then
		    echo "removing $base-$old_vers ($old_build)"
		    /sbin/removepkg $base
		else
		    echo "same or newer vesion($base-$old_vers,$build) has been installed."
		    echo "installation stopped for $tmppkg"	    
		    continue
	        fi
	    fi
        fi
    fi
    /sbin/installpkg $tmppkg
done
