#!/bin/sh
# PATH=/bin; export PATH

backup=backup
temp=archive-`date +'%Y-%m-%dT%H%M%S%Z'`
tar=archive.tar
input=Cipher.c

# deletes all the .o files
clean() {
	rm *.o
	return 0
}

# copies all the .c and .h files into your backup directory
backup() {
	echo Attempting to backup *.c, *.h, and Makefile in $backup/.
	# be sure $backup exists
	[ -d $backup ] || (mkdir $backup && return 1)
	for file in `ls *.c *.h Makefile`
	do
		[ -r $file ] && cp $file $backup
	done
	return 0
}

# TARs the contents of your source directory with anything and everything in
# it; TAR moved into your backup directory
archive() {
	echo Creating $backup/$tar:
	# be sure $backup exists
	[ -d $backup ] || (mkdir $backup && return 1)
	# assert $temp doesn't exist, copy files into $temp
	[ ! -d $temp ] || return 1
	mkdir $temp || return 1
	for file in `ls`
	do
		[ ! -d $file ] && cp $file $temp
	done
	tar -cvf $backup/$tar $temp
	rm -R $temp
	return 0
}

# shows how to use the command
help() {
	echo $0 –o \<filename\> [–clean] [–backup] [–archive] [-help]
	echo '-o        argument that indicates the name of the executable'
	echo '-clean    deletes all the .o files'
	echo '-backup   copies all the .c and .h files into the backup directory'
	echo '-archive  TARs the contents of your source directory; the TAR file is then'
	echo '          moved into your backup directory'
	echo '-help     shows how to use the command'
	return 0
}

# "whatever options are present the –o (lowercase) must always be present"
# ok . . . what about -archive, etc? whatever, it makes it easier to parse
if [ \( $# -lt 2 \) -o \( "$1" != "-o" \) ]; then
	help
	exit 1
fi
output=$2

# gcc
echo Compiling $input -\> $output
gcc -Wall -O3 -fasm -fomit-frame-pointer -ffast-math -funroll-loops -fasm \
-fomit-frame-pointer -ffast-math -funroll-loops -ansi -pedantic -o $output $input

# shift other args
while [ $# -ge 3 ]; do
	case "$3" in
	"-clean") boolClean=-1;;
	"-backup") boolBackup=-1;;
	"-archive") boolArchive=-1;;
	"-help") boolHelp=-1;;
	*) echo $3?;;
	esac
	shift
done
[ $boolClean ] && (clean || echo clean failed)
[ $boolBackup ] && (backup || echo backup failed)
[ $boolArchive ] && (archive || echo archive failed)
[ $boolHelp ] && (help || echo help failed)

exit 0
