#!/bin/bash

appname=${0##*/}

def_mnt_parent=/mnt/vfs.
test -e "${1:?Parameter missing

mkvfs 0.1.2004062216 -- Create a virtual filesystem
Copyright (C) 2004  Thomas Lahn <mehl@PointedEars.de>
Distributed under the terms of the GNU General Public License (GPL).
See COPYING file or <http://www.fsf.org/copyleft/gpl.html> for details.

USAGE: $appname IMG_FILE [SIZE [MOUNT_POINT [FS_TYPE]]]

  IMG_FILE       File system image file.  Required.
  SIZE           Size of the new file system in KiB.  The default is 60,
                   which appears to be the minimum size of an ext2 fs.
                   The block size of the new file system is determined
                   automagically by the respective mkfs program.
  MOUNT_POINT    Directory on which the filesystem should be mounted.
                   The default is ${def_mnt_parent}FS_TYPE.
  FS_TYPE        File system type.  The default is ext2.

EXIT CODES

  0    No error
  1    Required parameter missing
  2    File system image file existed and resizing/overwriting it was denied
  3    Error unmounting image file system
  4    Error creating the file system image file
  5    Error unmounting the file system mounted to the specified mount point
  6    Error creating the virtual file system
  7    Error creating the mount point for the virtual file system
  8    Error mounting the virtual file system

CREDITS

  Thanks to Christoph \'Mehdorn\' Weber <ich-reweb@gmx.net> for his support.

AVAILABILITY

  The author\'s latest can be obtained from
  <http://PointedEars.de/tools/system/mkvfs/>.
  Report bugs to <mkvfs@PointedEars.de>.}" &&
{
  read -p "${appname}: WARNING: File '$1' exists.  Overwrite (y/n)? " -n 1 reply
  echo
  test "$reply" != 'y' -a "$reply" != 'Y' &&
  {
    read -p "Resize existing file (y/n)? " -n 1 reply
    echo
    if test "$reply" = 'y' -o "$reply" = 'Y'; then
      echo "NOTE: The resize feature is experimental." >&2
      exit 0
    else
      exit 2
    fi
  }
}

test -n "`grep "$1" /proc/mounts`" &&
{
  umount -v "$1"
  test $? -ne 0 && exit 3
}

dd if=/dev/zero of="$1" bs=1k count=${2:-60}
test $? -ne 0 && exit 4

fstype=${4:-ext2}
mntpt=${3:-$def_mnt_parent$fstype}
test -n "`grep "$mntpt" /proc/mounts`" &&
{
  umount -v "$mntpt"
  test $? -ne 0 && exit 5
}
mkfs -t $fstype -v "$1"
test $? -ne 0 && exit 6

mkdir -v "$mntpt" 2>/dev/null
if test -d "$mntpt"; then
  mount -o loop -t $fstype -v "$1" "$mntpt"
  test $? -ne 0 && exit 8
else
  exit 7
fi
