#!/bin/bash

# I keep getting files from windows machines where *all* files have the execute
# bit set. This script recurses and attempts to sort out the permission bits
# based on whether file(1) thinks it is executable or not. It makes all
# directories executable (in case you did "chmod -R -x *" in an earlier
# attempt).

# This script should be called using its full path (or put it in your path
# somewhere); ie do *not* call it with ./sort_executables

set -e

IFS="" # needed so that read doesn't throw away spaces

# loop through all file+directory names, but ignore '.'
find . -maxdepth 1 | while read a
	do if [ "$a" != . ] ; then
		# recurse into directories, but not if it is a link, because
		# could get into infinite cycles
		if [ -d "$a" -a ! -h "$a" ] ; then
			chmod +x "$a"
			cd "$a"
			"$0"
			cd ..
		else
			# Sort out executable bit of files based on file(1)
			if file "$a" 2>&1 | grep executable &> /dev/null ; then
				chmod +x "$a"
			else
				chmod -x "$a"
			fi
		fi
	fi
done
