Make playartist filter faster and honor sort order

-- core configuration --

-- configurable options --

-- limit number of songs to improve efficiency
property resultLimit : 15
-- whether or not to retrieve/display album artwork for each result
property albumArtEnabled : true

-- workflow parameters --

-- workflow folders
property libraryFolder : (path to library folder from user domain as text)
property cacheFolder : (libraryFolder & "Caches:")
property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred:Workflow Data:")
property bundleId : "com.calebevans.playsong"
property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text

-- the default icon used for search results without album artwork
property defaultIconName : "resources/icon-noartwork.png"
-- the name of the playlist used by the workflow for playing songs
property workflowPlaylistName : "Alfred Play Song"
-- list of Alfred results
property resultList : {}

-- replaces substring in string with another substring
on replace(replaceThis, replaceWith, theString)

	set oldDelims to AppleScript's text item delimiters
	set AppleScript's text item delimiters to replaceThis
	set strItems to text items of theString
	set AppleScript's text item delimiters to replaceWith
	set newString to strItems as text
	set AppleScript's text item delimiters to oldDelims
	return newString

end replace

-- retrieve the plural/singular form of a quantity based on the given number
on quantifyNumber(theNumber, quantityName, pluralQuantityName)

	if theNumber is 1 then

		set theString to (theNumber as text) & space & quantityName

	else

		set theString to (theNumber as text) & space & pluralQuantityName

	end if

	return theString

end quantifyNumber

-- encodes JSON reserved characters in the given string
on encodeFeedbackChars(theString)

	set theString to replace("\\", "\\\\", theString)
	set theString to replace("\"", "\\\"", theString)
	return theString

end encodeFeedbackChars

-- decodes JSON reserved characters in the given string
on decodeFeedbackChars(theString)

	set theString to replace("\\\\", "\\", theString)
	set theString to replace("\\\"", "\"", theString)
	return theString

end decodeFeedbackChars

-- adds Alfred result to result list
on addResult(theResult)

	copy theResult to the end of resultList

end addResult

-- adds item for "No Results" message
on addNoResultsItem(query, queryType)

	addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName})

end addNoResultsItem

on resultListIsFull()

	return (length of resultList is resultLimit)

end resultListIsFull

on resultListIsEmpty()

	return (length of resultList is 0)

end resultListIsFull

-- builds Alfred result item as JSON
on getResultFeedback(theResult)

	-- encode reserved JSON characters
	set resultUid to encodeFeedbackChars(uid of theResult)
	set resultValid to (valid of theResult) as text
	set resultTitle to encodeFeedbackChars(title of theResult)
	set resultSubtitle to encodeFeedbackChars(subtitle of theResult)

	if (icon of theResult) contains ":" then

		set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult)

	else

		set resultIcon to icon of theResult

	end if

	set json to "{"
	set json to json & "\"uid\":\"" & resultUid & "\","
	set json to json & "\"arg\":\"" & resultUid & "\","
	set json to json & "\"valid\":\"" & resultValid & "\","
	set json to json & "\"title\":\"" & resultTitle & "\","
	set json to json & "\"subtitle\":\"" & resultSubtitle & "\","
	set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}"
	set json to json & "}"
	return json

end getResultFeedback

-- retrieves JSON document for Alfred results
on getResultListFeedback()

	set json to "{\"items\": ["

	repeat with theResult in resultList

		set json to json & getResultFeedback(theResult)
		set json to json & ","

	end repeat

	-- remove trailing comma after last item
	set json to text 1 thru (length of json - 1) of json
	set json to json & "]}"
	return json

end getResultListFeedback

-- query path to artwork image file cached natively by Music.app in Catalina
on getSongArtworkPath(theSong)

	try

		if albumArtEnabled is false then return defaultIconName

		tell application "Music"

			-- get persistent ID of song and use it to fetch album artwork
			set songId to persistent ID of theSong
			-- the base path to the artwork file (without extension)
			set artworkPath to (do shell script "./resources/get-song-artwork-path.sh" & space & songId & space & defaultIconName)

		end tell

		return artworkPath

	on error errorMessage

		log errorMessage

	end try

end getSongArtworkPath

-- creates album artwork cache
on createWorkflowPlaylist()

	tell application "Music"

		if not (user playlist workflowPlaylistName exists) then

			make new user playlist with properties {name:workflowPlaylistName, shuffle:false}

		end if

	end tell

end createWorkflowPlaylist

on clearQueue()

	tell application "Music"

		if user playlist workflowPlaylistName exists then

			delete tracks of user playlist workflowPlaylistName

		end if

	end tell

end clearQueue

on queueSongs(theSongs)

	tell application "Music"

		repeat with theSong in theSongs

			duplicate theSong to user playlist workflowPlaylistName

		end repeat

	end tell

end queueSongs

on playQueue()

	tell application "Music"

		if number of tracks in user playlist workflowPlaylistName is not 0 then

			play user playlist workflowPlaylistName

		end if

	end tell

end playQueue

on getPlaylist(playlistId)

	tell application "Music"

		return (first playlist whose id is playlistId)

	end tell

end getPlaylist

on getPlaylistSongs(playlistId)

	tell application "Music"

		set thePlaylist to getPlaylist(playlistId) of me
		set playlistSongs to every track of thePlaylist

	end tell

	return playlistSongs

end getPlaylistSongs

-- retrieves list of songs within the given genre, sorted by artist
on getGenreSongs(genreName)

	tell application "Music"

		return every track of playlist 2 whose genre is genreName

	end tell

end getGenreSongs

-- retrieves list of songs by the given artist, sorted by album
on getArtistSongs(artistName)

	tell application "Music"

		set artistSongs to every track of playlist 2 whose artist is artistName

	end tell

	return artistSongs

end getArtistSongs

-- retrieves list of songs in the given album
on getAlbumSongs(albumName)

	tell application "Music"

		set albumSongs to every track of playlist 2 whose album is albumName

	end tell

	return albumSongs

end getAlbumSongs

-- retrieves the song with the given ID
on getSong(songId)

	tell application "Music"

		set theSong to first track of playlist 2 whose database ID is songId

	end tell

	return theSong

end getSong

-- retrieves a list of objects or names matching the given query and type
on getResultsFromQuery(query, queryType)

	set evalScript to run script "
	script

		on findResults(query, queryType, resultLimit)

			tell application \"Music\"

				set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query)

				if length of theSongs < resultLimit then

					set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query)

				end if

				if length of theSongs < resultLimit then

					set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query))

				end if

				if length of theSongs is 0 then

					if queryType is \"name\" then

						set theSongs to theSongs & (search playlist 2 for query only songs)

					else if queryType is not \"genre\" then

						set theSongs to theSongs & (search playlist 2 for query only " & queryType & "s)

					end if

				end if

				if queryType is \"name\" then

					if length of theSongs > resultLimit then

						set theSongs to items 1 thru resultLimit of theSongs

					end if

					set theResults to theSongs

				else

					set theResults to {}

					repeat with theSong in theSongs

						if length of theResults is resultLimit then exit repeat

						set theResult to " & queryType & " of theSong

						if theResult is not in theResults then

							set theResults to theResults & theResult

						end if

					end repeat

				end if

			end tell

			return theResults

		end findResults

	end script
	"

	evalScript's findResults(query, queryType, resultLimit)

end getResultsFromQuery

-- returns the given string with leading and trailing whitespace removed
on trimWhitespace(theString)

	-- trim leading whitespace
	repeat while theString begins with space

		if length of theString is 1 then return ""
		set theString to text 2 thru end of theString

	end repeat

	-- trim trailing whitespace
	repeat while theString ends with space

		set theString to text 1 thru ((length of theString) - 1) of theString

	end repeat

	return theString

end trimWhitespace

-- queues the song with the given ID
on queueSong(songId)

	set theSong to getSong(songId)
	queueSongs({theSong})

end queueSong

-- queues all songs belonging to the given album
on queueAlbum(albumName)

	set albumName to decodeFeedbackChars(albumName)
	set albumSongs to getAlbumSongs(albumName)
	queueSongs(albumSongs)

end queueAlbum

-- queues all songs by the given artist
on queueArtist(artistName)

	set artistName to decodeFeedbackChars(artistName)
	set artistSongs to getArtistSongs(artistName)
	queueSongs(artistSongs)

end queueArtist

-- queues all songs within the given genre
on queueGenre(genreName)

	set genreName to decodeFeedbackChars(genreName)
	set genreSongs to getGenreSongs(genreName)
	queueSongs(genreSongs)

end queueGenre

-- queues all songs in the given playlist
on queuePlaylist(playlistId)

	set playlistSongs to getPlaylistSongs(playlistId)
	queueSongs(playlistSongs)

end queuePlaylist

-- parses the given result query to retrieve type and id of item to queue
on parseResultQuery(query)

	set pos to offset of "-" in query
	set theType to text 1 thru (pos - 1) of query
	set theId to text (pos + 1) thru end of query
	return {type:theType, id:theId}

end parseResultQuery

on queue(query)

	set typeAndId to parseResultQuery(query)
	set theType to type of typeAndId
	set theId to id of typeAndId

	createWorkflowPlaylist()

	if theType is "song" then
		queueSong(theId)
	else if theType is "album" then
		queueAlbum(theId)
	else if theType is "artist" then
		queueArtist(theId)
	else if theType is "genre" then
		queueGenre(theId)
	else if theType is "playlist" then
		queuePlaylist(theId)
	else
		log "Unsupported type: " & theType
	end if

end queue

on play(query)

	clearQueue()
	queue(query)
	playQueue()

end play

-- core configuration --

-- configurable options --

-- limit number of songs to improve efficiency
property resultLimit : 15
-- whether or not to retrieve/display album artwork for each result
property albumArtEnabled : true

-- workflow parameters --

-- workflow folders
property libraryFolder : (path to library folder from user domain as text)
property cacheFolder : (libraryFolder & "Caches:")
property alfredWorkflowDataFolder : (cacheFolder & "com.runningwithcrayons.Alfred:Workflow Data:")
property bundleId : "com.calebevans.playsong"
property workflowCacheFolder : (alfredWorkflowDataFolder & bundleId & ":") as text

-- the default icon used for search results without album artwork
property defaultIconName : "resources/icon-noartwork.png"
-- the name of the playlist used by the workflow for playing songs
property workflowPlaylistName : "Alfred Play Song"
-- list of Alfred results
property resultList : {}

-- replaces substring in string with another substring
on replace(replaceThis, replaceWith, theString)

	set oldDelims to AppleScript's text item delimiters
	set AppleScript's text item delimiters to replaceThis
	set strItems to text items of theString
	set AppleScript's text item delimiters to replaceWith
	set newString to strItems as text
	set AppleScript's text item delimiters to oldDelims
	return newString

end replace

-- retrieve the plural/singular form of a quantity based on the given number
on quantifyNumber(theNumber, quantityName, pluralQuantityName)

	if theNumber is 1 then

		set theString to (theNumber as text) & space & quantityName

	else

		set theString to (theNumber as text) & space & pluralQuantityName

	end if

	return theString

end quantifyNumber

-- encodes JSON reserved characters in the given string
on encodeFeedbackChars(theString)

	set theString to replace("\\", "\\\\", theString)
	set theString to replace("\"", "\\\"", theString)
	return theString

end encodeFeedbackChars

-- decodes JSON reserved characters in the given string
on decodeFeedbackChars(theString)

	set theString to replace("\\\\", "\\", theString)
	set theString to replace("\\\"", "\"", theString)
	return theString

end decodeFeedbackChars

-- adds Alfred result to result list
on addResult(theResult)

	copy theResult to the end of resultList

end addResult

-- adds item for "No Results" message
on addNoResultsItem(query, queryType)

	addResult({uid:"no-results", valid:"no", title:"No Results Found", subtitle:("No " & queryType & "s matching '" & query & "'"), icon:defaultIconName})

end addNoResultsItem

on resultListIsFull()

	return (length of resultList is resultLimit)

end resultListIsFull

on resultListIsEmpty()

	return (length of resultList is 0)

end resultListIsFull

-- builds Alfred result item as JSON
on getResultFeedback(theResult)

	-- encode reserved JSON characters
	set resultUid to encodeFeedbackChars(uid of theResult)
	set resultValid to (valid of theResult) as text
	set resultTitle to encodeFeedbackChars(title of theResult)
	set resultSubtitle to encodeFeedbackChars(subtitle of theResult)

	if (icon of theResult) contains ":" then

		set resultIcon to encodeFeedbackChars(POSIX path of icon of theResult)

	else

		set resultIcon to icon of theResult

	end if

	set json to "{"
	set json to json & "\"uid\":\"" & resultUid & "\","
	set json to json & "\"arg\":\"" & resultUid & "\","
	set json to json & "\"valid\":\"" & resultValid & "\","
	set json to json & "\"title\":\"" & resultTitle & "\","
	set json to json & "\"subtitle\":\"" & resultSubtitle & "\","
	set json to json & "\"icon\":{\"path\":\"" & resultIcon & "\"}"
	set json to json & "}"
	return json

end getResultFeedback

-- retrieves JSON document for Alfred results
on getResultListFeedback()

	set json to "{\"items\": ["

	repeat with theResult in resultList

		set json to json & getResultFeedback(theResult)
		set json to json & ","

	end repeat

	-- remove trailing comma after last item
	set json to text 1 thru (length of json - 1) of json
	set json to json & "]}"
	return json

end getResultListFeedback

-- query path to artwork image file cached natively by Music.app in Catalina
on getSongArtworkPath(theSong)

	try

		if albumArtEnabled is false then return defaultIconName

		tell application "Music"

			-- get persistent ID of song and use it to fetch album artwork
			set songId to persistent ID of theSong
			-- the base path to the artwork file (without extension)
			set artworkPath to (do shell script "./resources/get-song-artwork-path.sh" & space & songId & space & defaultIconName)

		end tell

		return artworkPath

	on error errorMessage

		log errorMessage

	end try

end getSongArtworkPath

-- creates album artwork cache
on createWorkflowPlaylist()

	tell application "Music"

		if not (user playlist workflowPlaylistName exists) then

			make new user playlist with properties {name:workflowPlaylistName, shuffle:false}

		end if

	end tell

end createWorkflowPlaylist

on clearQueue()

	tell application "Music"

		if user playlist workflowPlaylistName exists then

			delete tracks of user playlist workflowPlaylistName

		end if

	end tell

end clearQueue

on queueSongs(theSongs)

	tell application "Music"

		repeat with theSong in theSongs

			duplicate theSong to user playlist workflowPlaylistName

		end repeat

	end tell

end queueSongs

on playQueue()

	tell application "Music"

		if number of tracks in user playlist workflowPlaylistName is not 0 then

			play user playlist workflowPlaylistName

		end if

	end tell

end playQueue

on getPlaylist(playlistId)

	tell application "Music"

		return (first playlist whose id is playlistId)

	end tell

end getPlaylist

on getPlaylistSongs(playlistId)

	tell application "Music"

		set thePlaylist to getPlaylist(playlistId) of me
		set playlistSongs to every track of thePlaylist

	end tell

	return playlistSongs

end getPlaylistSongs

-- retrieves list of songs within the given genre, sorted by artist
on getGenreSongs(genreName)

	tell application "Music"

		return every track of playlist 2 whose genre is genreName

	end tell

end getGenreSongs

-- retrieves list of album names for the given artist
on getArtistAlbums(artistName)

	tell application "Music"

		set artistSongs to every track of playlist 2 whose artist is artistName
		set albumNames to {}

		repeat with theSong in artistSongs

			if (album of theSong) is not in albumNames then

				set albumNames to albumNames & (album of theSong)

			end if

		end repeat

	end tell

	return albumNames

end getArtistAlbums

-- retrieves list of songs by the given artist, sorted by album
on getArtistSongs(artistName)

	tell application "Music"

		set albumNames to getArtistAlbums(artistName) of me
		set artistSongs to {}

		repeat with albumName in albumNames

			set albumSongs to (every track of playlist 2 whose artist is artistName and album is albumName)
			set artistSongs to artistSongs & albumSongs

		end repeat

	end tell

	return artistSongs

end getArtistSongs

-- retrieves list of songs in the given album
on getAlbumSongs(albumName)

	tell application "Music"

		set albumSongs to every track of playlist 2 whose album is albumName

	end tell

	return albumSongs

end getAlbumSongs

-- retrieves the song with the given ID
on getSong(songId)

	tell application "Music"

		set theSong to first track of playlist 2 whose database ID is songId

	end tell

	return theSong

end getSong

-- retrieves a list of objects or names matching the given query and type
on getResultsFromQuery(query, queryType)

	set evalScript to run script "
	script

		on findResults(query, queryType, resultLimit)

			tell application \"Music\"

				set theSongs to (get every track in playlist 2 whose " & queryType & " starts with query)

				if length of theSongs < resultLimit then

					set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains (space & query) and " & queryType & " does not start with query)

				end if

				if length of theSongs < resultLimit then

					set theSongs to theSongs & (get every track in playlist 2 whose " & queryType & " contains query and " & queryType & " does not start with query and " & queryType & " does not contain (space & query))

				end if

				if length of theSongs is 0 then

					if queryType is \"name\" then

						set theSongs to theSongs & (search playlist 2 for query only songs)

					else if queryType is not \"genre\" then

						set theSongs to theSongs & (search playlist 2 for query only " & queryType & "s)

					end if

				end if

				if queryType is \"name\" then

					if length of theSongs > resultLimit then

						set theSongs to items 1 thru resultLimit of theSongs

					end if

					set theResults to theSongs

				else

					set theResults to {}

					repeat with theSong in theSongs

						if length of theResults is resultLimit then exit repeat

						set theResult to " & queryType & " of theSong

						if theResult is not in theResults then

							set theResults to theResults & theResult

						end if

					end repeat

				end if

			end tell

			return theResults

		end findResults

	end script
	"

	evalScript's findResults(query, queryType, resultLimit)

end getResultsFromQuery

-- returns the given string with leading and trailing whitespace removed
on trimWhitespace(theString)

	-- trim leading whitespace
	repeat while theString begins with space

		if length of theString is 1 then return ""
		set theString to text 2 thru end of theString

	end repeat

	-- trim trailing whitespace
	repeat while theString ends with space

		set theString to text 1 thru ((length of theString) - 1) of theString

	end repeat

	return theString

end trimWhitespace

-- queues the song with the given ID
on queueSong(songId)

	set theSong to getSong(songId)
	queueSongs({theSong})

end queueSong

-- queues all songs belonging to the given album
on queueAlbum(albumName)

	set albumName to decodeFeedbackChars(albumName)
	set albumSongs to getAlbumSongs(albumName)
	queueSongs(albumSongs)

end queueAlbum

-- queues all songs by the given artist
on queueArtist(artistName)

	set artistName to decodeFeedbackChars(artistName)
	set artistSongs to getArtistSongs(artistName)
	queueSongs(artistSongs)

end queueArtist

-- queues all songs within the given genre
on queueGenre(genreName)

	set genreName to decodeFeedbackChars(genreName)
	set genreSongs to getGenreSongs(genreName)
	queueSongs(genreSongs)

end queueGenre

-- queues all songs in the given playlist
on queuePlaylist(playlistId)

	set playlistSongs to getPlaylistSongs(playlistId)
	queueSongs(playlistSongs)

end queuePlaylist

-- parses the given result query to retrieve type and id of item to queue
on parseResultQuery(query)

	set pos to offset of "-" in query
	set theType to text 1 thru (pos - 1) of query
	set theId to text (pos + 1) thru end of query
	return {type:theType, id:theId}

end parseResultQuery

on queue(query)

	set typeAndId to parseResultQuery(query)
	set theType to type of typeAndId
	set theId to id of typeAndId

	createWorkflowPlaylist()

	if theType is "song" then
		queueSong(theId)
	else if theType is "album" then
		queueAlbum(theId)
	else if theType is "artist" then
		queueArtist(theId)
	else if theType is "genre" then
		queueGenre(theId)
	else if theType is "playlist" then
		queuePlaylist(theId)
	else
		log "Unsupported type: " & theType
	end if

end queue

on play(query)

	clearQueue()
	queue(query)
	playQueue()

end play


Reduce nesting in sortSongsByAlbumOrder()


final version of convert script

final version of convert script

on run argv
	set MagicFormatPDF to 999
	set appName to "Microsoft Excel"
	try
		-- get a posix file object to avoid grant access issue with 'Microsoft Office 2016',  not the same as (file documentPath) when using the 'open  ...' command
		set tFile to (POSIX path of (item 1 of argv)) as POSIX file
		set PDFFile to (POSIX path of (item 2 of argv)) as POSIX file
		--tell application "Finder"
		if fileExists(PDFFile) then
			tell application "Finder"
			delete file PDFFile
			end tell
		end if
		--end tell
		tell application "Microsoft Excel"
			set isRun to running
			activate
			open tFile
			tell active workbook
				alias PDFFile -- This is necessary to any script for 'Microsoft Office 2016', this avoid errors with any "save ... " command
				set wkbk1 to active workbook
				save as active sheet filename PDFFile file format PDF file format with overwrite
				close saving no
			end tell
		end tell
		return 2
	on error errMsg number errorNumber
		log ("ERROR: ")
		log (errMsg)
		tell application appName to quit
		return -6
	end try
end run
on fileExists(theFile) -- (String) as Boolean
	tell application "System Events"
		if exists file (theFile as text) then
			return true
		else
			return false
		end if
	end tell
end fileExists

# See http://msdn.microsoft.com/en-us/library/bb243311%28v=office.12%29.aspx
set WdExportFormatPDF to 17
set MagicFormatPDF to 999
set appName to "Microsoft Excel"

on fun argv
	try
		tell application appName
			open (quoted form of (item 1 of argv))

			if formatEnumeration = MagicFormatPDF then
				save workbook as workbook (active workbook) filename (quoted form of (item 2 of argv)) file format (PDF file format) with overwrite
			else
			    save workbook as workbook (active workbook) filename (quoted form of (item 2 of argv)) file format ((item 3 of argv) file format) with overwrite
			end if

			close (active workbook) saving no

			return 2
		end tell
	on error errMsg number errorNumber
		return -6
	end try
end run


Update arrange windows.

Update arrange windows.

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
lmnnoo1Password 7mpq
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/0Calendar
o010narrow_center_position
o120narrow_center_size
l7B
I7B0resize_app_window
m89CARROTweather
o9:0narrow_center_position
J:>
m:;"
m;<
lCM
ICM0resize_app_window
mDGFantastical
oGH0narrow_center_position
oHI0narrow_center_size
lNX
INX0resize_app_window
mORGoogle Chrome
oRS0narrow_center_position
oST0narrow_center_size
lYc
IYc0resize_app_window
mZ]Mail
o]^0narrow_center_position
o^_0narrow_center_size
ldx
Idx0resize_app_window
mehMessages
Jhn
mhk
mkl$~
Jnt
mnq}}|
mqr{{|~
lyzy
Iyxwx0resize_app_window
mz}
Music
o}~vv0narrow_center_positionu
o~tt0narrow_center_sizeuwzy
lsr
Iqpq0resize_app_window
mNews
ooo0narrow_center_positionn
omm0narrow_center_sizenpsr
llk
Ijij0resize_app_window
m
Notes
ohh0narrow_center_positiong
off0narrow_center_sizegilk
led
Icbc0resize_app_window
mNotion
oaa0narrow_center_position`
o__0narrow_center_size`bed
l^]
I\[\0resize_app_window
mPhotos
oZZ0narrow_center_positionY
oXX0narrow_center_sizeY[^]
lWV
IUTU0resize_app_window
m

Preview
oSS0narrow_center_position
R

oQQ0narrow_center_sizeRTWV
lPO
INMN0resize_app_window
mRadarScope
oLL0narrow_center_positionK
oJJ0narrow_center_sizeKMPO
lIH
IGFG0resize_app_window
m  Safari!"
!oEE0narrow_center_position"#D
#oCC0narrow_center_sizeDFIH$%
$l&BA
&I@'?@0resize_app_window'()
(m**++Siftie),-
,o>>0narrow_center_position-.=
.o<<0narrow_center_size=?BA%/0
/l1;:
1I92890resize_app_window234
3m5566
Slack478
7o770narrow_center_position896
9J::;<
;m55"<=4
=m33468;:0>?
>l@21
@I0A/00resize_app_windowABC
BmDDEETextEditCFG
FJHHIJ
Im..JK-
Km,,]-GL+
LJMMNO
Nm**ROP)
Pm((4)+/21?QR
QlS'&
SI%T$%0resize_app_windowTUV
UmWWXXTweetbotVYZ
YJ
[[\]
\m
##]^"
^m
!!$"Z_
_J
``ab
am
bc
cm $'&Rd
dl%e
eI%f0resize_app_windowfgh
gmiijjzoom.ushkl
ko0narrow_center_positionlm
mJ!nnop
om"pq
qmrstr0resize_app_window
.aevtoappnull****s
uv0resize_app_windowww

0app_name	0win_position0win_size
u0app_name0win_position0win_sizev=

capp

prun

prcs

cobj

cwin

posn

ptsz>*/,e3+*/#k/l/lv*-,FOk/l/lv*-,FUUYhtxyz
.aevtoappnull****
xk%{{@||I}}T~~]hs~$/>Qdyz&ny	*5DWi$0narrow_center_position"m0narrow_center_size0wide_center_position0wide_center_size0resize_app_window]R4&lvEOlvEOlvEOlvEO*m+O*m+O*m+O*lvm+O*am+O*am+O*am+O*aalvalvm+O*am+O*am+O*am+O*am+O*am+O*am+O*am+O*am+O*am+O*alvm+O*a aa!lva"a#lvm+O*a$alvalvm+O*a%lvm+ascr
ޭ

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
lmnnoo1Password 7mpq
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/0Calendar
o010narrow_center_position
o120narrow_center_size
l7B
I7B0resize_app_window
m89CARROTweather
o9:0narrow_center_position
J:>
m:;"
m;<
lCM
ICM0resize_app_window
mDGFantastical
oGH0narrow_center_position
oHI0narrow_center_size
lNX
INX0resize_app_window
mORGoogle Chrome
oRS0narrow_center_position
oST0narrow_center_size
lYc
IYc0resize_app_window
mZ]Linear
o]^0narrow_center_position
o^_0narrow_center_size
ldn
Idn0resize_app_window
mehMail
ohi0narrow_center_position
oij0narrow_center_size
lo~}
Io|{|0resize_app_window
mpsMessages
Jsy
msvzzy
mvwxx$yw
Jy
my|vvu
m|}ttuw{~}
lsr
Iqpq0resize_app_window
mMicrosoft Teams
ooo0narrow_center_positionn
J
mmm"l
mkklnpsr
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
oVV0narrow_center_sizeWY\[
l	UT
	IS
RS0resize_app_window

m

Notion
oQQ0narrow_center_positionP
oOO0narrow_center_sizePRUT
lNM
ILKL0resize_app_window
mObsidian
oJJ0narrow_center_positionI
oHH0narrow_center_sizeIKNM
lGF
IE DE0resize_app_window !"
!m##$$Photos"%&
%oCC0narrow_center_position&'B
'oAA0narrow_center_sizeBDGF()
(l*@?
*I>+=>0resize_app_window+,-
,m..//Pixelmator Pro-01
0o<<0narrow_center_position12;
2o::0narrow_center_size;=@?)34
3l598
5I76670resize_app_window678
7m99::Preview8;<
;o550narrow_center_position<=4
=o330narrow_center_size46984>?
>l@21
@I0A/00resize_app_windowABC
BmDDEERadarScopeCFG
Fo..0narrow_center_positionGH-
Ho,,0narrow_center_size-/21?IJ
IlK+*
KI)L()0resize_app_windowLMN
MmOOPPSafariNQR
Qo''0narrow_center_positionRS&
So%%0narrow_center_size&(+*JTU
Tl
V$#
VI
"W!"0resize_app_windowWXY
XmZZ[[SiftieY\]
\o  0narrow_center_position]^
^o0narrow_center_size!$#U_`
_la
aIb0resize_app_windowbcd
cmeeff
Slackdgh
go0narrow_center_positionhi
iJjjkl
km"lm
mm`no
nl#p
pI#q0resize_app_windowqrs
rmttuuSpotifysvw
vo0narrow_center_positionwx
xo0narrow_center_sizeoyz
yl$<{

{I$<|
0resize_app_window|}~
}m%(TextEdit~
J(0
m(+
m+.]
J08
m03R
m364

z
l=Q
I=Q0resize_app_window
m>ATweetbot
JAG
mAD
mDE$
JGM
mGJ
mJK
lR_
IR_0resize_app_window
mSVzoom.us
oVW0narrow_center_position
JW[
mWX"
mXY
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~(3>IT_ny+ny
#.9DOZet$0narrow_center_position"m0narrow_center_size0wide_center_position0wide_center_size0resize_app_window]R4`lvEOlvEOlvEOlvEO*m+O*m+O*m+O*lvm+O*am+O*am+O*am+O*am+O*aalvalvm+O*alvm+O*am+O*am+O*am+O*am+O*am+O*am+O*am+O*am+O*a m+O*a!m+O*a"m+O*a#lvm+O*a$m+O*a%aa&lva'a(lvm+O*a)alvalvm+O*a*lvm+$"m$mascr
ޭ


Run mac script

Run mac script

FasdUAS 1.101.10
k
lIC ==================================================================		 ==================================================================

l
	 PROGRESS
 PROGRESS
lIC ================================================================== ==================================================================
l
l
r
mQuit All
1

ppgd
l
r !
 m
!1

ppgt"#
"j$0
progresssteps
progressSteps
$m#%&
%i'(
'I) 0updateprogressupdateProgress)*
*1

dscr
(k#++,-
,I.
.sysodelanullnmbr
.m-/0
/r12
11

dscr
21

ppga034
3r56
5[78
7o0
progresssteps
progressSteps
8m
6o0
progresssteps
progressSteps49
9r#:;
:o0
progresssteps
progressSteps
;1"

ppgc&<=
<l=>?
>l?@A
@lBCBIC ==================================================================CDD ==================================================================AEF
ElGHG QUITHII
 QUITFJK
JlLMLIC ==================================================================MNN ==================================================================KOP
OlPQR
QlS
SIT 0updateprogressupdateProgressTU
Um
VVWW6Quitting apps and processesRXY
XlYZ[
Zl\]\! Close running applications]^^6 Close running applications[_`
_la
aObc
brde
dm
boovtrue
elf
fngh
g1

pvis
h2

prcs
cmiisevsalisMacintosh HD{H+ZKSystem Events.app]u	 CoreServices
ZKZJZI=Macintosh HD:System:Library:CoreServices:System Events.app$System Events.appMacintosh HD-System/Library/CoreServices/System Events.app/`jk
jl &l
lr &mn
mJ $oopq
pm !rrssFinderqt
tm!"uuvvquit-all-script
no0
white_listkwx
wl'y
yQ'z{|
zk*}}}~
~O*?
r.>
6.<
l.3
n.3
113

pnam
2.1

prcs
=4;
157

pvis
m8:
boovtrue
o0process_list
m*+MACSalistMacintosh HD{H+ZK
Finder.app])	 CoreServices
ZKZJZI6Macintosh HD:System:Library:CoreServices:Finder.app
Finder.appMacintosh HD&System/Library/CoreServices/Finder.app/
Y@}
kQx
rQY
nQU
4RU

cobj
oST0i
lQR
oQR0process_list
o0this_process
ZZx
HZ`
EZ_
oZ[0
white_list
o[^0this_process
Oct
Ins
.aevtquitnullnull
4ck

capp
ogj0this_process0i
mCD
lDL
nDL
mGK

nmbr
nDG
2EG

cobj
oDE0process_list
{R
.ascrerr ********
|I
.sysodlogaskrTEXT
l
mBError: An app couldn't be closed!

btns
J
mOk

disp
m
sticx
l
l Kill running processes. Kill running processes
l
r
J
mnode
mphantomjs
o
0	processes
l
X
I
.sysoexecTEXTTEXT
b
b
mkillall
o0process
m || true0process
o
0	processes
l
l
l~~IC ================================================================== ==================================================================
l}} EJECT EJECT
l||IC ================================================================== ==================================================================
l{zy{zy
lxw
Ivuv 0updateprogressupdateProgresst
m Ejecting devicestuxw
lsrqsrq
lpp Eject plugged-in devices2 Eject plugged-in devices
l
on
Q

O
Iml
m.fndrejctnullobj
lkj
2i
i
cdiskjl
mMACSalistMacintosh HD{H+ZK
Finder.app])	 CoreServices
ZKZJZI6Macintosh HD:System:Library:CoreServices:Finder.app
Finder.appMacintosh HD&System/Library/CoreServices/Finder.app/
Rhgf
h.ascrerr ********gf
I
e
e.sysodlogaskrTEXT
ldc
mHError: A device couldn't be ejected!dcb
b
btns
J

a
m

Oka	`_
`
disp
m^
^stic_on
l]\[]\[
lZYXZYX
lWWIC ================================================================== ==================================================================
lVV CLEAN CLEAN
lU UIC ================================================================== !! =================================================================="#
"lTSRTSR#$%
$l&QP
&IO'NO 0updateprogressupdateProgress'(M
(m))**(Cleaning directoriesMNQP%+,
+lLKJLKJ,-.
-lI/0I/ Empty trash011 Empty trash.23
2l"4HG
4O"56
5I!F7E
F.fndremptnullobj
7l8DC
81B
B
trshDCE
6m99MACSalistMacintosh HD{H+ZK
Finder.app])	 CoreServices
ZKZJZI6Macintosh HD:System:Library:CoreServices:Finder.app
Finder.appMacintosh HD&System/Library/CoreServices/Finder.app/HG3:;
:lA@?A@?;<=
<l>>?>>*$ Delete contents of Downloads folder?@@H Delete contents of Downloads folder=AB
Al#*C=<
CI#*;D:
;.sysoexecTEXTTEXT
Dm#&EEFF(rm -rf ~/Downloads/*:=<BGH
Gl987987HIJ
Il6KL6K,& Delete all extra node_modules foldersLMML Delete all extra node_modules foldersJN5
Nl+2O43
OI+22P1
2.sysoexecTEXTTEXT
Pm+.QQRRfind ~/'Google Drive' -name 'node_modules' -type d -exec rm -r '{}' ';' || true14350S/TUVWXY.-,+*0S)('&%$#"! )0
progresssteps
progressSteps( 0updateprogressupdateProgress
'.aevtoappnull****&0
white_list%0process_list$0this_process#
0	processes"! /!T(Z[ 0updateprogressupdateProgress\\

dscrZ

dscr[
.sysodelanullnmbr

ppga

ppgc$kjO*,FObkEcOb*,FU]^_
.aevtoappnull****
]k2``aabbQcc_ddjeewffgghhiijj$kk2llAmmN^
0i
0process_/V
i	run)EQ

ppgd

ppgt
 0updateprogressupdateProgress

prcs

pvis0
white_list

pnamn0process_list

cobj

nmbr0this_process

capp
.aevtquitnullnull

btns

disp
stic
.sysodlogaskrTEXT
0	processes

kocl
.corecnte********
.sysoexecTEXTTEXT

cdis
.fndrejctnullobj

trsh
.fndremptnullobj 3*,FOm*,FO*k+O	e*-,FUOlvEOX*-,[,\Ze81EUO<k-a,Ekh/E`O_*a_/*jUYh[OYWXaaakvaaaOaalvE`O%_[a l!kha"%a#%j$[OYO*a%k+O*a&-j'UWXa(aa)kvaaaO*a*k+O*a+,j,UOa-j$Oa.j$VooruWp
p
qrstuvwxyXqzzFinderr{{Google Chromes||Spotifyt}}Todoistu~~iTerm2vCalendarwMessagesxMailyDashXquit-all-scriptY.-,+*ascrޭ

FasdUAS 1.101.10
k
lIC ==================================================================		 ==================================================================

l
	 PROGRESS
 PROGRESS
lIC ================================================================== ==================================================================
l
l
r
mQuit All
1

ppgd
l
r !
 m
!1

ppgt"#
"j$0
progresssteps
progressSteps
$m#%&
%i'(
'I) 0updateprogressupdateProgress)*
*1

dscr
(k#++,-
,I.
.sysodelanullnmbr
.m-/0
/r12
11

dscr
21

ppga034
3r56
5[78
7o0
progresssteps
progressSteps
8m
6o0
progresssteps
progressSteps49
9r#:;
:o0
progresssteps
progressSteps
;1"

ppgc&<=
<l=>?
>l?@A
@lBCBIC ==================================================================CDD ==================================================================AEF
ElGHG QUITHII
 QUITFJK
JlLMLIC ==================================================================MNN ==================================================================KOP
OlPQR
QlS
SIT 0updateprogressupdateProgressTU
Um
VVWW6Quitting apps and processesRXY
XlYZ[
Zl\]\! Close running applications]^^6 Close running applications[_`
_la
aObc
brde
dm
boovtrue
elf
fngh
g1

pvis
h2

prcs
cmiisevsalisMacintosh HD{H+ZKSystem Events.app]u	 CoreServices
ZKZJZI=Macintosh HD:System:Library:CoreServices:System Events.app$System Events.appMacintosh HD-System/Library/CoreServices/System Events.app/`jk
jl &l
lr &mn
mJ $oopq
pm !rrssFinderqt
tm!"uuvvquit-all-script
no0
white_listkwx
wl'y
yQ'z{|
zk*}}}~
~O*?
r.>
6.<
l.3
n.3
113

pnam
2.1

prcs
=4;
157

pvis
m8:
boovtrue
o0process_list
m*+MACSalistMacintosh HD{H+ZK
Finder.app])	 CoreServices
ZKZJZI6Macintosh HD:System:Library:CoreServices:Finder.app
Finder.appMacintosh HD&System/Library/CoreServices/Finder.app/
Y@}
kQx
rQY
nQU
4RU

cobj
oST0i
lQR
oQR0process_list
o0this_process
ZZx
HZ`
EZ_
oZ[0
white_list
o[^0this_process
Oct
Ins
.aevtquitnullnull
4ck

capp
ogj0this_process0i
mCD
lDL
nDL
mGK

nmbr
nDG
2EG

cobj
oDE0process_list
{R
.ascrerr ********
|I
.sysodlogaskrTEXT
l
mBError: An app couldn't be closed!

btns
J
mOk

disp
m
sticx
l
l Kill running processes. Kill running processes
l
r
J
mnode
mphantomjs
o
0	processes
l
X
I
.sysoexecTEXTTEXT
b
b
mkillall
o0process
m || true0process
o
0	processes
l
l
l~~IC ================================================================== ==================================================================
l}} EJECT EJECT
l||IC ================================================================== ==================================================================
l{zy{zy
lxw
Ivuv 0updateprogressupdateProgresst
m Ejecting devicestuxw
lsrqsrq
lpp Eject plugged-in devices2 Eject plugged-in devices
l
on
Q

O
Iml
m.fndrejctnullobj
lkj
2i
i
cdiskjl
mMACSalistMacintosh HD{H+ZK
Finder.app])	 CoreServices
ZKZJZI6Macintosh HD:System:Library:CoreServices:Finder.app
Finder.appMacintosh HD&System/Library/CoreServices/Finder.app/
Rhgf
h.ascrerr ********gf
I
e
e.sysodlogaskrTEXT
ldc
mHError: A device couldn't be ejected!dcb
b
btns
J

a
m

Oka	`_
`
disp
m^
^stic_on
l]\[]\[
lZYXZYX
lWWIC ================================================================== ==================================================================
lVV CLEAN CLEAN
lU UIC ================================================================== !! =================================================================="#
"lTSRTSR#$%
$l&QP
&IO'NO 0updateprogressupdateProgress'(M
(m))**(Cleaning directoriesMNQP%+,
+lLKJLKJ,-.
-lI/0I/ Empty trash011 Empty trash.23
2l"4HG
4O"56
5I!F7E
F.fndremptnullobj
7l8DC
81B
B
trshDCE
6m99MACSalistMacintosh HD{H+ZK
Finder.app])	 CoreServices
ZKZJZI6Macintosh HD:System:Library:CoreServices:Finder.app
Finder.appMacintosh HD&System/Library/CoreServices/Finder.app/HG3:;
:lA@?A@?;<=
<l>>?>>*$ Delete contents of Downloads folder?@@H Delete contents of Downloads folder=AB
Al#*C=<
CI#*;D:
;.sysoexecTEXTTEXT
Dm#&EEFF(rm -rf ~/Downloads/*:=<BGH
Gl987987HIJ
Il6KL6K,& Delete all extra node_modules foldersLMML Delete all extra node_modules foldersJN5
Nl+2O43
OI+22P1
2.sysoexecTEXTTEXT
Pm+.QQRRfind ~/'Google Drive' -name 'node_modules' -type d -exec rm -r '{}' ';' || true14350S/TUVWXY.-,+*0S)('&%$#"! )0
progresssteps
progressSteps( 0updateprogressupdateProgress
'.aevtoappnull****&0
white_list%0process_list$0this_process#
0	processes"! /T(Z[ 0updateprogressupdateProgress\\

dscrZ

dscr[
.sysodelanullnmbr

ppga

ppgc$kjO*,FObkEcOb*,FU]^_
.aevtoappnull****
]k2``aabbQcc_ddjeewffgghhiijj$kk2llAmmN^
0i
0process_/V
i	run)EQ

ppgd

ppgt
 0updateprogressupdateProgress

prcs

pvis0
white_list

pnamn0process_list

cobj

nmbr0this_process

capp
.aevtquitnullnull

btns

disp
stic
.sysodlogaskrTEXT
0	processes

kocl
.corecnte********
.sysoexecTEXTTEXT

cdis
.fndrejctnullobj

trsh
.fndremptnullobj 3*,FOm*,FO*k+O	e*-,FUOlvEOX*-,[,\Ze81EUO<k-a,Ekh/E`O_*a_/*jUYh[OYWXaaakvaaaOaalvE`O%_[a l!kha"%a#%j$[OYO*a%k+O*a&-j'UWXa(aa)kvaaaO*a*k+O*a+,j,UOa-j$Oa.j$VooruWp	p	qrstuvwxXqyyFinderrzzSpotifys{{Todoistt||iTerm2u}}Calendarv~~MessageswMailxDashXquit-all-scriptY.-,+*ascr
ޭ


Go to Document

Go to Document

use scripting additions
use framework "Foundation"
property NSString : a reference to current application's NSString

-- Helper

on myRemoveLastPath(myPath)
set myString to NSString's stringWithString:myPath
set removedLastPathString to myString's stringByDeletingLastPathComponent
removedLastPathString as text
end myRemoveLastPath

on myFolderExists(myFolder) -- (String) as Boolean
tell application "System Events"
if exists folder myFolder then
return true
else
return false
end if
end tell
end myFolderExists

on myGetRemote(myText)
set myString to NSString's stringWithString:myText
set myParts to myString's componentsSeparatedByString:"\t"
set myFirstParts to item 1 of myParts
myFirstParts as text
end myGetRemote

-- Path

on myHomePath()
tell application "System Events"
"/Users/" & (name of current user)
end tell
end myHomePath

on myLibraryPath()
myHomePath() & "/Library"
end myLibraryPath

on myXcodePath()
myLibraryPath() & "/Developer/Xcode"
end myXcodePath

on myUserDataPath()
myXcodePath() & "/UserData"
end myUserDataPath

on myProjectPath()
tell application "Xcode"
tell active workspace document
set myPath to path
end tell
end tell
myRemoveLastPath(myPath)
end myProjectPath

-- Generic Open

on myOpenFolder(myPath)
tell application "Finder"
activate
open myPath as POSIX file
end tell
end myOpenFolder

on myOpeniTerm(myPath)
tell application "Finder"
do shell script "open -a iTerm " & quoted form of myPath
end tell
end myOpeniTerm

-- Open

on myOpenThemesFolder()
set myPath to myUserDataPath() & "/FontAndColorThemes/"
myOpenFolder(myPath)
end myOpenThemesFolder

on myOpenCodeSnippetsFolder()
set myPath to myUserDataPath() & "/CodeSnippets/"
myOpenFolder(myPath)
end myOpenCodeSnippetsFolder

on myOpenDeviceSupportFolder()
set myPath to "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport"
myOpenFolder(myPath)
end myOpenDeviceSupportFolder

on myOpenArchivesFolder()
set myPath to myXcodePath() & "/Archives/"
myOpenFolder(myPath)
end myOpenArchivesFolder

on myOpenProvisioningProfileFolder()
set myPath to myLibraryPath() & "/MobileDevice/Provisioning Profiles"
myOpenFolder(myPath)
end myOpenProvisioningProfileFolder

on myOpenProjectFolder()
set myPath to myProjectPath()
myOpenFolder(myPath)
end myOpenProjectFolder

on myOpeniTermForCurrentProject()
set myPath to myProjectPath()
myOpeniTerm(myPath)
end myOpeniTermForCurrentProject

on myOpenDerivedDataFolder()
set myRelativePath to myProjectPath() & "/DerivedData/"
if myFolderExists(myRelativePath) then
myOpenFolder(myRelativePath)
else
myOpenFolder(myXcodePath() & "/DerivedData/")
end if
end myOpenDerivedDataFolder

on myOpenGitHub()
set myPath to myProjectPath()
set myConsoleOutput to (do shell script "cd " & quoted form of myPath & "; git remote -v")
set myRemote to myGetRemote(myConsoleOutput)
set myUrl to (do shell script "cd " & quoted form of myPath & "; git config --get remote." & quoted form of myRemote & ".url")
open location myUrl
end myOpenGitHub

on myOpenDocument()
set command1 to "cd ~/Library/Developer/CoreSimulator/Devices/;"
set command2 to "cd `ls -t | head -n 1`/data/Containers/Data/Application;"
set command3 to "cd `ls -t | head -n 1`/Documents;"
set command4 to "open ."
do shell script command1 & command2 & command3 & command4
end myOpenDocument

on myOpenAbout()
open location "https://github.com/onmyway133/XcodeWay"
end myOpenAbout

use scripting additions
use framework "Foundation"
property NSString : a reference to current application's NSString

-- Helper

on myRemoveLastPath(myPath)
set myString to NSString's stringWithString:myPath
set removedLastPathString to myString's stringByDeletingLastPathComponent
removedLastPathString as text
end myRemoveLastPath

on myFolderExists(myFolder) -- (String) as Boolean
tell application "System Events"
if exists folder myFolder then
return true
else
return false
end if
end tell
end myFolderExists

on myGetRemote(myText)
set myString to NSString's stringWithString:myText
set myParts to myString's componentsSeparatedByString:"\t"
set myFirstParts to item 1 of myParts
myFirstParts as text
end myGetRemote

-- Path

on myHomePath()
tell application "System Events"
"/Users/" & (name of current user)
end tell
end myHomePath

on myLibraryPath()
myHomePath() & "/Library"
end myLibraryPath

on myXcodePath()
myLibraryPath() & "/Developer/Xcode"
end myXcodePath

on myUserDataPath()
myXcodePath() & "/UserData"
end myUserDataPath

on myProjectPath()
tell application "Xcode"
tell active workspace document
set myPath to path
end tell
end tell
myRemoveLastPath(myPath)
end myProjectPath

-- Generic Open

on myOpenFolder(myPath)
tell application "Finder"
activate
open myPath as POSIX file
end tell
end myOpenFolder

on myOpeniTerm(myPath)
tell application "Finder"
do shell script "open -a iTerm " & quoted form of myPath
end tell
end myOpeniTerm

-- Open

on myOpenThemesFolder()
set myPath to myUserDataPath() & "/FontAndColorThemes/"
myOpenFolder(myPath)
end myOpenThemesFolder

on myOpenCodeSnippetsFolder()
set myPath to myUserDataPath() & "/CodeSnippets/"
myOpenFolder(myPath)
end myOpenCodeSnippetsFolder

on myOpenDeviceSupportFolder()
set myPath to "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport"
myOpenFolder(myPath)
end myOpenDeviceSupportFolder

on myOpenArchivesFolder()
set myPath to myXcodePath() & "/Archives/"
myOpenFolder(myPath)
end myOpenArchivesFolder

on myOpenProvisioningProfileFolder()
set myPath to myLibraryPath() & "/MobileDevice/Provisioning Profiles"
myOpenFolder(myPath)
end myOpenProvisioningProfileFolder

on myOpenProjectFolder()
set myPath to myProjectPath()
myOpenFolder(myPath)
end myOpenProjectFolder

on myOpeniTermForCurrentProject()
set myPath to myProjectPath()
myOpeniTerm(myPath)
end myOpeniTermForCurrentProject

on myOpenDerivedDataFolder()
set myRelativePath to myProjectPath() & "/DerivedData/"
if myFolderExists(myRelativePath) then
myOpenFolder(myRelativePath)
else
myOpenFolder(myXcodePath() & "/DerivedData/")
end if
end myOpenDerivedDataFolder

on myOpenGitHub()
set myPath to myProjectPath()
set myConsoleOutput to (do shell script "cd " & quoted form of myPath & "; git remote -v")
set myRemote to myGetRemote(myConsoleOutput)
set myUrl to (do shell script "cd " & quoted form of myPath & "; git config --get remote." & quoted form of myRemote & ".url")
open location myUrl
end myOpenGitHub

on myOpenAbout()
open location "https://github.com/onmyway133/XcodeWay"
end myOpenAbout


Update with fixes for Yosemite & Shellshock test

Cleaned up OS version detection to use "as number" for clarity and accuracy.

Specified a single "OK" button on dialogs that didn't need a cancel button.

Added Yosemite SWUpdate URL.

Added a "target file" variable in the reset functions to gracefully handle using either the ".bashrc" or ".profile" as needed by the OS version.

Restored the missing "current user" text insert in the resetThisUserCPU() function. This was causing it not to actually specify the user account to delete, so it wasn't deleting anything.

Added testing for several Shellshock vulnerabilities, although currently it does nothing to resolve.

Added Yosemite-specific command to  FlushDNSCache()

-- 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

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 "mhq-swupdate.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 "mhq-swupdate.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

--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", "Install Tech User Reset Script", "Test for Flashback Trojan", "Test for ShellShock vulnerability", "Rebuild Launch Services DB", "Flush DNS Cache", "Reinstall default 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 "Install Tech User Reset Script" then
		installTechResetScript()
	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 "Reinstall default 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 > 7) 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 10.8 we need to supply password
	try
		if (osVersion as number > 7) then
			do shell script theSetScript with administrator privileges
		else
			do shell script theSetScript
		end if
	end try
end setSWUpdateServer

on installResetScript()
	try
		set TheFile to ((path to me as string) & "Contents:Resources:mhqreset.sh") as alias
		tell application "Finder"
			duplicate TheFile to the startup disk with replacing
		end tell
	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 installTechResetScript()
	set TheFile to ((path to me as string) & "Contents:Resources:techreset.sh") as alias
	tell application "Finder"
		duplicate TheFile to the startup disk with replacing
	end tell

end installTechResetScript

on InstallSWUpdatePlist()

	set TheFile to ((path to me as string) & "Contents:Resources: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()
	set TheFile to ((path to me as string) & "Contents:Resources:com.fakeapp.Fake.plist") as alias
	tell application "Finder"
		duplicate TheFile to ((path to preferences folder) as alias) with replacing
	end tell
	set theSetScript to "
#!/bin/bash

defaults delete com.fakeapp.Fake \"FUWindowFrameString\"
defaults delete com.fakeapp.Fake \"NSWindow Frame ActionLibrary\"
defaults delete com.fakeapp.Fake \"NSWindow Frame FUWindow\"
defaults delete com.fakeapp.Fake \"NSWindow Frame Preferences\"
defaults delete com.fakeapp.Fake \"WebDatabaseDirectory\"
defaults write com.fakeapp.Fake \"FakeDelayBetweenRunningActions\" '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 ((path to me as string) & "Contents:Resources: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

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 "mhq-swupdate.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 "mhq-swupdate.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

--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", "Install Tech User Reset Script", "Test for Flashback Trojan", "Test for ShellShock vulnerability", "Rebuild Launch Services DB", "Flush DNS Cache", "Reinstall default 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 "Install Tech User Reset Script" then
		installTechResetScript()
	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 "Reinstall default 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 > 7) 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 10.8 we need to supply password
	try
		if (osVersion as number > 7) then
			do shell script theSetScript with administrator privileges
		else
			do shell script theSetScript
		end if
	end try
end setSWUpdateServer

on installResetScript()
	try
		set TheFile to ((path to me as string) & "Contents:Resources:mhqreset.sh") as alias
		tell application "Finder"
			duplicate TheFile to the startup disk with replacing
		end tell
	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
			do shell script "echo \"sh /mhqreset.sh\" >> /private/var/root/.bashrc" with administrator privileges
		else
			do shell script "echo \"sh /mhqreset.sh\" >> /private/var/root/.profile" with administrator privileges
		end if
		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
			do shell script "echo \"sh /mhqreset.sh\" >> /private/var/root/.bashrc" with administrator privileges
		else
			do shell script "echo \"sh /mhqreset.sh\" >> /private/var/root/.profile" with administrator privileges
		end if
		do shell script "nvram boot-args=\"-s\"" with administrator privileges
		tell application "Finder" to restart
		return -128
	end try
end resetThisUserCPU

on installTechResetScript()
	set TheFile to ((path to me as string) & "Contents:Resources:techreset.sh") as alias
	tell application "Finder"
		duplicate TheFile to the startup disk with replacing
	end tell

end installTechResetScript

on InstallSWUpdatePlist()

	set TheFile to ((path to me as string) & "Contents:Resources: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()
	set TheFile to ((path to me as string) & "Contents:Resources:com.fakeapp.Fake.plist") as alias
	tell application "Finder"
		duplicate TheFile to ((path to preferences folder) as alias) with replacing
	end tell
	set theSetScript to "
#!/bin/bash

defaults delete com.fakeapp.Fake \"FUWindowFrameString\"
defaults delete com.fakeapp.Fake \"NSWindow Frame ActionLibrary\"
defaults delete com.fakeapp.Fake \"NSWindow Frame FUWindow\"
defaults delete com.fakeapp.Fake \"NSWindow Frame Preferences\"
defaults delete com.fakeapp.Fake \"WebDatabaseDirectory\"
defaults write com.fakeapp.Fake \"FakeDelayBetweenRunningActions\" '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 ((path to me as string) & "Contents:Resources: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


Cleanup show_results script

Cleanup show_results script

#! /usr/bin/osascript

# Display runner results in BBEdit Results Browser
#
# Expected arguments:
#   title    -- tile for results browser
#	doc      -- path to document
#   messages -- sorted list of messages
on run argv
	if (count of argv) < 3 then
		error "Usage: bbresults [title] [doc] [messages]"
	end if

	set title to ((item 1 of argv) as string)
	set doc to POSIX file ((item 2 of argv) as string)
	set messages to (item 3 of argv)

	tell application "Finder"
		set resources to (container of (path to me)) as string
		set golib to load script ((resources & "package.scpt") as alias)
		tell golib to showResults(title, doc, messages)
	end tell

	return
end run