#!/bin/bash
#
# Author: Francesca Ferrari
# Program name: mkfile
# Date: 05/06/2012
#
# To run: mkfile [-s SIZE] [-n QUANTITY] FILE1 ...
# -s: mkfile creates FILE1 FILE2... of the SIZE specified
# -n: mkfile creates QUANTITY of empty FILE1 ... 
# (eg. for FILE1: FILE1.1, FILE1.2, ... , FILE1.QUANTITY).
# -s and -n: mkfile creates QUANTITY of FILE1 ... 
# (eg. for FILE1: FILE1.1, FILE1.2, ... , FILE1.QUANTITY).
# The size of the created file is specified by SIZE.
# if -s and -n are not provided, mkfile creates FILE1 ...
#

help_mkfile()
{ 
  local prog=$(basename $0)
  echo "$prog [-s SIZE] [-n QUANTITY] [-h] FILE1 ..." 
}

fatal() 
{
  local prog=$(basename $0)
  echo -e "$prog: ERROR: $*" >&2
  help_mkfile >&2
  exit 1
}

get_integer_input()
{
  local input=$1
  local isnum=$(echo "$input" | sed 's/^[1-9][0-9]*//')
  if [ ! -z "$isnum" ]; then
     fatal "'$input' must be a valid number"
  fi
  echo "$input"
}

# Input validation and command line parsing
[ $# -eq 0 ] && fatal "Missing arguments"

while [ $# -gt 0 ]; do
  case "$1" in
  -h) help_mkfile 
      exit 0;;
  -s) if [ $# -eq 1 ]; then
	fatal "-s requires an argument"
      fi
      shift
      size=$(get_integer_input "$1");;
  -n) if [ $# -eq 1 ]; then
	fatal "-n requires an argument"
      fi
      shift
      quantity=$(get_integer_input "$1");;
  -*) fatal "illegal option '$1'";;
  *)  break;;
  esac
  shift
done

[ $# -eq 0 ] && fatal "No filename supplied"

# end input validation and command line parsing

if [ -z "$size" -a -z "$quantity" ]; then
  while [ $# -gt 0 ]; do
      touch "$1"
    shift
  done
  exit 0
fi

if [ -n "$quantity" -a -z "$size" ]; then
  while [ $# -gt 0 ]; do
    for ((i=1; i<=quantity; i++)); do 
      touch "$1".$i  
    done
    shift
  done
  exit 0
fi

if [ -n "$size" -a -z "$quantity" ]; then
  while [ $# -gt 0 ]; do
     dd count=1 bs=$size if=/dev/urandom of="$1" &>/dev/null
    shift
  done
  exit 0
fi

if [ -n "$size" -a -n "$quantity" ]; then
  while [ $# -gt 0 ]; do
    for ((i=1; i<=quantity; i++)); do 
      dd count=1 bs=$size if=/dev/urandom of="$1".$i &>/dev/null
    done
  shift
  done
  exit 0  
fi

exit 0
