#!/bin/bash

# This script creates a new FAT32 virtual disk for a MacOS or a Linux
# platform.

# Defining some variables.
clusters_nr=65536   # Total number of clusters of the new virtual disk.
sector_size=512     # Size of a sector (in bytes).
secsperclus=8       # Count of sectors per cluster.
rsectors_nr=4096    # Count of Reserved Region sectors.

# FAT32: the DATA Region starts at cluster #2.
data_clust=$clusters_nr-2

# Computing the count of DATA Region sectors.
let "dsectors_nr    = data_clust * secsperclus"

# Computing the count of FAT Region sectors.
let "fsectors_nr    = (clusters_nr * 4) / 512"

# An FAT32 disk image is traditionally structured as follows:
#   - MBR sector,
#   - Reserved Region sectors,
#   - FAT Region sectors,
#   - DATA Region sectors.
# Since our virtual disk image is not partitioned, its first sector is not a
# MBR but a VBR.
let "sectors_nr     = dsectors_nr + fsectors_nr + rsectors_nr + 1" 

# Getting the system kernel name then print it out.
platform=`uname`
echo "Dectected platform: $platform"

# If we are running on MacOS:
if [[ $platform == "Darwin" ]]; then
    case $1 in 
        # Creating a disk image.
        create)
            # Checking if the string given by the second script argument size 
            # is 0.
            if [[ -z $2 ]]; then
                echo "Please enter the name of the virtual disk image to be "
                echo "created as the second argument of this script!"
                exit 1
            fi

            echo "Creating <$2.dmg>"
            # Defining additional arguments to format the virtual disk in the
            # filesystem implied by -fs option.
            # -F <fat_type>         : FAT type.
            # -c <secs_per_clus>    : count of sectors per cluster.
            # -n <fats_nr>          : count of FAT copies.
            # -r <rsvd_secs_nr>     : count of Reserved Region sectors.
            # -k <bbs>              : Backup Boot Sector (0xFFFF if no backup).
            fsargs="-F 32 -c $secsperclus -n 1 -r $rsectors_nr -k 0xffff"

            # Invoking the appropriate MacOS command to get the work done.
            # -fs       <filesystem>    : causes a filesystem of type
            #                             <filesystem> to be written to the
            #                             image.
            # -volname  <volname>       : the newly created filesystem will 
            #                             be named <volname>.
            # -layout   <layout>        : specifies the partition layout of the
            #                             image (NONE creates an image with no
            #                             partition map).
            # -sectors  <sector_count>  : specifies the size of the image file
            #                             in 512-byte sectors.
            # -ov                       : overwrites an existing file.
            # -type                     : specifies the format of empty
            #                             read/write images.
            hdiutil create -fs MS-DOS           \
                           -volname virtualdisk \
                           -layout NONE         \
                           -sectors $sectors_nr \
                           -ov                  \
                           -fsargs "$fsargs"    \
                           -type "UDIF"         \
                           $2
            ;;

        # Attaching the disk image as a device.
        attach)
            hdiutil attach $2
            ;;
       
        # Detaching the disk image and terminating any associated process.
        detach)
            hdiutil detach $2
            ;;

        # Printing out information about the disk image.
        info)
            hdiutil imageinfo $2
            ;;

        # The first argument of this script should tell it what to do.
        *)
            echo "Enter one of the following verbs as the first argument:"
            echo "  - create <image>    : create the new disk image <image>."
            echo "  - attach <image>    : attach the created disk image "
            echo "                        <image> to the system and mount it."
            echo "  - detach <dev_name> : detach the device <dev_name>."
            echo "  - info   <image>    : print out information about the "
            echo "                        <image> disk image."
            echo ""
            echo "EXAMPLES:"
            echo "./create_dmg create disk_image"
            echo "./create_dmg attach /path/to/disk_image.dmg"
            echo "./create_dmg detach /dev/disk5"
            echo "./create_dmg info   /path/to/disk_image.dmg"
            ;;
    esac

# If we are running on Linux:
elif [[ $platform == "Linux" ]]; then
    case $1 in
        create)
            if [[ -z $2 ]]; then
                echo "Please enter the name of the virtual disk image to be "
                echo " created as the second argument of this script!"
                exit 1
            fi

            echo "Creating disk image <$2>"
            let "sectors_nr = (sectors_nr - 1) / 2"

            # Looking for the appropriate Linux command which will perform the
            # work.
            CREATE_DISK=$(command -v mkfs.vfat                  ||  \
                          command -v /sbin/mkfs.vfat            ||  \
                          command -v /usr/sbin/mkfs.vfat        ||  \
                          command -v /usr/local/sbin/mkfs.vfat)

            if [[ -z ${CREATE_DISK} ]]; then
                echo "ERROR: command mkfs.vfat not found!"
                exit 1
            fi
    
            # Invoking the previously found command to create an MS-DOS 
            # filesystem on the device <device> of size <block_count>.
            # -C                    : creates the file given as <device> on the
            #                         command line and writes the to-be-created
            #                         filesystem to it. Used to create the new
            #                         filesystem in a file instead of on a real 
            #                         device.
            # -F <fat_type>         : specifies the type of FAT used.
            # -f <fats_nr>          : specifies the number of FAT copies in the
            #                         filesystem.
            # -R <rsvd_secs_nr>     : selects the number of reserved sectors.
            # -s <secs_per_clus>    : specifies the number of disk sectors per
            #                         cluster.
            # -S <sector_size>      : specifies the number of bytes per logical
            #                         sector.
            # -v                    : verbose execution.
            # <device>              : special file corresponding to the device.
            # <block_count>         : number of blocks on the the device.
            ${CREATE_DISK} -C               \
                           -F 32            \
                           -f 1             \
                           -R $rsectors_nr  \
                           -S $sector_size  \
                           -s $secsperclus  \
                           -v               \
                           $2.dmg           \
                           $sectors_nr      \
            ;;
        
        *)
            echo "Enter 'create' as the first argument to create a disk image."
            echo ""
            echo "EXAMPLES:"    
            echo "./create_dmg create disk_image"
            ;;
    esac

else
    echo "The following platform is not supported: $platform"
fi
