#! /bin/sh
#
#   diskinfo.sh -- ディスクの情報を得る
#
#	0.0: Feb. 18, 2010 by Dai ISHIJIMA (for Live CD)
#	0.1: Dec. 25, 2022
#

temp=/tmp/diskinfo.$$

trap 'rm -f $temp*; exit 1' 1 2 15

mode=byte
while [ $# -gt 0 ]; do
	case x"$1" in
	    # ディスクのサイズ
	    x-b)
		mode=byte
		;;
	    x-s)
		mode=suffix
		;;
	    x-c)
		mode=camma
		;;
	    x-d)
		FLAVOR=DEBUG
		shift
		abytes="$1"
		;;
	    x-o)
		mode='os'
		;;
	    x-*)
		echo "Usage: $0 [-b|-m] disk" 1>&2
		exit 1
		;;
	    *)
		break
		;;
	esac
	shift
done

if [ $# -ne 1 ]; then
	echo "Usage: $0 [-[bsc] disk" 1>&2
	exit 1
fi

####disk=`echo "$1" | sed 's/^.dev.//'`
disk=$1
if [ ! -r /dev/$disk ]; then
	echo "$0: can't to open /dev/$disk" 1>&2
#	exit 1
fi

case x"$FLAVOR" in
    xDEBUG)
	bytes="$abytes"
	;;
    xBSD)
	if fdisk $disk > $temp.out 2>/dev/null; then
		cat $temp.out | sed -n /^cyl/p | sed -n 1p |
		sed 's|[a-z/]*=| |g' | sed 's/(.*)//' | sed 's/  */*/g' |
		sed 's/\(.*\)/1\1512/' > $temp.2
		bytes=$(( `cat $temp.2` ))
	else
		echo "$0: can't get disk information: $disk" 1>&2
		exit 1
	fi
	;;
    x*)
	bytes=0
	if fdisk -l /dev/$disk > $temp.out 2>/dev/null; then
	    bytes=`cat $temp.out |
		sed -n '/^Disk .dev./p' | awk '{print 0 + $5}'`
	else
	    echo "$0: can't get disk information: $disk" 1>&2
	    exit 1
	fi
	;;
esac

case "x$bytes" in
	x)
		bytes=0
		;;
esac

case x"$mode" in
	xbyte*)
		echo $bytes
		;;
	xcamma*)
		echo $bytes | rev | sed 's/\(...\)/\1,/g' | rev | sed 's/^,//'
		;;
	xsuffix*)
		b=$bytes
		s='n'
		while [ $b -gt 0 ]; do
			q=$b
			b=$(( $b / 1024 ));
			case x"$s" in
				xn)
					s=""
					;;
				x)
					s="k"
					;;
				xk)
					s="M"
					;;
				xM)
					s="G"
					;;
				xG)
					s="T"
					;;
				x[TX])
					s="X"
					;;
			esac
		done
		echo "$q$s"
		;;
	xos)
		cat $temp.out | sed -n '/^Disk .dev./p'
		cat $temp.out | sed -n /^cyl/p | sed -n 1p
		;;
	*)
		echo $bytes
		;;
esac

rm -f $temp*

exit 0
