#!/bin/sh
if [ ! "$1" ]; then
    printf "usage: extromfs.sh [romfs image] ([target directory])\n"
    printf "\tnote: You should be root.\n"
    exit 0
fi
if [ ! -f "$1" ]; then
    printf "%s not found.\n" $1
    exit 1
fi
TARGET=_$1
if [ "$2" ]; then
    TARGET=$2
fi
if [ -f "$TARGET" ]; then
    printf "%s is not directory.\n" $TARGET
    exit 1
fi
MNTDIR=mnt
if [ -f "$MNTDIR" ]; then
    printf "%s is not directory.\n" $MNTDIR
    exit 1
fi
if [ ! -d "$MNTDIR" ]; then
    mkdir mnt
    MKDIR=1
fi
mount -o loop $1 $MNTDIR
if [ $? != 0 ]; then
    printf "mount failed.(Are you root?)\n"
    if [ $MKDIR ]; then
	rm -rf $MNTDIR
    fi
    exit 1
fi
if [ ! -d "$TARGET" ]; then
    mkdir $TARGET
    if [ $? != 0 ]; then
	printf "mkdir failed.\n"
	umount $MNTDIR
	if [ $MKDIR ]; then
	    rm -rf $MNTDIR
	fi
	exit 1
    fi
fi
(cd $MNTDIR;tar cf - *)|(cd $TARGET;tar xf -)
if [ $? != 0 ]; then
    printf "copy failed.\n"
    rm -rf $TARGET
    umount $MNTDIR
    if [ $MKDIR ]; then
	rm -rf $MNTDIR
    fi
    exit 1
fi
umount $MNTDIR
if [ $MKDIR ]; then
    rm -rf $MNTDIR
fi
exit 0
