#!/bin/bash
BASE_DIR=$(dirname $0)
FIND=/usr/bin/find
RPM_COMMAND_UBUNTU=/usr/bin/rpm2cpio
RPM_COMMAND_MAC=$BASE_DIR/rpm2cpio.sh

print_usage()
{
	echo "Usage: debuginfo -u|-m [options] [arguments]"
	echo "-u			ubuntu command"
	echo "-m			macos command"
	echo "Options:"
	echo "-r			extract two rpm package"
	echo "-d			extract one rpm package"
	echo "-l			show the file list in rpm package"
	echo "-f			find files"
}

find_file()
{
	cd $1
	find . -name $2
}

extract_2pkgs()
{
	echo $1
	echo $2
	echo $3
	cd $1

	case "$OS" in
		ubuntu)
			$RPM_COMMAND_UBUNTU $2 | cpio -imd
			$RPM_COMMAND_UBUNTU $3 | cpio -imd
			;;
		mac)
			$RPM_COMMAND_MAC $2 | cpio -imd
			$RPM_COMMAND_MAC $3 | cpio -imd			
			;;
		*)
			echo "unknown OS"
			print_usage
			exit 1
			;;
	esac
}

extract_pkg()
{
	echo $1
	echo $2
	cd $1

	case "$OS" in
		ubuntu)
			$RPM_COMMAND_UBUNTU $2 | cpio -imd
			;;
		mac)
			$RPM_COMMAND_MAC $2 | cpio -imd
			;;
		*)
			echo "unknown OS"
			print_usage
			exit 1
			;;
	esac
}

list_pkg()
{
	case "$OS" in
		ubuntu)
			$RPM_COMMAND_UBUNTU $1 | cpio -t
			;;
		mac)
			$RPM_COMMAND_MAC $1 | cpio -t
			;;
		*)
			echo "unknown OS"
			print_usage
			exit 1
			;;
	esac
}

if [[ -n $1 ]]; then
	case "$1" in
		-u)
			OS=ubuntu
			shift
			;;
		-m)
			OS=mac
			shift
			;;
		*)
			echo "must specify host OS"
			print_usage
			exit 1
			;;
	esac
else
	print_usage
fi

if [[ -n $1 ]]; then
	case "$1" in
		-f)
			if [[ "$#" -ne 3 ]]; then
				echo "find needs two arguments!"
				exit 1
			fi
			shift
			find_file $@
			;;
		-r)
			if [[ "$#" -ne 4 ]]; then
				echo "extract needs three arguments!"
				exit 1
			fi
			shift
			extract_2pkgs $@
			;;
		-d)
			if [[ "$#" -ne 3 ]]; then
				echo "extract needs two arguments!"
				exit 1
			fi
			shift
			extract_pkg $@
			;;
		-l)
			if [[ "$#" -ne 2 ]]; then
				echo "list needs an argument!"
				exit 1
			fi
			shift
			list_pkg $@
			;;
		*)
			echo "unknown option!"
			print_usage
			;;
	esac
else
	print_usage
fi



