# 
# Purpose: Script to compress all files of given extension to individual archives using 7z
# Usage  : zipeach.sh <extension-without-prefix-dot> i.e zipeach.sh n64
# Author : r3dux
# Date   : 16/04/2009
#
#!/bin/bash

found=false       # Flag to keep track of whether we've found a file or not
count=0           # File counter
got7z=$(which 7z) # Use "which" to check if there's a copy of 7z on the system

# If there's no copy of 7z - we're not going to be doing much compressing... Exit stage left.
if [ "$got7z" = "" ]; then
    echo "No copy of 7z found on system! Try running: sudo apt-get install 7z"
    exit 0
fi

# If we have 7z, and have been given file extension parameter...
if test "$1"; then
	 	
	# Stop the script from entering an infinite loop should user mistakenly enter 7z as filetype to compress...
 	if [ $1 = "7z" ]; then
 	    echo "Recursion neatly sidestepped - no 7z filetypes ya scurvy seadog! =P"
 	    exit 0
 	fi	 	
	 	
 	echo "Starting zipeach..."
	 	
 	# For each file with the given extension in the current directory...
	for file in ./*.$1; do
  		
		# If a file exists with given extension...
		if [ -e "$file" ]; then
			
			# Set our found flag, so no error is displayed when we reach the last file
			found=true
										
			# Compress the file with maximum compression (-mx9) and use multiple threads for multiCPU machines (-mmt)
			# NOTE: Remove -mmt flag to run this on a single CPU box...
			7z a -mx9 -mmt "$file".7z "$file"
  					
			# Increment our file counter
			let count+=1
		else
			# If no file of required extension has been found then notify user and quit
			if [ $found = false ]; then
					    
				echo "No files of extension .$1 found in current directory!"
				exit 0
					    
			fi # End of if $found = false
					
		fi # End of if file exists condition				
			
	done # End of for each file loop
		
	# Exit when all files compressed
	echo # Cheap blank line =P
	echo "Zipeach completed. $count files of extension .$1 found and compressed."
  	exit 0 
  		
else
	# No extension parameter given? No worky...
	echo 'Please run the script with an extension to compress i.e. "zipeach n64" to compress each .n64 file into its own 7z archive.'
	exit 0  		
fi

