#!/bin/sh
PATH=/bin:/usr/bin:/sbin:/usr/sbin export PATH

#------------------------------------------------------------------------------
#  firstbootconfig.sh
#  Copyright 2010 Andrew MacKenzie
#  Andrew MacKenzie, andrewmackenzie@mac.com
#  
#  Understand that this script is offerred to you as is, without any warranty
#  whatsoever.  Use at your own risk.
#------------------------------------------------------------------------------

#------------------------------------------------------------------------------
#  Global Variables
#------------------------------------------------------------------------------
scriptVersion="1/1/2010 303pm"
thisScript="$(basename "$0")"

thisHWAddress="$(ifconfig en0 | awk ' /ether/ { print $2 }')"
myHostname="$(hostname -s)"
myOS="$(sw_vers -productVersion)"
myRouter=$(ipconfig getpacket en0 | awk -F ': ' '/router/{ print $2 }' | tr -d '{}')
thisComputerName="$(systemsetup -getcomputername | cut -c 16-)"
thisLocalSubnetName="$(systemsetup -getlocalsubnetname | cut -c 20-)"

#------------------------------------------------------------------------------
#  Functions
#------------------------------------------------------------------------------
function writelog {
	logger -t "$thisScript" "${1}"
	echo "$(date '+%b %d %H:%M:%S') $myHostname $thisScript -- ${1}"
}


function checkroot {
	if [ "$(whoami)" != "root" ] ; then
		writelog "Must be run as root...exiting"
		exit 1 
	else
		writelog "Running as root."
	fi
}


function EnableSSHforUser {
# Thanks to Reed Stoner for his contributions to the remote desktop listserv
	writelog "Enabling SSH for User $1"
	# first turn on SSH via systemsetup
	systemsetup -setremotelogin on
	
	theUserGUID=$(dscl . read /Users/$1 GeneratedUID | awk -F ': ' '{ print $2 }')
	
	# Now check to see if the ssh access group already exists (it shouldn't, but check)
	if [ "$(dscl . read /Groups/com.apple.access_ssh | grep RecordName)" ] ; then 
	
		if [ "$(dscl . read /Groups/com.apple.access_ssh | grep $1)" ] ; then 
			writelog "User $1 already has SSH access"
		else
			writelog "com.apple.access_ssh exists, $1 not a member"
			# Add the user shortname to the group
			dscl . append /Groups/com.apple.access_ssh user $1
			# Add the user GUID to the groupmembers
		    dscl . append /Groups/com.apple.access_ssh groupmembers $theUserGUID 
		fi
		
	else
		writelog "com.apple.access_ssh doesn't exist"
		# There wasn't a group, so we have to create it
		# These next two lines figure out the next highest GID for any new group
		# The first gets the max gid of all existing groups
		nextGID="$(dscl . list groups | while read thegroup ; do dscl . read /Groups/$thegroup gid | awk -F ': ' '{ print $2 }' ; done | sort --numeric-sort | tail -n 1)"
		# Then we add 1 to get the next available gid number
		(( nextGID++ ))
		
		dscl . create /Groups/com.apple.access_ssh
		dscl . create /Groups/com.apple.access_ssh gid "$nextGID"
		dscl . create /Groups/com.apple.access_ssh realname "Remote Login Group"
		dscl . append /Groups/com.apple.access_ssh users $1
		dscl . append /Groups/com.apple.access_ssh groupmembers $theUserGUID 
	fi
}


function FindMySite {
# Based on router address, we can determine which building & network we're on

	myRouter=$(ipconfig getpacket en0 | awk -F ': ' '/router/{ print $2 }' | tr -d '{}')
	writelog "myRouter is $myRouter"
	
	case $myRouter in
		10.0.0.1)
			writelog "This machine is at HQ."
			mySSID="HQWireless"
			mySSIDpass="abc123"
			myTimeZone="America/Chicago"
			myTimeServer="hq-time.example.com"
			myOD="hq-odm.example.com"
			;;
		10.1.*.1)
			writelog "This machine is at Pink."
			mySSID="PinkWireless"
			mySSIDpass="P4s5w0rd"
			myTimeZone="America/New_York"
			myTimeServer="pink-time.example.com"
			myOD="pink-odr.example.com"
			;;
		10.2.*.1)
			writelog "This machine is at Blue."
			mySSID="GoBlue"
			mySSIDpass="P4s5w0rd"
			myTimeZone="America/Chicago"
			myTimeServer="blue-time.example.com"
			myOD="blue-odr.example.com"
			;;
		10.3.*.1)
			writelog "This machine is at Green."
			mySSID="GreenZone"
			mySSIDpass="P4s5w0rd"
			myTimeZone="America/Denver"
			myTimeServer="green-time.example.com"
			myOD="green-odr.example.com"
			;;
		*)
			writelog "Unknown location, or does not have ethernet plugged in."
			mySSID="HQWireless"
			mySSIDpass="abc123"
			myTimeZone="America/Central"
			myTimeServer="hq-time.example.com"
			myOD="hq-odm.example.com"
			;;
		esac

}


function SetSiteSettings {

	FindMySite

	myOS=$(sw_vers -productVersion)
		
	case $myOS in 
		10.5*)
			writelog "$myOS is Leopard"
			writelog "Setting timezone to $myTimeZone, using $myTimeServer"
			systemsetup -settimezone "$myTimeZone"
			systemsetup -setnetworktimeserver "$myTimeServer"
			systemsetup -setusingnetworktime on
			writelog "Turning off IPv6 for Ethernet and AirPort"
			networksetup -setv6off AirPort
			networksetup -setv6off Ethernet
			writelog "Enable ARD for user localadmin"
			/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -access -on -users admin -privs -all -restart -agent -menu
			;;
		10.6*)
			writelog "$myOS is Snow Leopard"
			writelog "Adding wireless $mySSID"
			networksetup -addpreferredwirelessnetworkatindex AirPort "$mySSID" 1 WPA2 "$mySSIDpass"
			networksetup -setairportpower AirPort off
			sleep 2
			networksetup -setairportpower AirPort on
			writelog "Setting timezone to $myTimeZone, using $myTimeServer"
			systemsetup -settimezone "$myTimeZone"
			systemsetup -setnetworktimeserver "$myTimeServer"
			systemsetup -setusingnetworktime on
			writelog "Turning off IPv6 for Ethernet and AirPort"
			networksetup -setv6off AirPort
			networksetup -setv6off Ethernet
			writelog "Enable ARD for user localadmin"
			/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart -activate -configure -access -on -users admin -privs -all -restart -agent -menu
			;;
		*)
			writelog "$myOS is an unsupported OS"
			;;
	esac

}


function ReIndexGBLoops {

	writelog "Reindexing GarageBand Loops"
	Indexer="/Library/Receipts/GarageBand_Loops.pkg/Contents/Resources/ALPIndex.app/Contents/MacOS/ALPIndex"
	rm -rf "/Library/Audio/Apple Loops Index/*"
	$Indexer "/Library/Audio/Apple Loops/Apple/iLife Sound Effects/"	
	$Indexer "/Library/Audio/Apple Loops/Apple/Apple Loops for GarageBand/"

}


function AnonBindOD {
	
	writelog "My OD Server is $myOD"
	writelog "Starting BindOD"
	dsconfigldap -a $myOD -v

	dscl /Search -create / SearchPolicy CSPSearchPath
	dscl /Search -append / CSPSearchPath /LDAPv3/$myOD
	writelog "Ending BindOD"

}


function AddComputerRecord {

	writelog "AddComputerRecord - Starting AddComputerRecord"
	
	diradminuser="bindinguser"
	diradminpass="5pr0uts"

	# Check for non-empty router IP. Need network to continue.
	if [ "$myRouter" != "" ] ; then
	
		# Looking for an existing record by macAddress, to remove
		writelog "AddComputerRecord - Looking for Computer Record"
		# Grab the name of the matching record
		myLDAPRecord="$(dscl localhost search /LDAPv3/$myOD/Computers macAddress $thisHWAddress | awk '/dsAttr/ { print $1 }')"
		if [ "$myLDAPRecord" != "" ]; then
			writelog "Found a Computer Record for $thisHWAddress...$myLDAPRecord...removing"
			dscl -u $diradminuser -P $diradminpass /LDAPv3/$myOD/ -delete "/Computers/$myLDAPRecord"
		fi
	
		# Create a computer record using the LocalSubnetName as the record id
		writelog "AddComputerRecord - Creating a Computer Record for $thisLocalSubnetName"
		dscl -u $diradminuser -P $diradminpass /LDAPv3/$myOD -create /Computers/$thisLocalSubnetName macAddress $thisHWAddress
	
		# Add the RealName attribute
		writelog "AddComputerRecord - Appending the RealName attr for $thisLocalSubnetName *$thisComputerName*"
		dscl -u $diradminuser -P $diradminpass /LDAPv3/$myOD/ -append /Computers/$thisLocalSubnetName RealName "$thisComputerName"
	
		# Add this machine to a ComputerList
		writelog "AddComputerRecord - Adding $thisLocalSubnetName to ComputerList $computerList"
		dscl -u $diradminuser -P $diradminpass /LDAPv3/$myOD/ -merge "/ComputerLists/$computerList" apple-computers "$thisLocalSubnetName"
	
		# Add this machine to a ComputerGroup
		writelog "AddComputerRecord - Adding $thisLocalSubnetName to ComputerGroup $computerList"
		thisGUID="$(dscl /LDAPv3/$myOD/ -read /Computers/$thisLocalSubnetName GeneratedUID | awk '{ print $2 }')"
		dscl -u $diradminuser -P $diradminpass /LDAPv3/$myOD/ -merge "/ComputerGroups/$computerList" apple-group-memberguid "$thisGUID"
		dscl -u $diradminuser -P $diradminpass /LDAPv3/$myOD/ -merge "/ComputerGroups/$computerList" memberUid "$thisLocalSubnetName"

	else
		
		writelog "No router found - no computer record created"
		
	fi

	writelog "AddComputerRecord - Ending AddComputerRecord"
	
}


#------------------------------------------------------------------------------
#  Main Script
#------------------------------------------------------------------------------
writelog "$thisScript Starting"
writelog "$thisScript Version $scriptVersion"

checkroot

writelog "$thisScript is Done."
