#!/usr/pkg/bin/perl
#####
# NAME
#	get-package-version
# VERSION
#	$Id$
# CHANGELOG
#	$Log$
# USAGE
#	get-package-version [options] tarballfile
#

$this = "get-package-version" ;

$g_print_major=0 ;
$g_print_minor=0 ;
$g_print_micro=0 ;

$g_tarball='' ;

$g_version_major=0 ;
$g_version_minor=0 ;
$g_version_micro=0 ;

main: {
	&analyze_argument() ;
	&get_version() ;
	&print_version() ;
}

sub error {
	local($msg) = @_ ;
	print STDERR "$this [ERROR] $msg\n" ;
	exit 1 ;
}

sub analyze_argument {
	local($opt) ;

	while(($opt = shift(@ARGV)) ne ''){
		if(!($opt =~ /^--/)){
			last ;
		} elsif ($opt eq '--major'){
			$g_print_major=1 ;
		} elsif ($opt eq '--minor'){
			$g_print_minor=1 ;
		} elsif ($opt eq '--micro'){
			$g_print_micro=1 ;
		} else {
			&error("can not recognize option \"$opt\"") ;
		}
	}
	$g_tarball = $opt || &error("tarball name is required") ;
}

sub get_version {
	local(@pathset, @verset, $filename) ;

	# remove path (directory names and slashes)
	@pathset = split(/\//, $g_tarball) ;
	$filename = $pathset[$#pathset] ;
	# print "tarball: $g_tarball, filename: $filename\n" ;

	# remove file extension
	$filename =~ s/.gz$// ;
	$filename =~ s/.bz2$// ;
	$filename =~ s/.Z$// ;
	$filename =~ s/.tar$// ;
	$filename =~ s/.tgz$// ;
	# print "filename(2): $filename\n" ;

	# remove file name "*-"
	$filename =~ s/^.*-// ;
	# print "filename(3): $filename\n" ;

	# get major, minor, micro version
	if($filename =~ /^([0-9]+)\.([0-9]+)\.([0-9]+)/){
		$g_version_major=$1 ;
		$g_version_minor=$2 ;
		$g_version_micro=$3 ;
	} elsif($filename =~ /^([0-9]+)\.([0-9]+)/){
		$g_version_major=$1 ;
		$g_version_minor=$2 ;
		$g_version_micro=0 ;
	} elsif($filename =~ /^([0-9]+)/){
		$g_version_major=$1 ;
		$g_version_minor=0 ;
		$g_version_micro=0 ;
	} else {
		&error("failed to get version of \"$g_tarball\"") ;
	}
}

sub print_version {
	if($g_print_major){ print "$g_version_major\n" ; }
	if ($g_print_minor){ print "$g_version_minor\n" ; }
	if ($g_print_micro){ print "$g_version_micro\n" ; }
	if(!$g_print_major && !$g_print_minor && !$g_print_micro){
		print "${g_version_major}.${g_version_minor}.${g_version_micro}\n" ;
	}
}

