partial fix for spotloght localizations

partial fix for spotloght localizations

tell application "System Events"
	tell process "SystemUIServer"
		-- find the spotlight menu item. count backwards because it's usually in the second one.
		try
			repeat with menuBarNum from (count of menu bars) to 0 by -1
				repeat with theItem in (menu bar items of (item menuBarNum of menu bars))
					if (description of theItem) contains "spotlight" then
						-- we found it
						if (selected of theItem) is false then
							click theItem
						end if
						keystroke "{popclip text}"
						error
					end if
				end repeat
			end repeat
		on error theError
		end try
	end tell
end tell

tell application "System Events"
	tell process "SystemUIServer"
		-- find the spotlight menu item. count backwards because it's usually in the second one.
		try
			repeat with menuBarNum from (count of menu bars) to 0 by -1
				repeat with theItem in (menu bar items of (item menuBarNum of menu bars))
					if (description of theItem) is "spotlight menu" then
						-- we found it
						if (selected of theItem) is false then
							click theItem
						end if
						keystroke "{popclip text}"
						error
					end if
				end repeat
			end repeat
		on error theError
		end try
	end tell
end tell


Change tabs to open at work

Change tabs to open at work

set myTabs to {"http://app.getsentry.com/", "http://github.com/uberVU/thehole/issues/assigned/palcu?direction=desc&labels=&milestone=&page=1&sort=updated&state=open/", "https://mail.google.com/mail/u/1/?shva=1#inbox", "https://drive.google.com/a/hootsuite.com/#folders/0BwuFsHJDxJWPYmxXQ1VQVlN6T2M"}
tell application "Google Chrome"
	activate
	repeat with i in myTabs
		open location i
	end repeat
end tell

set myTabs to {"http://app.getsentry.com/", "http://app.ubervu.com/", "http://github.com/uberVU/thehole/issues/assigned/palcu?direction=desc&labels=&milestone=&page=1&sort=updated&state=open/", "https://mail.google.com/mail/u/1/?shva=1#inbox", "https://drive.google.com/a/ubervu.com/#folders/0BzycGIkC5P50TXBlcTZoRXZ5VUE"}
tell application "Google Chrome"
	activate
	repeat with i in myTabs
		open location i
	end repeat
end tell


Delete Jarvis-One-Time.applescript

Delete Jarvis-One-Time.applescript

(*Instead of using the spotlight app, this opens a new terminal directly*)

tell application "Terminal"

	(*opens up speech-to-text*)
	delay 0.5
	tell application "System Events" to key code 63
	tell application "System Events" to key code 63
	delay 2

	(*presses "enter" on DictationIM*)
	tell application "System Events" to tell process "DictationIM"
		click button 1
	end tell
	delay 2

	(*presses "enter" in the terminal*)
	tell application "System Events" to key code 36

end tell


Reactivate SWUpdate Server for Yosemite

Reactivate SWUpdate Server for Yosemite

-- This is the master machq script to replace all others!
-- First find out the version of OS X

global osVersion
global externalIP
global SWUpdateServer
global store
global resources_directory

set osVersion to do shell script "/usr/bin/sw_vers -productVersion | /usr/bin/awk -F . '{print $2}'"

try
	set externalIP to do shell script "/usr/bin/curl http://icanhazip.com/"

	set test1 to do shell script "/usr/bin/dig +short 001.machq.com"
	set test2 to do shell script "/usr/bin/dig +short 002.machq.com"
	set test3 to do shell script "/usr/bin/dig +short 003.machq.com"

	if externalIP is test1 then
		set store to "001"
		set SWUpdateServer to "netboot-station.local:8088"
	else if externalIP is test2 then
		set store to "002"
		set SWUpdateServer to "xserve.local:8088"
	else if externalIP is test3 then
		set store to "003"
		set SWUpdateServer to "servercdr.local:8088"
	end if

on error
	--can't determine which store automatically
	set theStoreList to {"St. Louis", "O'Fallon", "Cedar Rapids"}
	set theStore to choose from list theStoreList with title "Help!" with prompt "Where are we?"

	if theStore as string is "St. Louis" then
		set SWUpdateServer to "netboot-station.local:8088"
	else if theStore as string is "O'Fallon" then
		set SWUpdateServer to "xserve.local:8088"
	else if theStore as string is "Cedar Rapids" then
		set SWUpdateServer to "servercdr.local:8088"
	end if

end try

--check for updates to the updater script
try
	tell application "Finder"
		set scripts_directory to (container of (path to me) as text)
		set resources_directory to (container of container of (path to me) as text)
	end tell

	set local_file to the POSIX path of (resources_directory & "updater.version")
	set local_version to do shell script "/bin/cat \"" & local_file & "\""

	set current_version to do shell script "/usr/bin/curl https://raw.githubusercontent.com/nilness/mhqtools/master/updater.version"
	--display dialog "Local version of updater is: " & local_version & ", current version is: " & current_version

	if current_version > local_version then

		--download the new version
		set local_file to the POSIX path of (scripts_directory & "updater.applescript")
		do shell script "/usr/bin/curl https://raw.githubusercontent.com/nilness/mhqtools/master/updater.applescript > \"" & local_file & "\""
		--update the local version string
		set local_file to the POSIX path of (resources_directory & "updater.version")
		do shell script "/usr/bin/curl https://raw.githubusercontent.com/nilness/mhqtools/master/updater.version > \"" & local_file & "\""

	end if
end try

tell application "Finder"
	set resources_directory to (container of container of (path to me) as text)
end tell

--display dialog osVersion buttons {"OK"}

--display dialog SWUpdateServer buttons {"OK"}

set theButtonNames to {"Set Used Prefs (all *'ed items)", "Set SWUpdateServer*", "List SWUpdateServer", "Remove SWUpdateServer", "Set MacHQ homepage*", "Disable Sleep*", "Rename HD by Size*", "Install MHQ Reset Script", "Remove Current User & Reset CPU", "Test for Flashback Trojan", "Test for ShellShock vulnerability", "Rebuild Launch Services DB", "Flush DNS Cache", "Reset Fake preferences", "Update Fake Workflows from Server", "Install SWUpdate StartupItem", "Save System Profiler Report to server"}

repeat
	set theChoice to choose from list theButtonNames
	if theChoice is false then
		exit repeat
	else if theChoice as string is "Set SWUpdateServer*" then
		setSWUpdateServer()
	else if theChoice as string is "List SWUpdateServer" then
		listSWUpdateServer()
	else if theChoice as string is "Remove SWUpdateServer" then
		resetSWUpdateServer()
	else if theChoice as string is "Set MacHQ homepage*" then
		setHomePage()
	else if theChoice as string is "Set Used Prefs (all *'ed items)" then
		setUsedPrefs()
	else if theChoice as string is "Disable Sleep*" then
		disableSleep()
	else if theChoice as string is "Rename HD by Size*" then
		renameHDbySize()
	else if theChoice as string is "Install MHQ Reset Script" then
		installResetScript()
	else if theChoice as string is "Remove MHQ User & Reset CPU" then
		if resetUserCPU() = -128 then
			return
		end if
	else if theChoice as string is "Remove Current User & Reset CPU" then
		if resetThisUserCPU() = -128 then
			return
		end if
	else if theChoice as string is "Test for Flashback Trojan" then
		testForFlashbackTrojan()
	else if theChoice as string is "Rebuild Launch Services DB" then
		rebuildLaunchServicesDB()
	else if theChoice as string is "Reset Fake preferences" then
		reinstallDefaultFakePreferences()
	else if theChoice as string is "Reinstall Fake Workflows" then
		reinstallFakeWorkflows()
	else if theChoice as string is "Install SWUpdate StartupItem" then
		InstallSWUpdatePlist()
	else if theChoice as string is "Flush DNS Cache" then
		FlushDNSCache()
	else if theChoice as string is "Save System Profiler Report to server" then
		SystemProfilerReport()
	else if theChoice as string is "Update Fake Workflows from Server" then
		UpdateWorkflowsFromServer()
	else if theChoice as string is "Test for ShellShock vulnerability" then
		testForShellShockVulnerability()
	else
		tell me to quit
	end if

end repeat

on setUsedPrefs()
	disableSleep()
	setSWUpdateServer()
	setHomePage()
	renameHDbySize()
end setUsedPrefs

on setHomePage()
	set fileTarget to (path to library folder from user domain as text) & "Preferences:com.apple.Safari.plist"

	try
		-- we don't really need the alias; we're just checking to see if it exists
		fileTarget as alias
	on error
		tell application "Safari"
			activate
		end tell
	end try
	if running of application "Safari" then
		tell application "Safari"
			quit
		end tell
		repeat while (running of application "Safari")
			delay 1
		end repeat
		delay 2
	end if
	do shell script "defaults write com.apple.Safari HomePage http://twitter.com/machq; defaults write com.apple.Safari NewWindowBehavior 0"
	delay 2
	tell application "Safari"
		activate
		delay 2
		close every window
		quit
	end tell
end setHomePage

on listSWUpdateServer()
	try
		set server_name to do shell script "defaults read /Library/Preferences/com.apple.SoftwareUpdate CatalogURL"
		display dialog "SW update server is: " & server_name buttons {"OK"}
	on error
		display dialog "Using default Apple SW Update Server" buttons {"OK"}
	end try
end listSWUpdateServer

on resetSWUpdateServer()
	try
		--if running in 10.7 or later we need to supply password

		if (osVersion as number > 6) then
			do shell script "defaults delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL" with administrator privileges
		else
			do shell script "/usr/bin/defaults delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL"
		end if

		--do shell script "defaults delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL"
	end try
end resetSWUpdateServer

on disableSleep()
	try
		do shell script "pmset -c displaysleep 0 sleep 0 disksleep 0" with administrator privileges
	end try
end disableSleep

on renameHDbySize()
	set theSetScript to "

#!/bin/bash

boot_vol=`bless --getBoot`

boot_disk=`diskutil info ${boot_vol} |sed '/^ *Volume Name: */!d;s###'`

disk_size=`system_profiler SPSerialATADataType |sed '/^ *Capacity: */!d;s###' | awk '{print int($1+0.5)  $2\" HD\"}' | head -n 1 `

diskutil rename \"${boot_disk}\" \"${disk_size}\"

# Show icons for hard drives, servers, and removable media on the desktop
#defaults write com.apple.finder ShowExternalHardDrivesOnDesktop -bool true
defaults write com.apple.finder ShowHardDrivesOnDesktop -bool true
#defaults write com.apple.finder ShowMountedServersOnDesktop -bool true
#defaults write com.apple.finder ShowRemovableMediaOnDesktop -bool true

killall Finder

"
	do shell script theSetScript

end renameHDbySize

on setSWUpdateServer()

	set theSetScript to "

#!/bin/bash

URL1='http://" & SWUpdateServer & "'
    case `/usr/bin/sw_vers -productVersion | /usr/bin/awk -F . '{print $2}'` in
      4) URL=\"${URL1}/index.sucatalog\" ;;
      5) URL=\"${URL1}/index-leopard.merged-1.sucatalog\" ;;
      6) URL=\"${URL1}/index-leopard-snowleopard.merged-1.sucatalog\" ;;
	7) URL=\"${URL1}/index-lion-snowleopard-leopard.merged-1.sucatalog\" ;;
	8) URL=\"${URL1}/index-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog\" ;;
	9) URL=\"${URL1}/index-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog\" ;;
	10) URL=\"${URL1}/index-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog\" ;;
      *) echo \"Unsupported client OS\"; exit 1 ;;
    esac

/usr/bin/defaults write /Library/Preferences/com.apple.SoftwareUpdate CatalogURL \"${URL}\"

	"
	--if running in 10.7 or later we need to supply password
	try
		if (osVersion as number > 6) then
			do shell script theSetScript with administrator privileges
		else
			do shell script theSetScript
		end if
	end try
end setSWUpdateServer

on installResetScript()
	try
		tell application "Finder"
			set TheFile to (resources_directory & "mhqreset.sh") as alias
			duplicate TheFile to the startup disk with replacing
		end tell
	on error error_message
		display dialog error_message
	end try
end installResetScript

on resetUserCPU()
	try
		display dialog "This will install the MHQ reset script and restart the computer into single user mode, then run the reset script automatically. Do you wish to continue?" buttons {"Quit", "Continue"} default button "Continue" cancel button "Quit"
		installResetScript()

		if osVersion is "10" then
			set target_file to ".bashrc"
		else
			set target_file to ".profile"
		end if

		do shell script "echo \"sh /mhqreset.sh\" >> /private/var/root/" & target_file with administrator privileges

		do shell script "nvram boot-args=\"-s\"" with administrator privileges

		tell application "Finder" to restart
		return -128
	end try
end resetUserCPU

on resetThisUserCPU()
	try
		tell application "System Events"
			set current_user to get the name of current user
		end tell

		display dialog "This will install the MHQ reset script and restart the computer into single user mode, then run the reset script automatically. The user \"" & current_user & "\" will be deleted with all it's files. Do you wish to continue?" buttons {"Quit", "Continue"} default button "Continue" cancel button "Quit"
		display dialog "Are you absolutely certain?. The user \"" & current_user & "\" will be deleted with all it's files. Do you wish to continue?" buttons {"Quit", "Continue"} default button "Continue" cancel button "Quit"
		installResetScript()

		if osVersion is "10" then
			set target_file to ".bashrc"
		else
			set target_file to ".profile"
		end if

		do shell script "echo \"sh /mhqreset.sh\" " & current_user & " >> /private/var/root/" & target_file with administrator privileges

		do shell script "nvram boot-args=\"-s\"" with administrator privileges

		tell application "Finder" to restart
		return -128
	end try
end resetThisUserCPU

on InstallSWUpdatePlist()

	set TheFile to (resources_directory & "Set SWUpdate Server") as alias

	if (osVersion as number > 7) then

		tell application "Finder"
			duplicate TheFile to (path to startup items from local domain as alias) with replacing
		end tell
	else

		set theScript to "

		#!/bin/bash

		if [ ! -e '/Library/StartupItems/Set SWUpdate Server' ]; then
		    mkdir '/Library/StartupItems/Set SWUpdate Server'
		fi
		cp -R '" & (the POSIX path of TheFile) & "' '/Library/StartupItems/Set SWUpdate Server/.'
		"
		do shell script theScript with administrator privileges

	end if

	do shell script "chmod -R 755 '/Library/StartupItems/Set SWUpdate Server'; sudo chown -R root:wheel '/Library/StartupItems/Set SWUpdate Server'" with administrator privileges

end InstallSWUpdatePlist

on testForFlashbackTrojan()
	display alert ("Beginning test") message "Testing for presence of Flashback trojan. Keep in mind this is NOT a definitive test!"

	try
		set check1 to do shell script "defaults read /Applications/Safari.app/Contents/Info LSEnvironment"
		display alert ("Possible infection!") message "Recommend running full antivirus scan with up to date scanner. Please note this test is a first release and may produce false positives."

	on error error_message number error_number
		if error_number is equal to 1 then
			display alert ("Alert!") message "First check appears okay"
		end if
	end try

	try
		set check2 to do shell script "defaults read ~/.MacOSX/environment DYLD_INSERT_LIBRARIES"
		display alert ("Possible infection!") message "Recommend running full antivirus scan with up to date scanner. Please note this test is a first release and may produce false positives."

	on error error_message number error_number
		if error_number is equal to 1 then
			display alert ("Alert!") message "Second check appears okay"
		end if
	end try
end testForFlashbackTrojan

on rebuildLaunchServicesDB()
	display alert ("Alert!") message "The Finder must be quit and will relaunch when complete."

	try
		tell application "Finder" to quit
		do shell script "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user"
		tell application "Finder" to activate

	end try
end rebuildLaunchServicesDB

on reinstallDefaultFakePreferences()

	--delete the current preference file

	tell application "Finder"
		set oldFile to (path to preferences folder as string) & "com.fakeapp.Fake.plist"
		delete file oldFile
	end tell

	-- create new preference file and set the properties we care about
	set theSetScript to "
#!/bin/bash

touch \"~/Preferences/com.fakeapp.Fake.plist\"
defaults write com.fakeapp.Fake \"FakeDelayBetweenRunningActions\" '0'
defaults write com.fakeapp.Fake \"FakePlaySuccessFailureSounds\" '0'
"
	do shell script theSetScript

end reinstallDefaultFakePreferences

on reinstallFakeWorkflows()
	set oldFolder to (path to application support from user domain as text) & "Fake:Workflows:"
	set fakeFolder to (path to application support from user domain as text) & "Fake:"
	set newFolder to (resources_directory & "Workflows") as alias
	--	display dialog oldFolder buttons {"OK"}
	tell application "Finder"
		try
			delete oldFolder
		end try
		duplicate newFolder to fakeFolder
	end tell
end reinstallFakeWorkflows

on FlushDNSCache()
	set theSetScript to "

#!/bin/bash

case `/usr/bin/sw_vers -productVersion | /usr/bin/awk -F . '{print $2}'` in
    4) lookupd -flushcache ;;
   [56]) dscacheutil -flushcache ;;
    [78]) sudo killall -HUP mDNSResponder ;;
    9) dscacheutil -flushcache; sudo killall -HUP mDNSResponder ;;
  10) dscacheutil -flushcache; sudo discoveryutil mdnsflushcache ;;
      *) echo \"Unsupported client OS\"; exit 1 ;;
esac

	"
	--if running in 10.7 or 10.8 we need to supply password

	if (osVersion as number > 7) then
		do shell script theSetScript with administrator privileges
	else
		do shell script theSetScript
	end if
end FlushDNSCache

on SystemProfilerReport()

	if (store = "001") then
		set destination to "/Volumes/MHQ/Backed Up/System Profiler Reports/"
		set dest_volume to "afp://mhq-swupdate.local/MHQ"
	else if (store = "002") then
		set destination to "/Volumes/Service/System Profiler Reports/"
		set dest_volume to "afp://xserve.local/Service"
	else if (store = "003") then
		set destination to "/Volumes/Service/System Profiler Reports/"
		set dest_volume to "afp://servercdr.local/Service"
	end if

	--	display dialog oldFolder

	tell application "Finder"
		try
			mount volume dest_volume
		on error
			return "Error mounting server volume \"" & dest_volume & "\". Please connect to server manually and try again."
			tell me to quit
		end try
	end tell

	--this shell script will generate a system profiler report and save it to the server
	do shell script "#!/bin/sh

# the location includes a folder based on the date in yyyy-mm-dd format
report_location=\"" & destination & "`date \"+%Y-%m-%d\"`/\"

if [ ! -d \"${report_location}\" ]; then
	mkdir \"${report_location}\"
fi

serial=`system_profiler SPHardwareDataType | grep \"Serial Number\" | awk  '{print $4}'`

SPDataTypes=\"SPHardwareDataType SPMemoryDataType SPPowerDataType SPSerialATADataType SPSoftwareDataType SPThunderboltDataType SPUSBDataType SPAirPortDataType SPFireWireDataType SPParallelATADataType SPAudioDataType SPBluetoothDataType SPNetworkDataType\"

system_profiler -xml $SPDataTypes > $report_location$serial\".spx\"
"

end SystemProfilerReport

on UpdateWorkflowsFromServer()

	set destination to POSIX path of ((path to application support from user domain as text) & "Fake:Workflows:")

	if (store = "001") then
		set source to "/Volumes/MHQ/Backed Up/Retail Stuff/Current Workflows/"
		set dest_volume to "afp://mhq-swupdate.local/MHQ"
	else if (store = "002") then
		set source to "/Volumes/Retail/Current Workflows/"
		set dest_volume to "afp://xserve.local/Retail"
	else if (store = "003") then
		set source to "/Volumes/Retail/Current Workflows/"
		set dest_volume to "afp://servercdr.local/Retail"
	end if

	--	display dialog oldFolder buttons {"OK"}

	tell application "Finder"
		try
			mount volume dest_volume
		on error
			return "Error mounting server volume \"" & dest_volume & "\". Please connect to server manually and try again."
			tell me to quit
		end try
	end tell

	try
		set theScript to "
	#!/bin/bash

	/usr/bin/rsync -a '" & source & "' '" & destination & "'
	" --shell script

		do shell script theScript --with administrator privileges
	on error
		return "Error syncronizing folders."
	end try

end UpdateWorkflowsFromServer

on testForShellShockVulnerability()

	set test_1 to "
#!/bin/bash

EXPLOIT_1=`env x='() { :;}; echo vulnerable' bash -c \"echo this is a test\"`
if [ \"${EXPLOIT_1}\" = \"vulnerable\" ]; then
    echo \"Test 1 (CVE-2014-6271):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 1 (CVE-2014-6271):	Machine doesn't appear to be vulnerable\"
fi
"
	set test_2 to "
#!/bin/bash

EXPLOIT_2=`env X='() { (shellshocker.net)=>\\' bash -c \"echo date\"; cat echo; rm ./echo `
if [ \"${EXPLOIT_2}\" != \"date\" ]; then
    echo \"Test 2 (CVE-2014-7169):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 2 (CVE-2014-7169):	Machine doesn't appear to be vulnerable\"
fi
"
	set test_3 to "
#!/bin/bash

EXPLOIT_3=`env X=' () { }; echo hello' bash -c 'date'`
if [ \"${EXPLOIT_3}\" = \"hello\" ]; then
    echo \"Test 3 (CVE-??):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 3 (CVE-??):	Machine doesn't appear to be vulnerable\"
fi

"

	set test_4 to "
#!/bin/bash

EXPLOIT_4=`bash -c 'true <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF' || echo \"CVE-2014-7186 vulnerable, redir_stack\"`
if [ \"${EXPLOIT_4}\" = \"CVE-2014-7186 vulnerable, redir_stack\" ]; then
    echo \"Test 4 (CVE-2014-7186):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 4 (CVE-2014-7186):	Machine doesn't appear to be vulnerable\"
fi

"

	set test_5 to "
#!/bin/bash

EXPLOIT_5=`(for x in {1..200} ; do echo \"for x$x in ; do :\"; done; for x in {1..200} ; do echo done ; done) | bash || echo \"CVE-2014-7187 vulnerable, word_lineno\"`
if [ \"${EXPLOIT_5}\" = \"CVE-2014-7187 vulnerable, word_lineno\" ]; then
    echo \"Test 5 (CVE-2014-7187):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 5 (CVE-2014-7187):	Machine doesn't appear to be vulnerable\"
fi

"
	set test_6 to "
#!/bin/bash

EXPLOIT_6=`shellshocker='() { echo You are vulnerable; }' bash -c shellshocker`
if [ \"${EXPLOIT_6}\" = \"You are vulnerable\" ]; then
    echo \"Test 6 (CVE-2014-6278):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 6 (CVE-2014-6278):	Machine doesn't appear to be vulnerable\"
fi

"
	set test_7 to "
#!/bin/bash

EXPLOIT_7=`bash -c \"f() { x() { _;}; x() { _;} <<a; }\" 2>/dev/null || echo vulnerable`
if [ \"${EXPLOIT_7}\" = \"vulnerable\" ]; then
    echo \"Test 7 (CVE-2014-6277):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 7 (CVE-2014-6277):	Machine doesn't appear to be vulnerable\"
fi

"

	set result_1 to do shell script test_1
	set result_2 to do shell script test_2
	set result_3 to do shell script test_3
	set result_4 to do shell script test_4
	set result_5 to do shell script test_5
	set result_6 to do shell script test_6
	set result_7 to do shell script test_7

	try
		display dialog result_1 & return & result_2 & return & result_3 & return & result_4 & return & result_6 & return & result_6 & return & result_7 & return buttons {"OK"}
	end try
end testForShellShockVulnerability

-- This is the master machq script to replace all others!
-- First find out the version of OS X

global osVersion
global externalIP
global SWUpdateServer
global store
global resources_directory

set osVersion to do shell script "/usr/bin/sw_vers -productVersion | /usr/bin/awk -F . '{print $2}'"

try
	set externalIP to do shell script "/usr/bin/curl http://icanhazip.com/"

	set test1 to do shell script "/usr/bin/dig +short 001.machq.com"
	set test2 to do shell script "/usr/bin/dig +short 002.machq.com"
	set test3 to do shell script "/usr/bin/dig +short 003.machq.com"

	if externalIP is test1 then
		set store to "001"
		set SWUpdateServer to "netboot-station.local:8088"
	else if externalIP is test2 then
		set store to "002"
		set SWUpdateServer to "xserve.local:8088"
	else if externalIP is test3 then
		set store to "003"
		set SWUpdateServer to "servercdr.local:8088"
	end if

on error
	--can't determine which store automatically
	set theStoreList to {"St. Louis", "O'Fallon", "Cedar Rapids"}
	set theStore to choose from list theStoreList with title "Help!" with prompt "Where are we?"

	if theStore as string is "St. Louis" then
		set SWUpdateServer to "netboot-station.local:8088"
	else if theStore as string is "O'Fallon" then
		set SWUpdateServer to "xserve.local:8088"
	else if theStore as string is "Cedar Rapids" then
		set SWUpdateServer to "servercdr.local:8088"
	end if

end try

--check for updates to the updater script
try
	tell application "Finder"
		set scripts_directory to (container of (path to me) as text)
		set resources_directory to (container of container of (path to me) as text)
	end tell

	set local_file to the POSIX path of (resources_directory & "updater.version")
	set local_version to do shell script "/bin/cat \"" & local_file & "\""

	set current_version to do shell script "/usr/bin/curl https://raw.githubusercontent.com/nilness/mhqtools/master/updater.version"
	--display dialog "Local version of updater is: " & local_version & ", current version is: " & current_version

	if current_version > local_version then

		--download the new version
		set local_file to the POSIX path of (scripts_directory & "updater.applescript")
		do shell script "/usr/bin/curl https://raw.githubusercontent.com/nilness/mhqtools/master/updater.applescript > \"" & local_file & "\""
		--update the local version string
		set local_file to the POSIX path of (resources_directory & "updater.version")
		do shell script "/usr/bin/curl https://raw.githubusercontent.com/nilness/mhqtools/master/updater.version > \"" & local_file & "\""

	end if
end try

tell application "Finder"
	set resources_directory to (container of container of (path to me) as text)
end tell

--display dialog osVersion buttons {"OK"}

--display dialog SWUpdateServer buttons {"OK"}

set theButtonNames to {"Set Used Prefs (all *'ed items)", "Set SWUpdateServer*", "List SWUpdateServer", "Remove SWUpdateServer", "Set MacHQ homepage*", "Disable Sleep*", "Rename HD by Size*", "Install MHQ Reset Script", "Remove Current User & Reset CPU", "Test for Flashback Trojan", "Test for ShellShock vulnerability", "Rebuild Launch Services DB", "Flush DNS Cache", "Reset Fake preferences", "Update Fake Workflows from Server", "Install SWUpdate StartupItem", "Save System Profiler Report to server"}

repeat
	set theChoice to choose from list theButtonNames
	if theChoice is false then
		exit repeat
	else if theChoice as string is "Set SWUpdateServer*" then
		setSWUpdateServer()
	else if theChoice as string is "List SWUpdateServer" then
		listSWUpdateServer()
	else if theChoice as string is "Remove SWUpdateServer" then
		resetSWUpdateServer()
	else if theChoice as string is "Set MacHQ homepage*" then
		setHomePage()
	else if theChoice as string is "Set Used Prefs (all *'ed items)" then
		setUsedPrefs()
	else if theChoice as string is "Disable Sleep*" then
		disableSleep()
	else if theChoice as string is "Rename HD by Size*" then
		renameHDbySize()
	else if theChoice as string is "Install MHQ Reset Script" then
		installResetScript()
	else if theChoice as string is "Remove MHQ User & Reset CPU" then
		if resetUserCPU() = -128 then
			return
		end if
	else if theChoice as string is "Remove Current User & Reset CPU" then
		if resetThisUserCPU() = -128 then
			return
		end if
	else if theChoice as string is "Test for Flashback Trojan" then
		testForFlashbackTrojan()
	else if theChoice as string is "Rebuild Launch Services DB" then
		rebuildLaunchServicesDB()
	else if theChoice as string is "Reset Fake preferences" then
		reinstallDefaultFakePreferences()
	else if theChoice as string is "Reinstall Fake Workflows" then
		reinstallFakeWorkflows()
	else if theChoice as string is "Install SWUpdate StartupItem" then
		InstallSWUpdatePlist()
	else if theChoice as string is "Flush DNS Cache" then
		FlushDNSCache()
	else if theChoice as string is "Save System Profiler Report to server" then
		SystemProfilerReport()
	else if theChoice as string is "Update Fake Workflows from Server" then
		UpdateWorkflowsFromServer()
	else if theChoice as string is "Test for ShellShock vulnerability" then
		testForShellShockVulnerability()
	else
		tell me to quit
	end if

end repeat

on setUsedPrefs()
	disableSleep()
	setSWUpdateServer()
	setHomePage()
	renameHDbySize()
end setUsedPrefs

on setHomePage()
	set fileTarget to (path to library folder from user domain as text) & "Preferences:com.apple.Safari.plist"

	try
		-- we don't really need the alias; we're just checking to see if it exists
		fileTarget as alias
	on error
		tell application "Safari"
			activate
		end tell
	end try
	if running of application "Safari" then
		tell application "Safari"
			quit
		end tell
		repeat while (running of application "Safari")
			delay 1
		end repeat
		delay 2
	end if
	do shell script "defaults write com.apple.Safari HomePage http://twitter.com/machq; defaults write com.apple.Safari NewWindowBehavior 0"
	delay 2
	tell application "Safari"
		activate
		delay 2
		close every window
		quit
	end tell
end setHomePage

on listSWUpdateServer()
	try
		set server_name to do shell script "defaults read /Library/Preferences/com.apple.SoftwareUpdate CatalogURL"
		display dialog "SW update server is: " & server_name buttons {"OK"}
	on error
		display dialog "Using default Apple SW Update Server" buttons {"OK"}
	end try
end listSWUpdateServer

on resetSWUpdateServer()
	try
		--if running in 10.7 or later we need to supply password

		if (osVersion as number > 6) then
			do shell script "defaults delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL" with administrator privileges
		else
			do shell script "/usr/bin/defaults delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL"
		end if

		--do shell script "defaults delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL"
	end try
end resetSWUpdateServer

on disableSleep()
	try
		do shell script "pmset -c displaysleep 0 sleep 0 disksleep 0" with administrator privileges
	end try
end disableSleep

on renameHDbySize()
	set theSetScript to "

#!/bin/bash

boot_vol=`bless --getBoot`

boot_disk=`diskutil info ${boot_vol} |sed '/^ *Volume Name: */!d;s###'`

disk_size=`system_profiler SPSerialATADataType |sed '/^ *Capacity: */!d;s###' | awk '{print int($1+0.5)  $2\" HD\"}' | head -n 1 `

diskutil rename \"${boot_disk}\" \"${disk_size}\"

# Show icons for hard drives, servers, and removable media on the desktop
#defaults write com.apple.finder ShowExternalHardDrivesOnDesktop -bool true
defaults write com.apple.finder ShowHardDrivesOnDesktop -bool true
#defaults write com.apple.finder ShowMountedServersOnDesktop -bool true
#defaults write com.apple.finder ShowRemovableMediaOnDesktop -bool true

killall Finder

"
	do shell script theSetScript

end renameHDbySize

on setSWUpdateServer()

	set theSetScript to "

#!/bin/bash

URL1='http://" & SWUpdateServer & "'
    case `/usr/bin/sw_vers -productVersion | /usr/bin/awk -F . '{print $2}'` in
      4) URL=\"${URL1}/index.sucatalog\" ;;
      5) URL=\"${URL1}/index-leopard.merged-1.sucatalog\" ;;
      6) URL=\"${URL1}/index-leopard-snowleopard.merged-1.sucatalog\" ;;
	7) URL=\"${URL1}/index-lion-snowleopard-leopard.merged-1.sucatalog\" ;;
	8) URL=\"${URL1}/index-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog\" ;;
	9) URL=\"${URL1}/index-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog\" ;;
	10) exit; URL=\"${URL1}/index-10.10-10.9-mountainlion-lion-snowleopard-leopard.merged-1.sucatalog\" ;;
      *) echo \"Unsupported client OS\"; exit 1 ;;
    esac

/usr/bin/defaults write /Library/Preferences/com.apple.SoftwareUpdate CatalogURL \"${URL}\"

	"
	--if running in 10.7 or later we need to supply password
	try
		if (osVersion as number > 6) then
			do shell script theSetScript with administrator privileges
		else
			do shell script theSetScript
		end if
	end try
end setSWUpdateServer

on installResetScript()
	try
		tell application "Finder"
			set TheFile to (resources_directory & "mhqreset.sh") as alias
			duplicate TheFile to the startup disk with replacing
		end tell
	on error error_message
		display dialog error_message
	end try
end installResetScript

on resetUserCPU()
	try
		display dialog "This will install the MHQ reset script and restart the computer into single user mode, then run the reset script automatically. Do you wish to continue?" buttons {"Quit", "Continue"} default button "Continue" cancel button "Quit"
		installResetScript()

		if osVersion is "10" then
			set target_file to ".bashrc"
		else
			set target_file to ".profile"
		end if

		do shell script "echo \"sh /mhqreset.sh\" >> /private/var/root/" & target_file with administrator privileges

		do shell script "nvram boot-args=\"-s\"" with administrator privileges

		tell application "Finder" to restart
		return -128
	end try
end resetUserCPU

on resetThisUserCPU()
	try
		tell application "System Events"
			set current_user to get the name of current user
		end tell

		display dialog "This will install the MHQ reset script and restart the computer into single user mode, then run the reset script automatically. The user \"" & current_user & "\" will be deleted with all it's files. Do you wish to continue?" buttons {"Quit", "Continue"} default button "Continue" cancel button "Quit"
		display dialog "Are you absolutely certain?. The user \"" & current_user & "\" will be deleted with all it's files. Do you wish to continue?" buttons {"Quit", "Continue"} default button "Continue" cancel button "Quit"
		installResetScript()

		if osVersion is "10" then
			set target_file to ".bashrc"
		else
			set target_file to ".profile"
		end if

		do shell script "echo \"sh /mhqreset.sh\" " & current_user & " >> /private/var/root/" & target_file with administrator privileges

		do shell script "nvram boot-args=\"-s\"" with administrator privileges

		tell application "Finder" to restart
		return -128
	end try
end resetThisUserCPU

on InstallSWUpdatePlist()

	set TheFile to (resources_directory & "Set SWUpdate Server") as alias

	if (osVersion as number > 7) then

		tell application "Finder"
			duplicate TheFile to (path to startup items from local domain as alias) with replacing
		end tell
	else

		set theScript to "

		#!/bin/bash

		if [ ! -e '/Library/StartupItems/Set SWUpdate Server' ]; then
		    mkdir '/Library/StartupItems/Set SWUpdate Server'
		fi
		cp -R '" & (the POSIX path of TheFile) & "' '/Library/StartupItems/Set SWUpdate Server/.'
		"
		do shell script theScript with administrator privileges

	end if

	do shell script "chmod -R 755 '/Library/StartupItems/Set SWUpdate Server'; sudo chown -R root:wheel '/Library/StartupItems/Set SWUpdate Server'" with administrator privileges

end InstallSWUpdatePlist

on testForFlashbackTrojan()
	display alert ("Beginning test") message "Testing for presence of Flashback trojan. Keep in mind this is NOT a definitive test!"

	try
		set check1 to do shell script "defaults read /Applications/Safari.app/Contents/Info LSEnvironment"
		display alert ("Possible infection!") message "Recommend running full antivirus scan with up to date scanner. Please note this test is a first release and may produce false positives."

	on error error_message number error_number
		if error_number is equal to 1 then
			display alert ("Alert!") message "First check appears okay"
		end if
	end try

	try
		set check2 to do shell script "defaults read ~/.MacOSX/environment DYLD_INSERT_LIBRARIES"
		display alert ("Possible infection!") message "Recommend running full antivirus scan with up to date scanner. Please note this test is a first release and may produce false positives."

	on error error_message number error_number
		if error_number is equal to 1 then
			display alert ("Alert!") message "Second check appears okay"
		end if
	end try
end testForFlashbackTrojan

on rebuildLaunchServicesDB()
	display alert ("Alert!") message "The Finder must be quit and will relaunch when complete."

	try
		tell application "Finder" to quit
		do shell script "/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user"
		tell application "Finder" to activate

	end try
end rebuildLaunchServicesDB

on reinstallDefaultFakePreferences()

	--delete the current preference file

	tell application "Finder"
		set oldFile to (path to preferences folder as string) & "com.fakeapp.Fake.plist"
		delete file oldFile
	end tell

	-- create new preference file and set the properties we care about
	set theSetScript to "
#!/bin/bash

touch \"~/Preferences/com.fakeapp.Fake.plist\"
defaults write com.fakeapp.Fake \"FakeDelayBetweenRunningActions\" '0'
defaults write com.fakeapp.Fake \"FakePlaySuccessFailureSounds\" '0'
"
	do shell script theSetScript

end reinstallDefaultFakePreferences

on reinstallFakeWorkflows()
	set oldFolder to (path to application support from user domain as text) & "Fake:Workflows:"
	set fakeFolder to (path to application support from user domain as text) & "Fake:"
	set newFolder to (resources_directory & "Workflows") as alias
	--	display dialog oldFolder buttons {"OK"}
	tell application "Finder"
		try
			delete oldFolder
		end try
		duplicate newFolder to fakeFolder
	end tell
end reinstallFakeWorkflows

on FlushDNSCache()
	set theSetScript to "

#!/bin/bash

case `/usr/bin/sw_vers -productVersion | /usr/bin/awk -F . '{print $2}'` in
    4) lookupd -flushcache ;;
   [56]) dscacheutil -flushcache ;;
    [78]) sudo killall -HUP mDNSResponder ;;
    9) dscacheutil -flushcache; sudo killall -HUP mDNSResponder ;;
  10) dscacheutil -flushcache; sudo discoveryutil mdnsflushcache ;;
      *) echo \"Unsupported client OS\"; exit 1 ;;
esac

	"
	--if running in 10.7 or 10.8 we need to supply password

	if (osVersion as number > 7) then
		do shell script theSetScript with administrator privileges
	else
		do shell script theSetScript
	end if
end FlushDNSCache

on SystemProfilerReport()

	if (store = "001") then
		set destination to "/Volumes/MHQ/Backed Up/System Profiler Reports/"
		set dest_volume to "afp://mhq-swupdate.local/MHQ"
	else if (store = "002") then
		set destination to "/Volumes/Service/System Profiler Reports/"
		set dest_volume to "afp://xserve.local/Service"
	else if (store = "003") then
		set destination to "/Volumes/Service/System Profiler Reports/"
		set dest_volume to "afp://servercdr.local/Service"
	end if

	--	display dialog oldFolder

	tell application "Finder"
		try
			mount volume dest_volume
		on error
			return "Error mounting server volume \"" & dest_volume & "\". Please connect to server manually and try again."
			tell me to quit
		end try
	end tell

	--this shell script will generate a system profiler report and save it to the server
	do shell script "#!/bin/sh

# the location includes a folder based on the date in yyyy-mm-dd format
report_location=\"" & destination & "`date \"+%Y-%m-%d\"`/\"

if [ ! -d \"${report_location}\" ]; then
	mkdir \"${report_location}\"
fi

serial=`system_profiler SPHardwareDataType | grep \"Serial Number\" | awk  '{print $4}'`

SPDataTypes=\"SPHardwareDataType SPMemoryDataType SPPowerDataType SPSerialATADataType SPSoftwareDataType SPThunderboltDataType SPUSBDataType SPAirPortDataType SPFireWireDataType SPParallelATADataType SPAudioDataType SPBluetoothDataType SPNetworkDataType\"

system_profiler -xml $SPDataTypes > $report_location$serial\".spx\"
"

end SystemProfilerReport

on UpdateWorkflowsFromServer()

	set destination to POSIX path of ((path to application support from user domain as text) & "Fake:Workflows:")

	if (store = "001") then
		set source to "/Volumes/MHQ/Backed Up/Retail Stuff/Current Workflows/"
		set dest_volume to "afp://mhq-swupdate.local/MHQ"
	else if (store = "002") then
		set source to "/Volumes/Retail/Current Workflows/"
		set dest_volume to "afp://xserve.local/Retail"
	else if (store = "003") then
		set source to "/Volumes/Retail/Current Workflows/"
		set dest_volume to "afp://servercdr.local/Retail"
	end if

	--	display dialog oldFolder buttons {"OK"}

	tell application "Finder"
		try
			mount volume dest_volume
		on error
			return "Error mounting server volume \"" & dest_volume & "\". Please connect to server manually and try again."
			tell me to quit
		end try
	end tell

	try
		set theScript to "
	#!/bin/bash

	/usr/bin/rsync -a '" & source & "' '" & destination & "'
	" --shell script

		do shell script theScript --with administrator privileges
	on error
		return "Error syncronizing folders."
	end try

end UpdateWorkflowsFromServer

on testForShellShockVulnerability()

	set test_1 to "
#!/bin/bash

EXPLOIT_1=`env x='() { :;}; echo vulnerable' bash -c \"echo this is a test\"`
if [ \"${EXPLOIT_1}\" = \"vulnerable\" ]; then
    echo \"Test 1 (CVE-2014-6271):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 1 (CVE-2014-6271):	Machine doesn't appear to be vulnerable\"
fi
"
	set test_2 to "
#!/bin/bash

EXPLOIT_2=`env X='() { (shellshocker.net)=>\\' bash -c \"echo date\"; cat echo; rm ./echo `
if [ \"${EXPLOIT_2}\" != \"date\" ]; then
    echo \"Test 2 (CVE-2014-7169):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 2 (CVE-2014-7169):	Machine doesn't appear to be vulnerable\"
fi
"
	set test_3 to "
#!/bin/bash

EXPLOIT_3=`env X=' () { }; echo hello' bash -c 'date'`
if [ \"${EXPLOIT_3}\" = \"hello\" ]; then
    echo \"Test 3 (CVE-??):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 3 (CVE-??):	Machine doesn't appear to be vulnerable\"
fi

"

	set test_4 to "
#!/bin/bash

EXPLOIT_4=`bash -c 'true <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF <<EOF' || echo \"CVE-2014-7186 vulnerable, redir_stack\"`
if [ \"${EXPLOIT_4}\" = \"CVE-2014-7186 vulnerable, redir_stack\" ]; then
    echo \"Test 4 (CVE-2014-7186):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 4 (CVE-2014-7186):	Machine doesn't appear to be vulnerable\"
fi

"

	set test_5 to "
#!/bin/bash

EXPLOIT_5=`(for x in {1..200} ; do echo \"for x$x in ; do :\"; done; for x in {1..200} ; do echo done ; done) | bash || echo \"CVE-2014-7187 vulnerable, word_lineno\"`
if [ \"${EXPLOIT_5}\" = \"CVE-2014-7187 vulnerable, word_lineno\" ]; then
    echo \"Test 5 (CVE-2014-7187):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 5 (CVE-2014-7187):	Machine doesn't appear to be vulnerable\"
fi

"
	set test_6 to "
#!/bin/bash

EXPLOIT_6=`shellshocker='() { echo You are vulnerable; }' bash -c shellshocker`
if [ \"${EXPLOIT_6}\" = \"You are vulnerable\" ]; then
    echo \"Test 6 (CVE-2014-6278):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 6 (CVE-2014-6278):	Machine doesn't appear to be vulnerable\"
fi

"
	set test_7 to "
#!/bin/bash

EXPLOIT_7=`bash -c \"f() { x() { _;}; x() { _;} <<a; }\" 2>/dev/null || echo vulnerable`
if [ \"${EXPLOIT_7}\" = \"vulnerable\" ]; then
    echo \"Test 7 (CVE-2014-6277):	**** Machine appears to be vulnerable ****\"
else
    echo \"Test 7 (CVE-2014-6277):	Machine doesn't appear to be vulnerable\"
fi

"

	set result_1 to do shell script test_1
	set result_2 to do shell script test_2
	set result_3 to do shell script test_3
	set result_4 to do shell script test_4
	set result_5 to do shell script test_5
	set result_6 to do shell script test_6
	set result_7 to do shell script test_7

	try
		display dialog result_1 & return & result_2 & return & result_3 & return & result_4 & return & result_6 & return & result_6 & return & result_7 & return buttons {"OK"}
	end try
end testForShellShockVulnerability


Delete iterm_bookmark.scpt; no longer used.

FasdUAS 1.101.10
k
i
I
.aevtoappnull****
	o0argv
O4

k3

I
.miscactvnullnull
O
3
k2
I
.ITRMLNCHnullobj

Pssn
l
n
4

cobj
m
o0argv
r"
l
4

Pssn
 m
o
0	mysession!
!O#2"#
"I'1$
.ITRMWrtenullobj $%

iTxt
%l)-&
&n)-'(
'4*-)

cobj
)m+,
(o)*0argv
#o#$
0	mysession
l
*
*4
+

Ptrm
+m

m,,ITRMalisHMacintosh HDīH+ݕ	shell.app:Y	 ApplicationsĬb\:Xݕ#Macintosh HD:Applications:shell.app	shell.appMacintosh HDApplications/shell.app/-
-l./0.
.aevtoappnull****
0	mysession/12
.aevtoappnull****0argv10argv2	,
.miscactvnullnull

Ptrm

Pssn

cobj
.ITRMLNCHnullobj
0	mysession

iTxt
.ITRMWrtenullobj 51*jO*k/#*k/lO*i/EO*l/lUUU03344,

Ptrm

Pssnascr
ޭ


Remove debug code.

Remove debug code.

tell application "iTunes"
  set specified_tracks to (every track whose #{conditions})

	set json to "["

	repeat with specified_track in specified_tracks
    set props to {}

    set end of props to "{"
    set end of props to ("\"persistent_id\":\"" & persistent ID of specified_track & "\",")
    set end of props to ("\"name\":\"" & my escape_quote(name of specified_track) & "\",")
    set end of props to ("\"album\":\"" & my escape_quote(album of specified_track) & "\",")
    set end of props to ("\"artist\":\"" & my escape_quote(artist of specified_track) & "\",")
    set end of props to ("\"track_count\":\"" & track count of specified_track & "\",")
    set end of props to ("\"track_number\":\"" & track number of specified_track & "\"")
    set end of props to "}"

    set json to json & props as string & ","
  end repeat

  set json to json & "null]"
  return json

end tell

on escape_quote(someText)
 return replaceText(someText, "\"", "\\\"")
end escape_quote

(*
   https://discussions.apple.com/thread/4588230?start=0&tstart=0
*)
on replaceText(someText, oldItem, newItem)
     set {tempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, oldItem}
     try
          set {itemList, AppleScript's text item delimiters} to {text items of someText, newItem}
          set {someText, AppleScript's text item delimiters} to {itemList as text, tempTID}
     on error errorMessage number errorNumber -- oops
          set AppleScript's text item delimiters to tempTID
          error errorMessage number errorNumber -- pass it on
     end try

     return someText
end replaceText

tell application "iTunes"
  set specified_tracks to (every track whose #{conditions})

	set json to "["

	repeat with specified_track in specified_tracks
    set props to {}

    set prop_name to name of specified_track

    set end of props to "{"
    set end of props to ("\"persistent_id\":\"" & persistent ID of specified_track & "\",")
    set end of props to ("\"name\":\"" & my escape_quote(name of specified_track) & "\",")
    set end of props to ("\"album\":\"" & my escape_quote(album of specified_track) & "\",")
    set end of props to ("\"artist\":\"" & my escape_quote(artist of specified_track) & "\",")
    set end of props to ("\"track_count\":\"" & track count of specified_track & "\",")
    set end of props to ("\"track_number\":\"" & track number of specified_track & "\"")
    set end of props to "}"

    set json to json & props as string & ","
  end repeat

  set json to json & "null]"
  return json

end tell

on escape_quote(someText)
 return replaceText(someText, "\"", "\\\"")
end escape_quote

(*
   https://discussions.apple.com/thread/4588230?start=0&tstart=0
*)
on replaceText(someText, oldItem, newItem)
     set {tempTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, oldItem}
     try
          set {itemList, AppleScript's text item delimiters} to {text items of someText, newItem}
          set {someText, AppleScript's text item delimiters} to {itemList as text, tempTID}
     on error errorMessage number errorNumber -- oops
          set AppleScript's text item delimiters to tempTID
          error errorMessage number errorNumber -- pass it on
     end try

     return someText
end replaceText


Scripts update

Scripts update

FasdUAS 1.101.10
k
i
I	0resize_app_window

o0app_name

o0win_position

o0win_size
Z=
=
n
1

prun
4

capp
o0app_name
m
boovtrue
O9
O8
k7
r&
J  !
 n"#
"4$

cobj
$m
#o0win_position!%
%n&'
&4(

cobj
(m
'o0win_position
n)*
)1#%

posn
*l #+
+2 #

cwin,
,r'7-.
-J'1//01
0n'+23
24(+4

cobj
4m)*
3o'(0win_size15
5n+/67
64,/8

cobj
8m-.
7o+,0win_size
.n9:
9146

ptsz
:l14;
;214

cwin
4<

prcs
<o0app_name
m==sevsalis\Macintosh HDBDSystem Events.app
 cuCoreServices0/:System:Library:CoreServices:System Events.app/$System Events.appMacintosh HD-System/Library/CoreServices/System Events.app/>?
>l?@A
@lB
BrCD
CJEEFG
FmGH
Hm(
Do0narrow_center_positionAIJ
Il
K
Kr
LM
LJNNOP
Om"PQ
Qm	m
Mo0narrow_center_sizeJRS
RlSTU
TlV
VrWX
WJYYZ[
Zm[\
\m(
Xo0wide_center_positionU]^
]l_
_r`a
`Jbbcd
cmde
emm
ao0wide_center_size^fg
flghi
hl$j
jI$k0resize_app_windowklm
lmnnoo1Passwordmpq
po0narrow_center_positionqr
ro 0narrow_center_sizeist
sl%-u
uI%-v0resize_app_windowvwx
wm&'yyzzApp Storex{|
{o'(0narrow_center_position|}
}o()0narrow_center_sizet~
~l.6
I.60resize_app_window
m/0
Books
o010narrow_center_position
o120narrow_center_size
l7?
I7?0resize_app_window
m89Calendar
o9:0narrow_center_position
o:;0narrow_center_size
l@M
I@M0resize_app_window
mABCARROTweather
oBC0narrow_center_position
JCI
mCD"
mDG
lN]
IN]0resize_app_window
mORDiscord
oRS0narrow_center_position
JSY
mST"
mTW
l^h
I^h0resize_app_window
m_bFantastical
obc0narrow_center_position
ocd0narrow_center_size
lis
Iis0resize_app_window
mjmGoogle Chrome
omn0narrow_center_position~
ono}}0narrow_center_size~
lt~|{
It~zyz0resize_app_window
muxMail
oxyxx0narrow_center_positionw
oyzvv0narrow_center_sizewy|{
lut
Isrs0resize_app_window
mMessages
J
mqqp
moo(pn
J
mmml
mkklnrut
lji
Ihgh0resize_app_window
m
Music
off0narrow_center_positione
odd0narrow_center_sizeegji
lcb
Ia`a0resize_app_window
mNews
o__0narrow_center_position^
o]]0narrow_center_size^`cb
l\[
IZYZ0resize_app_window
m
Notes
oXX0narrow_center_positionW
J
mVV"
U

mTTUWY\[
l
SR

IQPQ0resize_app_window
mPhotos
oOO0narrow_center_positionN
oMM0narrow_center_sizeNPSR
lLK
IJIJ0resize_app_window
mPhotoshop
oHH0narrow_center_position G
 oFF0narrow_center_sizeGILK!"
!l#ED
#IC$BC0resize_app_window$%&
%m''((Preview&)*
)oAA0narrow_center_position*+@
+o??0narrow_center_size@BED",-
,l.>=
.I</;<0resize_app_window/01
0m2233RadarScope145
4o::0narrow_center_position569
6o880narrow_center_size9;>=-78
7l976
9I5:450resize_app_window:;<
;m==>>Reflect<?@
?o330narrow_center_position@A2
Ao110narrow_center_size24768BC
BlD0/
DI.E-.0resize_app_windowEFG
FmHHIIRoonGJK
Jo,,0narrow_center_positionKL+
Lo**0narrow_center_size+-0/CMN
MlO)(
OI'P&'0resize_app_windowPQR
QmSSTTSafariRUV
Uo%%0narrow_center_positionVW$
Wo##0narrow_center_size$&)(NXY
Xl	Z"!
ZI	 [ 0resize_app_window[\]
\m

^^__Siftie]`a
`o
0narrow_center_positionab
bo0narrow_center_size"!Ycd
cl#e
eI#f0resize_app_windowfgh
gmiijj
Slackhkl
ko0narrow_center_positionlm
mJnnop
om"pq
qmdrs
rl$<t
tI$<u0resize_app_windowuvw
vm%(xxyyTextEditwz{
zJ(0||}~
}m(+~

m+.]
{
J08
m03

R
m364	s
l=L
I=L0resize_app_window
m>AThings
oAB0narrow_center_position
JBH
mBC"
mCF
lMW
IMW0resize_app_window
mNQ
TIDAL
oQR0narrow_center_position
oRS0narrow_center_size
lXn
IXn0resize_app_window
mY\Tweetbot
J\b
m\_
m_`(
Jbj
mbe
meh
lo~
Io~0resize_app_window
mpszoom.us
ost0narrow_center_position
Jtz
mtu"
mux
0resize_app_window
.aevtoappnull****0narrow_center_position0narrow_center_size0wide_center_position0wide_center_size0resize_app_window0app_name0win_position0win_size0app_name0win_position0win_size=

capp

prun

prcs

cobj

cwin

posn

ptsz>*/,e3+*/#k/l/lv*-,FOk/l/lv*-,FUUYh
.aevtoappnull****
k~@IT]hs~!,7BMXcr,ny'2=HS^ix(0narrow_center_position"m0narrow_center_size0wide_center_position0wide_center_size0resize_app_window]R4lvEOlvEOlvEOlvEO*m+O*m+O*m+O*m+O*alvm+O*aalvm+O*am+O*am+O*am+O*aalvaalvm+O*am+O*am+O*aalvm+O*am+O*am+O*am+O*am+O*am+O*a m+O*a!m+O*a"m+O*a#alvm+O*a$aa%lva&a'lvm+O*a(alvm+O*a)m+O*a*alvaalvm+O*a+alvm+("m(mascr
ޭ

FasdUAS 1.101.10
k
i
I	0resize_app_window

o0app_name

o0win_position

o0win_size
Z=
=
n
1

prun
4

capp
o0app_name
m
boovtrue
O9
O8
k7
r&
J  !
 n"#
"4$

cobj
$m
#o0win_position!%
%n&'
&4(

cobj
(m
'o0win_position
n)*
)1#%

posn
*l #+
+2 #

cwin,
,r'7-.
-J'1//01
0n'+23
24(+4

cobj
4m)*
3o'(0win_size15
5n+/67
64,/8

cobj
8m-.
7o+,0win_size
.n9:
9146

ptsz
:l14;
;214

cwin
4<

prcs
<o0app_name
m==sevsalis\Macintosh HDBDSystem Events.app
 cuCoreServices0/:System:Library:CoreServices:System Events.app/$System Events.appMacintosh HD-System/Library/CoreServices/System Events.app/>?
>l?@A
@lB
BrCD
CJEEFG
FmGH
Hm(
Do0narrow_center_positionAIJ
Il
K
Kr
LM
LJNNOP
Om"PQ
Qm	m
Mo0narrow_center_sizeJRS
RlSTU
TlV
VrWX
WJYYZ[
Zm[\
\m(
Xo0wide_center_positionU]^
]l_
_r`a
`Jbbcd
cmde
emm
ao0wide_center_size^fg
flghi
hl$j
jI$k0resize_app_windowklm
lmnnoo1Passwordmpq
po0narrow_center_positionqr
ro 0narrow_center_sizeist
sl%-u
uI%-v0resize_app_windowvwx
wm&'yyzzApp Storex{|
{o'(0narrow_center_position|}
}o()0narrow_center_sizet~
~l.6
I.60resize_app_window
m/0
Books
o010narrow_center_position
o120narrow_center_size
l7?
I7?0resize_app_window
m89Calendar
o9:0narrow_center_position
o:;0narrow_center_size
l@M
I@M0resize_app_window
mABCARROTweather
oBC0narrow_center_position
JCI
mCD"
mDG
lN]
IN]0resize_app_window
mORDiscord
oRS0narrow_center_position
JSY
mST"
mTW
l^h
I^h0resize_app_window
m_bFantastical
obc0narrow_center_position
ocd0narrow_center_size
lis
Iis0resize_app_window
mjmGoogle Chrome
omn0narrow_center_position~
ono}}0narrow_center_size~
lt~|{
It~zyz0resize_app_window
muxMail
oxyxx0narrow_center_positionw
oyzvv0narrow_center_sizewy|{
lut
Isrs0resize_app_window
mMessages
J
mqqp
moo(pn
J
mmml
mkklnrut
lji
Ihgh0resize_app_window
m
Music
off0narrow_center_positione
odd0narrow_center_sizeegji
lcb
Ia`a0resize_app_window
mNews
o__0narrow_center_position^
o]]0narrow_center_size^`cb
l\[
IZYZ0resize_app_window
m
Notes
oXX0narrow_center_positionW
J
mVV"
U

mTTUWY\[
l
SR

IQPQ0resize_app_window
mPhotos
oOO0narrow_center_positionN
oMM0narrow_center_sizeNPSR
lLK
IJIJ0resize_app_window
mPhotoshop
oHH0narrow_center_position G
 oFF0narrow_center_sizeGILK!"
!l#ED
#IC$BC0resize_app_window$%&
%m''((Preview&)*
)oAA0narrow_center_position*+@
+o??0narrow_center_size@BED",-
,l.>=
.I</;<0resize_app_window/01
0m2233RadarScope145
4o::0narrow_center_position569
6o880narrow_center_size9;>=-78
7l976
9I5:450resize_app_window:;<
;m==>>Reflect<?@
?o330narrow_center_position@A2
Ao110narrow_center_size24768BC
BlD0/
DI.E-.0resize_app_windowEFG
FmHHIIRoonGJK
Jo,,0narrow_center_positionKL+
LJMMNO
Nm**"OP)
Pm(()+-0/CQR
Ql
S'&
SI
%T$%0resize_app_windowTUV
UmWWXXSafariVYZ
Yo##0narrow_center_positionZ["
[o	!!0narrow_center_size"$'&R\]
\l^
^I_0resize_app_window_`a
`mbbccSiftieade
do0narrow_center_positionef
fo0narrow_center_size ]gh
gl(i
iI(j0resize_app_windowjkl
kmmmnn
Slacklop
oo0narrow_center_positionpq
qJ$rrst
sm"tu
um"hvw
vl)Ax
xI)Ay
0resize_app_windowyz{
zm*-||}}TextEdit{~
~J-5
m-0
m03

]
J5=
m58R
m8;4
w
lBQ
IBQ0resize_app_window
mCFThings
oFG0narrow_center_position
JGM
mGH"
mHK
lRa
IRa0resize_app_window
mSV
TIDAL
oVW0narrow_center_position
JW]
mWX"
mX[
lbx
Ibx0resize_app_window
mcfTweetbot
Jfl
mfi
mij(
Jlt
mlo
mor
ly
Iy0resize_app_window
mz}zoom.us
o}~0narrow_center_position
J~
m~"
m
0resize_app_window
.aevtoappnull****0narrow_center_position0narrow_center_size0wide_center_position0wide_center_size0resize_app_window0app_name0win_position0win_size0app_name0win_position0win_size=

capp

prun

prcs

cobj

cwin

posn

ptsz>*/,e3+*/#k/l/lv*-,FOk/l/lv*-,FUUYh
.aevtoappnull****
k@IT]hs~!,7BQ\gv,ny'2=HWbm|(0narrow_center_position"m0narrow_center_size0wide_center_position0wide_center_size0resize_app_window]R4lvEOlvEOlvEOlvEO*m+O*m+O*m+O*m+O*alvm+O*aalvm+O*am+O*am+O*am+O*aalvaalvm+O*am+O*am+O*aalvm+O*am+O*am+O*am+O*am+O*am+O*a alvm+O*a!m+O*a"m+O*a#alvm+O*a$aa%lva&a'lvm+O*a(alvm+O*a)alvm+O*a*alvaalvm+O*a+alvm+("m(mascr
ޭ


allow for unusual short date strings

allow for unusual short date strings

-- stolen from: https://discussions.apple.com/thread/3172966
property keyPhrase : "Trashed on: "
property securityLevel : 2 -- overwrites: 1=1-pass, 2=7-pass, 3=35-pass,  see man srm
property daysToWait : 7

tell application "Finder"
  -- get files in trash that are not new, and check dates
          set oldFiles to (every item of trash whose comment contains keyPhrase)
          set trashmeFiles to ""
          repeat with thisFile in oldFiles
  -- extract trashed date from the spotlight comments
                    set trashedDate to last item of my tid(comment of thisFile, keyPhrase)
                    try
  -- check dates in a try block in case of weirdness)
                              if my checkDate(trashedDate) then
                                        set trashmeFiles to trashmeFiles & " " & my makePosix(thisFile as alias)
                              end if
                    end try
          end repeat

  -- trash 'em in a subroutine
          my trashEm(trashmeFiles)

  -- gather new files
          set newFiles to every item of trash whose comment does not contain keyPhrase
  -- add the current date to the spotlight comment of the new files
          repeat with thisFile in newFiles
                    set c to comment of thisFile
                    if c = "" then
                              set comment of thisFile to keyPhrase & short date string of (current date)
                    else
                              set comment of thisFile to c & return & keyPhrase & short date string of (current date)
                    end if
          end repeat
end tell

on trashEm(fs)
  -- set up proper security level
          if securityLevel = 1 then
                    set cmd to "srm -rfsz"
          else if securityLevel = 3 then
                    set cmd to "srm -rfz"
          else
                    set cmd to "srm -rfmz"
          end if

  -- start a secure delete process in the background
          do shell script cmd & fs & " &> /dev/null &"
end trashEm

on tid(input, delim)
  -- generic subroutine to handle text items
          set {oldTID, my text item delimiters} to {my text item delimiters, delim}
          if class of input is list then
                    set output to input as text
          else
                    set output to text items of input
          end if
          set my text item delimiters to oldTID
          return output
end tid

on makePosix(f)
          return quoted form of POSIX path of f
end makePosix

on checkDate(d)
          return (date d) ≤ short date string of ((current date) - daysToWait * days)
end checkDate

-- stolen from: https://discussions.apple.com/thread/3172966
property keyPhrase : "Trashed on: "
property securityLevel : 2 -- overwrites: 1=1-pass, 2=7-pass, 3=35-pass,  see man srm
property daysToWait : 7

tell application "Finder"
  -- get files in trash that are not new, and check dates
          set oldFiles to (every item of trash whose comment contains keyPhrase)
          set trashmeFiles to ""
          repeat with thisFile in oldFiles
  -- extract trashed date from the spotlight comments
                    set trashedDate to last item of my tid(comment of thisFile, keyPhrase)
                    try
  -- check dates in a try block in case of weirdness)
                              if my checkDate(trashedDate) then
                                        set trashmeFiles to trashmeFiles & " " & my makePosix(thisFile as alias)
                              end if
                    end try
          end repeat

  -- trash 'em in a subroutine
          my trashEm(trashmeFiles)

  -- gather new files
          set newFiles to every item of trash whose comment does not contain keyPhrase
  -- add the current date to the spotlight comment of the new files
          repeat with thisFile in newFiles
                    set c to comment of thisFile
                    if c = "" then
                              set comment of thisFile to keyPhrase & short date string of (current date)
                    else
                              set comment of thisFile to c & return & keyPhrase & short date string of (current date)
                    end if
          end repeat
end tell

on trashEm(fs)
  -- set up proper security level
          if securityLevel = 1 then
                    set cmd to "srm -rfsz"
          else if securityLevel = 3 then
                    set cmd to "srm -rfz"
          else
                    set cmd to "srm -rfmz"
          end if

  -- start a secure delete process in the background
          do shell script cmd & fs & " &> /dev/null &"
end trashEm

on tid(input, delim)
  -- generic subroutine to handle text items
          set {oldTID, my text item delimiters} to {my text item delimiters, delim}
          if class of input is list then
                    set output to input as text
          else
                    set output to text items of input
          end if
          set my text item delimiters to oldTID
          return output
end tid

on makePosix(f)
          return quoted form of POSIX path of f
end makePosix

on checkDate(d)
          return (date d) ≤ (current date) - daysToWait * days
end checkDate


Do not create TIFF from artwork if it already exists

This prevents the creation of the artwork TIFF in get_artwork if the TIFF
already exists.

on replace_chars(this_text, search_string, replacement_string)
  set AppleScript's text item delimiters to the search_string
  set the item_list to every text item of this_text
  set AppleScript's text item delimiters to the replacement_string
  set this_text to the item_list as string
  set AppleScript's text item delimiters to ""
  return this_text
end replace_chars

on file_exists(filePath)
  tell application "Finder" to return exists filePath as POSIX file
end file_exists

tell application "Spotify"
  set currentArtwork to current track's artwork
  set savePath to POSIX path of (path to temporary items from user domain as string) & my replace_chars(current track's id,":","_")
  set tiffPath to (savePath & ".tiff")
  set pngPath to (savePath & ".png")
end tell

-- don't do the image events dance when the file already exists
if my file_exists(pngPath) then return pngPath

tell application "System Events"
  if not (my file_exists(tiffPath)) then
    set fileRef to (open for access tiffPath with write permission)
    write currentArtwork to fileRef
    close access fileRef
  end

  tell application "Image Events"
    launch
    set theImage to open tiffPath
    save theImage as PNG in pngPath
    quit
  end tell

  delete file tiffPath
  quit
end tell

return pngPath

on replace_chars(this_text, search_string, replacement_string)
  set AppleScript's text item delimiters to the search_string
  set the item_list to every text item of this_text
  set AppleScript's text item delimiters to the replacement_string
  set this_text to the item_list as string
  set AppleScript's text item delimiters to ""
  return this_text
end replace_chars

tell application "Spotify"
  set currentArtwork to current track's artwork
  set savePath to POSIX path of (path to temporary items from user domain as string) & my replace_chars(current track's id,":","_")
  set tiffPath to (savePath & ".tiff")
  set pngPath to (savePath & ".png")
end tell

-- don't do the image events dance when the file already exists
tell application "Finder"
  if exists pngPath as POSIX file then
    return pngPath
  end if
end tell

tell application "System Events"
  set fileRef to (open for access tiffPath with write permission)
  write currentArtwork to fileRef
  close access fileRef

  tell application "Image Events"
    launch
    set theImage to open tiffPath
    save theImage as PNG in pngPath
    quit
  end tell

  delete file tiffPath
  quit
end tell

return pngPath


windowSize.applescript, from darwin14

windowSize.applescript, from darwin14

property DEF_XSIZE : 1
property DEF_YSIZE : 1
property DEF_XPOS : 0
property DEF_YPOS : 0

property DEF_LEFT_MARGIN : 10
property DEF_RIGHT_MARGIN : 10
property DEF_TOP_MARGIN : 10
property DEF_BOTTOM_MARGIN : 10

property DEF_APPNAME : ""
property DEF_WINDOWNUMBER : ""
property DEF_MONPOSX : ""
property DEF_MONPOSY : ""
property DEF_RESIZE : 1
property DEF_DIRECTION : ""

property DEF_MOVEFORMON_FLAG : true
property DEF_DEBUG_LEVEL : 0

property GEEKTOOL_WINDOW : 1
property GEEKTOOL_MARGIN : 10

-- Window size main function
on windowSize(pars)
	-- Set Parameters
	set xsize to xsize of (pars & {xsize:DEF_XSIZE})
	set ysize to ysize of (pars & {ysize:DEF_YSIZE})
	set xpos to xpos of (pars & {xpos:DEF_XPOS})
	set ypos to ypos of (pars & {ypos:DEF_YPOS})
	set leftmargin to leftmargin of (pars & {leftmargin:DEF_LEFT_MARGIN})
	set rightmargin to rightmargin of (pars & {rightmargin:DEF_RIGHT_MARGIN})
	set topmargin to topmargin of (pars & {topmargin:DEF_TOP_MARGIN})
	set bottommargin to bottommargin of (pars & {bottommargin:DEF_BOTTOM_MARGIN})
	set appName to appName of (pars & {appName:DEF_APPNAME})
	set windowNumber to windowNumber of (pars & {windowNumber:DEF_WINDOWNUMBER})
	set monPosX to monPosX of (pars & {monPosX:DEF_MONPOSX})
	set monPosY to monPosY of (pars & {monPosY:DEF_MONPOSY})
	set resize to resize of (pars & {resize:DEF_RESIZE})
	set direction to direction of (pars & {direction:DEF_DIRECTION})
	set moveformon_flag to moveformon_flag of (pars & {moveformon_flag:DEF_MOVEFORMON_FLAG})
	set debug_level to debug_level of (pars & {debug_level:DEF_DEBUG_LEVEL})

	-- Debug mode
	if debug_level > 0 then
		log "debug mode = " & debug_level
		if debug_level > 1 then
			display dialog "debug mode = " & debug_level
		end if
	end if

	-- Get application name and window number, if appName is "", if windowNumber is not set, set 1
	if appName is "" then
		tell application "System Events"
			set pList to name of every process whose frontmost is true
			set appName to item 1 of pList
		end tell
	end if
	if windowNumber is "" then
		set windowNumber to 1
	end if

	if debug_level > 0 then
		log "windowSize(" & xsize & ", " & ysize & ", " & xpos & ", " & ypos & ", " & leftmargin & ", " & rightmargin & ", " & topmargin & ", " & bottommargin & ", " & appName & ", " & windowNumber & ", " & monPosX & ", " & monPosY & "," & resize & "," & moveformon_flag & "," & debug_level & ")"
		if debug_level > 5 then
			display dialog "windowSize(" & xsize & ", " & ysize & ", " & xpos & ", " & ypos & ", " & leftmargin & ", " & rightmargin & ", " & topmargin & ", " & bottommargin & ", " & appName & ", " & windowNumber & ", " & monPosX & ", " & monPosY & "," & resize & "," & moveformon_flag & "," & debug_level & ")"
		end if
	end if

	tell application "Finder"
		set scriptPath to (path to me)'s folder as text
	end tell

	-- First, move monitor
	if moveformon_flag then
		set moveForMonScpt to scriptPath & "moveForMon.scpt"
		set moveformon to load script file moveForMonScpt
		moveformon's moveformon({all:false})
	end if

	-- Get window position
	tell application "System Events"
		tell process appName
			try
				set topWindow to item windowNumber of (every window whose focused is true)
			on error
				set topWindow to window windowNumber
			end try
			set winPos to position of topWindow
			set winSize to size of topWindow
			set winPosX to item 1 of winPos
			set winPosY to item 2 of winPos
			set winSizeX to item 1 of winSize
			set winSizeY to item 2 of winSize
			set winPosRT to {winPosX + winSizeX, winPosY}
			set winPosLB to {winPosX, winPosY + winSizeY}
			set winPosRB to {winPosX + winSizeX, winPosY + winSizeY}
			if debug_level > 0 then
				log "winPos(" & winPosX & ", " & winPosY & ")"
				log "winSize(" & winSizeX & ", " & winSizeY & ")"
				if debug_level > 5 then
					display dialog "winPos(" & winPosX & ", " & winPosY & ")"
					display dialog "winSize(" & winSizeX & ", " & winSizeY & ")"
				end if
			end if
		end tell
	end tell

	-- Get screen (display) size
	set getFrameScpt to scriptPath & "getFrame.scpt"
	set gf to load script file getFrameScpt
	set vframes to gf's getAllVisibleFrames()
	set getCurrentFrameScpt to scriptPath & "getCurrentFrame.scpt"
	set gcf to load script file getCurrentFrameScpt

	if monPosX is not "" and monPosY is not "" then
		set cf to gcf's getCurrentFrame(monPosX, monPosY, vframes)
	else
		set cf to gcf's getCurrentFrame(item 1 of winPos, item 2 of winPos, vframes)
		if cf is 0 then
			set cf to gcf's getCurrentFrame(item 1 of winPosRT, item 2 of winPosRT, vframes)
			if cf is 0 then
				set cf to gcf's getCurrentFrame(item 1 of winPosLB, item 2 of winPosLB, vframes)
				if cf is 0 then
					set cf to gcf's getCurrentFrame(item 1 of winPosRB, item 2 of winPosRB, vframes)
				end if
			end if
		end if
	end if

	set recordlib to scriptPath & "recordlib.scpt"
	set rb to load script file recordlib

	set frames to rb's getKeyValue(vframes, item 1 of cf)
	set frame to item (item 2 of cf) of frames

	-- Move screen
	if direction is not "" then
		set fname to item 1 of cf
		set nout to item 2 of cf
		set nleft to length of rb's getKeyValue(vframes, "left_frames")
		set nright to length of rb's getKeyValue(vframes, "right_frames")
		set ntop to length of rb's getKeyValue(vframes, "top_frames")
		set nbottom to length of rb's getKeyValue(vframes, "bottom_frames")
		if direction is "LEFT" then
			if fname is "main_frames" then
				if nleft > 0 then
					set frame to item 1 of rb's getKeyValue(vframes, "left_frames")
				end if
			else if fname is "left_frames" then
				if nleft > nout then
					set frame to item (nout + 1) of rb's getKeyValue(vframes, "left_frames")
				end if
			else if fname is "right_frames" then
				if nout is 1 then
					set frame to item 1 of rb's getKeyValue(vframes, "main_frames")
				else
					set frame to item (nout - 1) of rb's getKeyValue(vframes, "right_frames")
				end if
			end if
		else if direction is "RIGHT" then
			if fname is "main_frames" then
				if nright > 0 then
					set frame to item 1 of rb's getKeyValue(vframes, "right_frames")
				end if
			else if fname is "right_frames" then
				if nright > nout then
					set frame to item (nout + 1) of rb's getKeyValue(vframes, "right_frames")
				end if
			else if fname is "left_frames" then
				if nout is 1 then
					set frame to item 1 of rb's getKeyValue(vframes, "main_frames")
				else
					set frame to item (nout - 1) of rb's getKeyValue(vframes, "left_frames")
				end if
			end if
		else if direction is "UP" then
			if fname is "main_frames" then
				if ntop > 0 then
					set frame to item 1 of rb's getKeyValue(vframes, "top_frames")
				end if
			else if fname is "top_frames" then
				if ntop > nout then
					set frame to item (nout + 1) of rb's getKeyValue(vframes, "top_frames")
				end if
			else if fname is "bottom_frames" then
				if nout is 1 then
					set frame to item 1 of rb's getKeyValue(vframes, "main_frames")
				else
					set frame to item (nout - 1) of rb's getKeyValue(vframes, "bottom_frames")
				end if
			end if
		else if direction is "DOWN" then
			if fname is "main_frames" then
				if nbottom > 0 then
					set frame to item 1 of rb's getKeyValue(vframes, "bottom_frames")
				end if
			else if fname is "bottom_frames" then
				if nbottom > nout then
					set frame to item (nout + 1) of rb's getKeyValue(vframes, "bottom_frames")
				end if
			else if fname is "top_frames" then
				if nout is 1 then
					set frame to item 1 of rb's getKeyValue(vframes, "main_frames")
				else
					set frame to item (nout - 1) of rb's getKeyValue(vframes, "top_frames")
				end if
			end if
		end if
	end if

	set dPosX to origin's x of frame
	set dPosY to origin's y of frame
	set dWidth to |size|'s width of frame
	set dHeight to |size|'s height of frame
	if debug_level > 0 then
		log "svs(" & dPosX & ", " & dPosY & ", " & dWidth & ", " & dHeight & ")"
		if debug_level > 5 then
			display dialog "svs(" & dPosX & ", " & dPosY & ", " & dWidth & ", " & dHeight & ")"
		end if
	end if

	-- Get GeekTool's position
	tell application "System Events"
		try
			tell process "GeekTool Helper"
				set topWindow to window GEEKTOOL_WINDOW
				set gtPos to position of topWindow
			end tell
			set gtflag to 1
		on error
			set gtflag to 0
		end try
	end tell

	-- Check if the window and GeekTool are in same screen
	if gtflag is 1 then
		set gtsvs to gf's getVisibleFrame(item 1 of gtPos, item 2 of gtPos)
		set gtdPosX to origin's x of gtsvs
		set gtdPosY to origin's y of gtsvs
		if dPosX is gtdPosX and dPosY is gtdPosY then
			try
				set gtSize to size of topWindow
				set geekToolWidth to item 1 of gtSize
				set geekToolWidth to geekToolWidth + GEEKTOOL_MARGIN -- additional margin
			on error
				set geekToolWidth to 0
			end try
		else
			set geekToolWidth to 0
		end if
	end if
	--if item 1 of winPos < 0 then
	--	set geekToolWidth to 160
	--	set geekToolWidth to geekToolWidth + GEEKTOOL_MARGIN -- additional margin
	--else
	--	set geekToolWidth to 0
	--end if

	-- Subtract geekToolWidth from display width
	set dWidth to dWidth - geekToolWidth

	-- Resize/move
	tell application "System Events"
		tell process appName
			try
				set topWindow to item windowNumber of (every window whose focused is true)
			on error
				set topWindow to window windowNumber
			end try
			-- Set screen size w/o margins
			--set useSize to {dWidth - leftmargin - rightmargin, dHeight - topmargin - bottommargin}
			--if debug_level > 0 then
			--	log "useSize(" & item 1 of useSize & ", " & item 2 of useSize & ")"
			--	if debug_level > 5 then
			--		display dialog "useSize(" & item 1 of useSize & ", " & item 2 of useSize & ")"
			--	end if
			--end if
			-- No margin w/o edges of screen
			--set wpos to {dPosX + leftmargin + xpos * (item 1 of useSize), dPosY + topmargin + ypos * (item 2 of useSize)}
			--set wsize to {xsize * (item 1 of useSize), ysize * (item 2 of useSize)}

			-- Set margin in any place
			set wpos to {dPosX + leftmargin + xpos * dWidth, dPosY + topmargin + ypos * dHeight}
			set wsize to {xsize * dWidth - leftmargin - rightmargin, ysize * dHeight - topmargin - bottommargin}

			if debug_level > 0 then
				log "wpos(" & item 1 of wpos & ", " & item 2 of wpos & ")"
				log "wsize(" & item 1 of wsize & ", " & item 2 of wsize & ")"
				if debug_level > 5 then
					display dialog "wpos(" & item 1 of wpos & ", " & item 2 of wpos & ")"
					display dialog "wsize(" & item 1 of wsize & ", " & item 2 of wsize & ")"
				end if
			end if
			tell topWindow
				if debug_level > 0 then
					log "preoperties before= "
					log properties
				end if
				set position to wpos
				if resize is 1 then
					set size to wsize
					-- When the original height is larger than the display size,
					-- the resize couldn't work well.
					-- Need to resize lower edge to internal of the display ({1,1})
					-- then resize to target size.
					-- -> resize to {1,1} could make a crash for such a terminal with screen.
					--    (maybe too small to resize windows.)
					--   use {100,100} for safe.
					-- if height is longer than display size, width can't be shorten than display size.
					-- Then, sometime only height can be changed first in the below procedure,
					-- then, need one more resize for the width (5 times for safe, but normamlly it should be fixed in a 2 times.)
					repeat 5 times
						set winSize to size
						if item 1 of winSize > item 1 of wsize or item 2 of winSize > item 2 of wsize then
							set size to {100, 100}
							set size to wsize
							delay 0.1
						else
							exit repeat
						end if
					end repeat
				end if
			end tell
		end tell
	end tell
end windowSize

on run
	windowSize({})
end run

property DEF_XSIZE : 1
property DEF_YSIZE : 1
property DEF_XPOS : 0
property DEF_YPOS : 0

property DEF_LEFT_MARGIN : 10
property DEF_RIGHT_MARGIN : 10
property DEF_TOP_MARGIN : 10
property DEF_BOTTOM_MARGIN : 10

property DEF_APPNAME : ""
property DEF_WINDOWNUMBER : ""
property DEF_MONPOSX : ""
property DEF_MONPOSY : ""
property DEF_RESIZE : 1
property DEF_DIRECTION : ""

property DEF_MOVEFORMON_FLAG : true
property DEF_DEBUG_LEVEL : 0

property GEEKTOOL_WINDOW : 1
property GEEKTOOL_MARGIN : 10

-- Window size main function
on windowSize(pars)
	-- Set Parameters
	set xsize to xsize of (pars & {xsize:DEF_XSIZE})
	set ysize to ysize of (pars & {ysize:DEF_YSIZE})
	set xpos to xpos of (pars & {xpos:DEF_XPOS})
	set ypos to ypos of (pars & {ypos:DEF_YPOS})
	set leftmargin to leftmargin of (pars & {leftmargin:DEF_LEFT_MARGIN})
	set rightmargin to rightmargin of (pars & {rightmargin:DEF_RIGHT_MARGIN})
	set topmargin to topmargin of (pars & {topmargin:DEF_TOP_MARGIN})
	set bottommargin to bottommargin of (pars & {bottommargin:DEF_BOTTOM_MARGIN})
	set appName to appName of (pars & {appName:DEF_APPNAME})
	set windowNumber to windowNumber of (pars & {windowNumber:DEF_WINDOWNUMBER})
	set monPosX to monPosX of (pars & {monPosX:DEF_MONPOSX})
	set monPosY to monPosY of (pars & {monPosY:DEF_MONPOSY})
	set resize to resize of (pars & {resize:DEF_RESIZE})
	set direction to direction of (pars & {direction:DEF_DIRECTION})
	set moveformon_flag to moveformon_flag of (pars & {moveformon_flag:DEF_MOVEFORMON_FLAG})
	set debug_level to debug_level of (pars & {debug_level:DEF_DEBUG_LEVEL})

	-- Debug mode
	if debug_level > 0 then
		log "debug mode = " & debug_level
		if debug_level > 1 then
			display dialog "debug mode = " & debug_level
		end if
	end if

	-- Get application name and window number, if appName is "", if windowNumber is not set, set 1
	if appName is "" then
		tell application "System Events"
			set pList to name of every process whose frontmost is true
			set appName to item 1 of pList
		end tell
	end if
	if windowNumber is "" then
		set windowNumber to 1
	end if

	if debug_level > 0 then
		log "windowSize(" & xsize & ", " & ysize & ", " & xpos & ", " & ypos & ", " & leftmargin & ", " & rightmargin & ", " & topmargin & ", " & bottommargin & ", " & appName & ", " & windowNumber & ", " & monPosX & ", " & monPosY & "," & resize & "," & moveformon_flag & "," & debug_level & ")"
		if debug_level > 5 then
			display dialog "windowSize(" & xsize & ", " & ysize & ", " & xpos & ", " & ypos & ", " & leftmargin & ", " & rightmargin & ", " & topmargin & ", " & bottommargin & ", " & appName & ", " & windowNumber & ", " & monPosX & ", " & monPosY & "," & resize & "," & moveformon_flag & "," & debug_level & ")"
		end if
	end if

	tell application "Finder"
		set scriptPath to (path to me)'s folder as text
	end tell

	-- First, move monitor
	if moveformon_flag then
		set moveForMonScpt to scriptPath & "moveForMon.scpt"
		set moveformon to load script file moveForMonScpt
		moveformon's moveformon({all:false})
	end if

	-- Get window position
	tell application "System Events"
		tell process appName
			try
				set topWindow to item windowNumber of (every window whose focused is true)
			on error
				set topWindow to window windowNumber
			end try
			set winPos to position of topWindow
			set winSize to size of topWindow
			set winPosX to item 1 of winPos
			set winPosY to item 2 of winPos
			set winSizeX to item 1 of winSize
			set winSizeY to item 2 of winSize
			set winPosRT to {winPosX + winSizeX, winPosY}
			set winPosLB to {winPosX, winPosY + winSizeY}
			set winPosRB to {winPosX + winSizeX, winPosY + winSizeY}
			if debug_level > 0 then
				log "winPos(" & winPosX & ", " & winPosY & ")"
				log "winSize(" & winSizeX & ", " & winSizeY & ")"
				if debug_level > 5 then
					display dialog "winPos(" & winPosX & ", " & winPosY & ")"
					display dialog "winSize(" & winSizeX & ", " & winSizeY & ")"
				end if
			end if
		end tell
	end tell

	-- Get screen (display) size
	set getFrameScpt to scriptPath & "getFrame.scpt"
	set gf to load script file getFrameScpt
	set vframes to gf's getAllVisibleFrames()
	set getCurrentFrameScpt to scriptPath & "getCurrentFrame.scpt"
	set gcf to load script file getCurrentFrameScpt

	if monPosX is not "" and monPosY is not "" then
		set cf to gcf's getCurrentFrame(monPosX, monPosY, vframes)
	else
		set cf to gcf's getCurrentFrame(item 1 of winPos, item 2 of winPos, vframes)
		if cf is 0 then
			set cf to gcf's getCurrentFrame(item 1 of winPosRT, item 2 of winPosRT, vframes)
			if cf is 0 then
				set cf to gcf's getCurrentFrame(item 1 of winPosLB, item 2 of winPosLB, vframes)
				if cf is 0 then
					set cf to gcf's getCurrentFrame(item 1 of winPosRB, item 2 of winPosRB, vframes)
				end if
			end if
		end if
	end if

	set recordlib to scriptPath & "recordlib.scpt"
	set rb to load script file recordlib

	set frames to rb's getKeyValue(vframes, item 1 of cf)
	set frame to item (item 2 of cf) of frames

	-- Move screen
	if direction is not "" then
		set fname to item 1 of cf
		set nout to item 2 of cf
		set nleft to length of rb's getKeyValue(vframes, "left_frames")
		set nright to length of rb's getKeyValue(vframes, "right_frames")
		set ntop to length of rb's getKeyValue(vframes, "top_frames")
		set nbottom to length of rb's getKeyValue(vframes, "bottom_frames")
		if direction is "LEFT" then
			if fname is "main_frames" then
				if nleft > 0 then
					set frame to item 1 of rb's getKeyValue(vframes, "left_frames")
				end if
			else if fname is "left_frames" then
				if nleft > nout then
					set frame to item (nout + 1) of rb's getKeyValue(vframes, "left_frames")
				end if
			else if fname is "right_frames" then
				if nout is 1 then
					set frame to item 1 of rb's getKeyValue(vframes, "main_frames")
				else
					set frame to item (nout - 1) of rb's getKeyValue(vframes, "right_frames")
				end if
			end if
		else if direction is "RIGHT" then
			if fname is "main_frames" then
				if nright > 0 then
					set frame to item 1 of rb's getKeyValue(vframes, "right_frames")
				end if
			else if fname is "right_frames" then
				if nright > nout then
					set frame to item (nout + 1) of rb's getKeyValue(vframes, "right_frames")
				end if
			else if fname is "left_frames" then
				if nout is 1 then
					set frame to item 1 of rb's getKeyValue(vframes, "main_frames")
				else
					set frame to item (nout - 1) of rb's getKeyValue(vframes, "left_frames")
				end if
			end if
		else if direction is "UP" then
			if fname is "main_frames" then
				if ntop > 0 then
					set frame to item 1 of rb's getKeyValue(vframes, "top_frames")
				end if
			else if fname is "top_frames" then
				if ntop > nout then
					set frame to item (nout + 1) of rb's getKeyValue(vframes, "top_frames")
				end if
			else if fname is "bottom_frames" then
				if nout is 1 then
					set frame to item 1 of rb's getKeyValue(vframes, "main_frames")
				else
					set frame to item (nout - 1) of rb's getKeyValue(vframes, "bottom_frames")
				end if
			end if
		else if direction is "DOWN" then
			if fname is "main_frames" then
				if nbottom > 0 then
					set frame to item 1 of rb's getKeyValue(vframes, "bottom_frames")
				end if
			else if fname is "bottom_frames" then
				if nbottom > nout then
					set frame to item (nout + 1) of rb's getKeyValue(vframes, "bottom_frames")
				end if
			else if fname is "top_frames" then
				if nout is 1 then
					set frame to item 1 of rb's getKeyValue(vframes, "main_frames")
				else
					set frame to item (nout - 1) of rb's getKeyValue(vframes, "top_frames")
				end if
			end if
		end if
	end if

	set dPosX to origin's x of frame
	set dPosY to origin's y of frame
	set dWidth to |size|'s width of frame
	set dHeight to |size|'s height of frame
	if debug_level > 0 then
		log "svs(" & dPosX & ", " & dPosY & ", " & dWidth & ", " & dHeight & ")"
		if debug_level > 5 then
			display dialog "svs(" & dPosX & ", " & dPosY & ", " & dWidth & ", " & dHeight & ")"
		end if
	end if

	-- Get GeekTool's position
	tell application "System Events"
		try
			tell process "GeekTool Helper"
				set topWindow to window GEEKTOOL_WINDOW
				set gtPos to position of topWindow
			end tell
			set gtflag to 1
		on error
			set gtflag to 0
		end try
	end tell

	-- Check if the window and GeekTool are in same screen
	if gtflag is 1 then
		set gtsvs to gf's getVisibleFrame(item 1 of gtPos, item 2 of gtPos)
		set gtdPosX to origin's x of gtsvs
		set gtdPosY to origin's y of gtsvs
		if dPosX is gtdPosX and dPosY is gtdPosY then
			try
				set gtSize to size of topWindow
				set geekToolWidth to item 1 of gtSize
				set geekToolWidth to geekToolWidth + GEEKTOOL_MARGIN -- additional margin
			on error
				set geekToolWidth to 0
			end try
		else
			set geekToolWidth to 0
		end if
	end if
	--if item 1 of winPos < 0 then
	--	set geekToolWidth to 160
	--	set geekToolWidth to geekToolWidth + GEEKTOOL_MARGIN -- additional margin
	--else
	--	set geekToolWidth to 0
	--end if

	-- Subtract geekToolWidth from display width
	set dWidth to dWidth - geekToolWidth

	-- Resize/move
	tell application "System Events"
		tell process appName
			try
				set topWindow to item windowNumber of (every window whose focused is true)
			on error
				set topWindow to window windowNumber
			end try
			-- Set screen size w/o margins
			--set useSize to {dWidth - leftmargin - rightmargin, dHeight - topmargin - bottommargin}
			--if debug_level > 0 then
			--	log "useSize(" & item 1 of useSize & ", " & item 2 of useSize & ")"
			--	if debug_level > 5 then
			--		display dialog "useSize(" & item 1 of useSize & ", " & item 2 of useSize & ")"
			--	end if
			--end if
			-- No margin w/o edges of screen
			--set wpos to {dPosX + leftmargin + xpos * (item 1 of useSize), dPosY + topmargin + ypos * (item 2 of useSize)}
			--set wsize to {xsize * (item 1 of useSize), ysize * (item 2 of useSize)}

			-- Set margin in any place
			set wpos to {dPosX + leftmargin + xpos * dWidth, dPosY + topmargin + ypos * dHeight}
			set wsize to {xsize * dWidth - leftmargin - rightmargin, ysize * dHeight - topmargin - bottommargin}

			if debug_level > 0 then
				log "wpos(" & item 1 of wpos & ", " & item 2 of wpos & ")"
				log "wsize(" & item 1 of wsize & ", " & item 2 of wsize & ")"
				if debug_level > 5 then
					display dialog "wpos(" & item 1 of wpos & ", " & item 2 of wpos & ")"
					display dialog "wsize(" & item 1 of wsize & ", " & item 2 of wsize & ")"
				end if
			end if
			tell topWindow
				if debug_level > 0 then
					log "preoperties before= "
					log properties
				end if
				set position to wpos
				if resize is 1 then
					set size to wsize
					-- When the original height is larger than the display size,
					-- the resize couldn't work well.
					-- Need to resize lower edge to internal of the display ({1,1})
					-- then resize to target size.
					set winSize to size
					if item 1 of winSize > item 1 of wsize or item 2 of winSize > item 2 of wsize then
						set size to {1, 1}
						set size to wsize
					end if
				end if
			end tell

		end tell
	end tell
end windowSize

on run
	windowSize({})
end run