#!/bin/bash

# generate filename without directory:
FILENAME=$(basename $0)
CAT=$(which cat)

print_help()
{
##########################################################################
$CAT <<EOF

  $0

  author:      Karl Voit, shellscript@Karl-Voit.at

  date:        v0.1 2002-05-20 
               v0.2 2003-12-12 (docu)

  copyright:   GPL

  usage:       $FILENAME
               ... this will read in one diskette image
               $FILENAME 5
               ... this will read in five diskettes in a row (same name)

  description: This script generates an image of a floppy disk using dd

               Please email me suggestions for improvements and errors!
               I am still learning how to write good shell-scripts *g*

EOF
##########################################################################
}

## 2do:
##      * loop for set of disks
##      * 



########################################################
########################################################
########################################################
##                                                    ##
##                  PERSONALISATION                   ##
##                                                    ##
########################################################
########################################################
########################################################


# filenames to use for ...

DEFAULT_SIGNAL="/usr/share/sounds/users/SOUND/SHORTS/BLOOP.WAV"


# change to "done", if you changed all options above to _your_ needs!

CONFIGURED_="NOTdone"


########################################################




# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #

# --- normally you DON'T have to change anything below this line! --- #

# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #
# !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! #




########################################################
########################################################
########################################################
##                                                    ##
##               hardcoded configuration              ##
##                                                    ##
########################################################
########################################################
########################################################


## generates a timestamp like "2002_Jan_31_-_09h43m03s"
#TIMESTAMP1=`/bin/date +%Y_%b_%d_-_%Hh%Mm%Ss`

## generates a syslog-like timestamp like "Mar 16 09:19:50"
## lisa qmail:
#TIMESTAMP2=`/bin/date +"%b %d %H:%M:%S"`

#LOGFILE_BIN=/???path/"$TIMESTAMP".log


BIG_DISKETTE_SIZE="1474560"
SMALL_DISKETTE_SIZE="737280"


# change to "on" if you want to read the debug-messages (can be much) to trace
# down problems:
export DEBUG="off"


########################################################
########################################################
########################################################
##                                                    ##
##                   F U N C T I O N S                ##
##                                                    ##
########################################################
########################################################
########################################################

## ---------------------------------------------------------

myexit()
{
    doreport debug "function myexit($1) called"

    [ "$1" -lt 1 ] && echo "$FILENAME done."
    [ "$1" -gt 0 ] && echo "$FILENAME aborted with errorcode $1."

#optionally    [ "$1" -gt 0 ] && do_sound_error

    exit $1
}


## ---------------------------------------------------------


## check, if some files needed are not found
testiffound()
{
    doreport debug "function testiffound($1) called"

  if [ -z "$2" ]; then
    doreport debug "The tool \"$1\" is missing because \"$2\" is empty."
    doreport notify "The tool \"$1\" could not be located (missing?)"
    export SOMETHINGMISSING="yes"
  fi
}


## ---------------------------------------------------------


doreport_internal_writestring()
{
## !! for use withing function "doreport" only !!
## prints out all strings on stdout

        echo
        echo "===$1============================================"
        echo "                                                 $FILENAME"


## FIXXME:
## 2DO: loop instead of this quick-hack!!!

        if [ ! -z "$2" ]; then
	    echo "$2"
        fi
        if [ ! -z "$3" ]; then
	    echo "$3"
        fi
        if [ ! -z "$4" ]; then
	    echo "$4"
        fi
        if [ ! -z "$5" ]; then
	    echo "$5"
        fi
        if [ ! -z "$6" ]; then
	    echo "$6"
        fi
        if [ ! -z "$7" ]; then
	    echo "$7"
        fi
        if [ ! -z "$8" ]; then
	    echo "$8"
        fi

        echo
        echo "===============================================================";
        echo

}



## ---------------------------------------------------------


doreport()
{
## reports the parameter to the stdout

## usage: (shortnote|notify|error|debug) string1 [string2] [string3] [...] [string7]

## NEEDS: doreport_internal_writestring


    case "$1" in

    "shortnote") 
	echo "$FILENAME: $2 $3 $4 $5 $6 $7";;

    "notify") 
	doreport_internal_writestring " notification ==" "$2" "$3" "$4" "$5" "$6" "$7";;

    "error") 
        doreport_internal_writestring " ERROR =========" "$2" "$3" "$4" "$5" "$6" "$7";;

    "debug") 
        ## debugs the script
        if [[ "$DEBUG" = "on" ]]; then echo "$TIMESTAMP $FILENAME: DEBUG: $2 $3 $4 $5 $6 $7"; fi;
        echo "do nothing" >/dev/null;;

    *)
        doreport_internal_writestring " INTERNAL ERROR " "An error occured, while calling function \"doreport\":" "The parameter that was given ($1) has no target/handle." "Aborting.";
        myexit 1;;

    esac
}




## ---------------------------------------------------------

ask()
{
## asks something (parameter 1) the user

  echo
  echo "=== question =================================================="
  echo "                                                 $FILENAME"
  echo "$1"
  echo
  echo "==============================================================="
  echo

## example: ##  ask "Do you want this?"
## example: ##  read ANSWER
## example: ##  echo  
## example: ##  case "$ANSWER" in
## example: ##  
## example: ##  y)
## example: ##    CDCPY_docover ;;
## example: ##  *)
## example: ##    echo "  OK, maybe you're right." ;
## example: ##    echo "  We don't need these fancy stuff anyway ..." ;
## example: ##    echo ;;
## example: ##
## example: ##  esac

}


## ---------------------------------------------------------

## plays the soundfile using "play"
play_sound()
{
    ## wether "play" is avaliable is checked before
    if [[ ! -z "$1" ]] ; then $PLAY "$1" >/dev/null; fi
}


## ---------------------------------------------------------


precondition_asserts()
{
## * test for things that are needed
## * check, if caller = root-user
## * check, if everything was configured by the user
## * check, if a parameter is given:

      export SOMETHINGMISSING="no"

      DD=$(which dd)
      testiffound dd $DD
      
      PLAY=$(which play)
      testiffound play $PLAY
      
      LS=$(which ls)
      testiffound ls $LS
      
      EXPR=$(which expr)
      testiffound expr $EXPR
      
##	MV=$(which mv)
##	testiffound cdrdao $MV
##	
##	CAT=$(which cat)
##	testiffound cat $CAT
	
	GREP=$(which grep)
	testiffound grep $GREP
	
##	HEAD=`which head`
##	testiffound head $HEAD
	
	AWK=`which awk`
	testiffound awk $AWK
	
##	SED=`which sed`
##	testiffound sed $SED
##	
##	FIND=`which find`
##	testiffound find $FIND
##	
##	DATE=`which date`
##	testiffound date $DATE
##	
##	CHOWN=`which chown`
##	testiffound chown $CHOWN


    ## check, if any tool was NOT found
    doreport debug "CHECK: any tool missing?"
    if [ "$SOMETHINGMISSING" = "yes" ]; then
      print_help
      doreport error "One or more tool(s), that are needed are missing! (See output above!)" "Please make sure, that you those tools are installed properly and try again." "aborting."
      myexit 2
    fi



    ## check, if everything was configured by the user
    if [ ! "$CONFIGURED_" = "done" ]; then
	  print_help
	  doreport "error" "Please make sure, that you checked/modified all options" "to meet your requirements!" "(see section "PERSONALISATION" in file $0)"
	  myexit 3
    fi
    
    
    
    ## check, if a parameter is given:
    if [ -z "$1" ]; then
	 #print_help
	 doreport "debug" "\$1 == \"$1\""
	 doreport "notify" "no parameter 1 for the image-file found!" "Using standard-filename \"floppy.img\""
	 IMAGE_FILE="floppy"

##	   ask "Do you want to read in with the (s)tandard-filename or (e)xit?"
##	   read ANSWER
##	   echo  
##	   case "$ANSWER" in
##	   
##	   s|S|y|Y)
##	     IMAGE_FILE="floppy" ;;
##	   *)
##	     myexit 1 ;;
##	 
##	   esac
	 
    else
	 IMAGE_FILE="$1"
    fi
    
    ## check, if a parameter is given:
    if [ -n "$2" ]; then
	doreport debug "Second parameter \"$2\" found."
	doreport "shortnote" "I recognised a second parameter \"$2\" which defines the amount of images."
	IMAGE_COUNT="$2"
    else
	IMAGE_COUNT=""
    fi

    doreport debug "<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< all checks OK!"
    export PRECONDITIONS_CHECKED="yes"


}


## ---------------------------------------------------------


check_filesize()
{

    CHK_FILESIZE_RESULT="not OK"

    CHK_FILESIZE=`$LS -la|$GREP "$1"|$AWK '{ print $5 }'`

    doreport "debug" "determined file-size is \"$CHK_FILESIZE\""

    if [ "$CHK_FILESIZE" == "$BIG_DISKETTE_SIZE" ]
    then
	doreport "debug" "filesize of image seems to be OK for 1.44MB."
	CHK_FILESIZE_RESULT="OK"
    else
	doreport "debug" "The filesize of the image differs from standard 1.44MB-diskette!"
    fi

    if [ "$CHK_FILESIZE" == "$SMALL_DISKETTE_SIZE" ]
    then
	doreport "debug" "filesize of image seems to be OK for 720kB."
	CHK_FILESIZE_RESULT="OK"
    else
	doreport "debug" "The filesize of the image differs from standard 720kB-diskette!"
    fi


#    if [ "$CHK_FILESIZE_RESULT" == "OK" -a $CHK_EXITSTATUS -eq 0 ]
    if [ "$CHK_FILESIZE_RESULT" == "OK" ]
    then
	doreport "shortnote" "(The creation of the disk image was succesfully.)"
    else
	doreport "error" "There was an error reading the diskette!" "Filesize doesn't fit 720kB nor 1.44MB-Diskette."
    fi


}


## ---------------------------------------------------------

postcondition_asserts()
{

## * deletes temporary files
## * ...

##  if [ -z "???filename" ]; then
##    ???
##  fi

echo "donothing" >/dev/null

}



########################################################
########################################################
########################################################
##                                                    ##
##                S C R I P T                         ##
##                                                    ##
########################################################
########################################################
########################################################

## test for important stuff:
precondition_asserts "$1" "$2" "$3" "$4" "$4" "$5" "$6" "$7" "$8" "$9"



## parse parameter 1
case "$1" in

    "help"|"--help"|"?"|"/?")
	doreport debug "Parameter help|--help|?|/? detected"
	print_help;
	myexit 0;;

##    "kill"|"stop")
##	  doreport debug "Parameter kill|stop detected"
##	  blablabla;;
##
##    *)
##	  doreport debug "Unknown parameter.";
##	  doreport error "The parameter you typed in ($1) could not be recognised!" "It will ignored and the script halted.";
##	  print_help;
##	  myexit 1;;

esac



if [ -z "$IMAGE_COUNT" ]
then
    ###################################
    ## do a simple copy of ONE image ##
    ###################################

    doreport "notify" "Everything seems to be OK, starting to read out the floppy ..." "May take long - best-case approx. 50 seconds."

    $DD if="/dev/fd0" of="$IMAGE_FILE.img" count=1 bs=1440k >/dev/null

    CHK_EXITSTATUS=$?

    echo " "

    if [ $CHK_EXITSTATUS -eq 0 ]
    then
	doreport "debug" "Exit-status of dd was OK"
    else
    	doreport "debug" "dd had exit status != 0"
    	doreport "error" "An error occured during reading the floppy disk."
    fi

    check_filesize "$IMAGE_FILE.img"

    play_sound $DEFAULT_SIGNAL

else

    #################################################
    ## make a set of images from 1 to $IMAGE_COUNT ##
    #################################################

    counter=1

    while [ $counter -le $IMAGE_COUNT ]
    do

	echo " "
	doreport "shortnote" "[diskette $counter] Please insert diskette number $counter (of $IMAGE_COUNT) and press ENTER"
	read DUMMYVARIABLE

	doreport "shortnote" "[diskette $counter] (starting to read out the floppy - usually takes long: best-case 50 seconds)"

	## append leading zero for all interations < 9:
	if [ $counter -le 9 ]
	then
	    CURRENT_FILENAME="$IMAGE_FILE"_0"$counter".img
	else
	    CURRENT_FILENAME="$IMAGE_FILE""$counter".img
	fi

	doreport "debug" "doing interation for file $IMAGE_FILE number $counter"

	## do the actual thing (wow! at last we can really _do_ something ;-)
	$DD if="/dev/fd0" of="$CURRENT_FILENAME" count=1 bs=1440k >/dev/null

	if [ $? -eq 0 ]
	then
	    doreport "shortnote" "[diskette $counter] (The readout of the disk image number $counter was succesfully.)"
	else
	    doreport "debug" "dd had exit status != 0"
	    doreport "error" "[diskette $counter] An error occured during reading the floppy disk number $counter."
	fi

	check_filesize "$CURRENT_FILENAME"

	## increment counter
	counter=`$EXPR $counter + 1`

	play_sound $DEFAULT_SIGNAL

    done

fi



########################################################


## test for important stuff:
postcondition_asserts

myexit 0


########################################################
##                      E N D                         ##
########################################################



