Fix AppleScript extension matching

Fix AppleScript extension matching

# AppleScript folder action for the pdfmatch command
#
# Open with script editor, compile and save to
# ~/Library/Workflows/Applications/Folder\ Actions/
#
# Then open the "Folder Actions Setup" application and add the work folder
# where your pdfmatch.json config lives and attach this script.
#
on adding folder items to this_folder after receiving these_files
	try
    set ext to {"pdf", "tif", "tiff", "jpeg", "jpg"}
		repeat with each_file in these_files
			tell application "System Events"
				if ext contains name extension of each_file then
					# You might need to add your node binary to your $PATH. For example:
					# export PATH=/usr/local/bin:/usr/local/opt/node@6/bin:$PATH
					set output to (do shell script "cd '" & POSIX path of this_folder & "' && pdfmatch '" & POSIX path of each_file & "' --delete 2>&1")
					#display alert output
				end if
			end tell
		end repeat
	on error err_string number error_number
		display alert "Error " & error_number & ": " & err_string
	end try
end adding folder items to

# AppleScript folder action for the pdfmatch command
#
# Open with script editor, compile and save to
# ~/Library/Workflows/Applications/Folder\ Actions/
#
# Then open the "Folder Actions Setup" application and add the work folder
# where your pdfmatch.json config lives and attach this script.
#
on adding folder items to this_folder after receiving these_files
	try
		repeat with each_file in these_files
			tell application "System Events"
				if name extension of each_file is "pdf" or "tif" or "tiff" or "jpeg" or "jpg" then
					# You might need to add your node binary to your $PATH. For example:
					# export PATH=/usr/local/bin:/usr/local/opt/node@6/bin:$PATH
					set output to (do shell script "cd '" & POSIX path of this_folder & "' && pdfmatch '" & POSIX path of each_file & "' --delete 2>&1")
					#display alert output
				end if
			end tell
		end repeat
	on error err_string number error_number
		display alert "Error " & error_number & ": " & err_string
	end try
end adding folder items to


Debug

Debug

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

r

l
n
4

cobj
m
o0argv
o0	pathtopsd	pathToPsd
r

l
n
4

cobj
m

o0argv
o0	pathtojsx	pathToJsx
O0
k/
I
.miscactvnullnull !"
!I #
.PsCSodocnull****
#4$

alis
$o0	pathtopsd	pathToPsd"%&
%I!)'
.miscDjxMutxt****
'l!%(
(4!%)

file
)m#$**++t/Users/ngys/Documents/Works/jenkins/photoshop-jsx/hoge.jsx&,
,I*/
.PsCSquitnullnull
m--08BIMalisMacintosh HDΘ*SH+t[IAdobe Photoshop CC 2015.appt[J	 Adobe Photoshop CC 2015ΗAt[I#$OMacintosh HD:Applications:Adobe Photoshop CC 2015:Adobe Photoshop CC 2015.app8Adobe Photoshop CC 2015.appMacintosh HD@Applications/Adobe Photoshop CC 2015/Adobe Photoshop CC 2015.app/.
.l/0/
.aevtoappnull****012
.aevtoappnull****0argv10argv2-*

cobj0	pathtopsd	pathToPsd0	pathtojsx	pathToJsx
.miscactvnullnull

alis
.PsCSodocnull****

file
.miscDjxMutxt****
.PsCSquitnullnull1k/EOl/EO*jO*/jO*/j	O*j
Uascrޭ

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

r

l
n
4

cobj
m
o0argv
o0	pathtopsd	pathToPsd
r

l
n
4

cobj
m

o0argv
o0	pathtojsx	pathToJsx
O'
k&
I
.miscactvnullnull !"
!I #
.PsCSodocnull****
#4$

alis
$o0	pathtopsd	pathToPsd"%&
%l!!'('% do javascript (file pathToJsx)())> do javascript (file pathToJsx)&*
*I!&
.PsCSquitnullnull
m++08BIMalisMacintosh HDΘ*SH+t[IAdobe Photoshop CC 2015.appt[J	 Adobe Photoshop CC 2015ΗAt[I#$OMacintosh HD:Applications:Adobe Photoshop CC 2015:Adobe Photoshop CC 2015.app8Adobe Photoshop CC 2015.appMacintosh HD@Applications/Adobe Photoshop CC 2015/Adobe Photoshop CC 2015.app/,
,l-.-
.aevtoappnull****./0
.aevtoappnull****0argv/0argv0+

cobj0	pathtopsd	pathToPsd0	pathtojsx	pathToJsx
.miscactvnullnull

alis
.PsCSodocnull****
.PsCSquitnullnull(k/EOl/EO*jO*/jO*jUascr
ޭ


Improved compatibility of iTerm2 button.

JsOsaDAS1.001.00bplist00Vscripto	//  The MIT License (MIT)
//  Copyright  2017 Lex Tang, http://lexrus.com
//
//  https://github.com/lexrus/LTFinderButtons
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the  Software ), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED  AS IS , WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.

var app = Application.currentApplication()
app.includeStandardAdditions = true

ObjC.import("Foundation")

function urlPathToPosixPath(path) {
	return decodeURIComponent(path)
	    .replace(/^\/?file[:]\/+/i, '/')
		.replace(/(")/g, '\\$1')
}

function getCurrentFinderFolderPath() {
	var Finder = Application('Finder')
	var item = Finder.selection()[0]
	if (!item) {
		try {
			return urlPathToPosixPath(Finder.windows[0].target().url())
		} catch (e) {
			return urlPathToPosixPath(Finder.desktop().url())
		}
	}
	if (item.kind() == 'Folder') {
		return urlPathToPosixPath(item.url())
	}

	var fileURL = $.NSURL.alloc.initFileURLWithPath(item.url())
	var urlPath = ObjC.unwrap(fileURL.path.stringByDeletingLastPathComponent)
	return urlPathToPosixPath(urlPath)
}

var iTerm2
try {
    iTerm2 = Application('iTerm2')
} catch(e) {
    iTerm2 = Application('iTerm')
}
iTerm2.activate()
if (!iTerm2.currentWindow()) {
	iTerm2.createWindowWithDefaultProfile()
}

var session = iTerm2.currentWindow().currentSession()

if (session.isAtShellPrompt()) {
	iTerm2.createWindowWithDefaultProfile()
}

session = iTerm2.currentWindow().currentSession()

var currentFolderPath = getCurrentFinderFolderPath()
console.log(currentFolderPath)

var cmd = `\ncd "${currentFolderPath}";clear;`

session.write({'text': cmd})

jscrޭ

JsOsaDAS1.001.00bplist00Vscripto	//  The MIT License (MIT)
//  Copyright  2017 Lex Tang, http://lexrus.com
//
//  https://github.com/lexrus/LTFinderButtons
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the  Software ), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED  AS IS , WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.

var app = Application.currentApplication()
app.includeStandardAdditions = true

ObjC.import("Foundation")

function urlPathToPosixPath(path) {
	return decodeURIComponent(path)
	    .replace(/^\/?file[:]\/+/i, '/')
		.replace(/(")/g, '\\$1')
}

function getCurrentFinderFolderPath() {
	var Finder = Application('Finder')
	var item = Finder.selection()[0]
	if (!item) {
		try {
			return urlPathToPosixPath(Finder.windows[0].target().url())
		} catch (e) {
			return urlPathToPosixPath(Finder.desktop().url())
		}
	}
	if (item.kind() == 'Folder') {
		return urlPathToPosixPath(item.url())
	}

	var fileURL = $.NSURL.alloc.initFileURLWithPath(item.url())
	var urlPath = ObjC.unwrap(fileURL.path.stringByDeletingLastPathComponent)
	return urlPathToPosixPath(urlPath)
}

var iTerm2 = Application('iTerm2')
iTerm2.activate();
if (!iTerm2.currentWindow()) {
	iTerm2.createWindowWithDefaultProfile()
}

var session = iTerm2.currentWindow().currentSession()

if (session.isAtShellPrompt()) {
	iTerm2.createWindowWithDefaultProfile()
}

session = iTerm2.currentWindow().currentSession()

var currentFolderPath = getCurrentFinderFolderPath()
console.log(currentFolderPath)

var cmd = `\ncd "${currentFolderPath}";clear;`

session.write({'text': cmd})

Hjscrޭ


Corrected destination of main.applescript

Was downloading it into the resources directory by mistake.

-- First compare versions on main:

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 & "main.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/main.version"
	--display dialog "Local version of main 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 & "main.applescript")
		do shell script "curl https://raw.githubusercontent.com/nilness/mhqtools/master/main.applescript > \"" & local_file & "\""
		--update the local version string
		set local_file to the POSIX path of (resources_directory & "main.version")
		do shell script "curl https://raw.githubusercontent.com/nilness/mhqtools/master/main.version > \"" & local_file & "\""

	end if

	-- Next compare versions on mhqreset:

	set local_file to the POSIX path of (resources_directory & "mhqreset.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/mhqreset.version"

	if current_version > local_version then
		--download the new version
		set local_file to the POSIX path of (resources_directory & "mhqreset.sh")
		do shell script "curl https://raw.githubusercontent.com/nilness/mhqtools/master/mhqreset.sh > \"" & local_file & "\""
		--update the local version string
		set local_file to the POSIX path of (resources_directory & "mhqreset.version")
		do shell script "curl https://raw.githubusercontent.com/nilness/mhqtools/master/mhqreset.version > \"" & local_file & "\""
		--display dialog "Need to update reset script!"
	end if

end try

-- now launch the main script

set theScript to (scripts_directory & "main.applescript") as alias

run script theScript

-- First compare versions on main:

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 & "main.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/main.version"
	--display dialog "Local version of main 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 (resources_directory & "main.applescript")
		do shell script "curl https://raw.githubusercontent.com/nilness/mhqtools/master/main.applescript > \"" & local_file & "\""
		--update the local version string
		set local_file to the POSIX path of (resources_directory & "main.version")
		do shell script "curl https://raw.githubusercontent.com/nilness/mhqtools/master/main.version > \"" & local_file & "\""

	end if

	-- Next compare versions on mhqreset:

	set local_file to the POSIX path of (resources_directory & "mhqreset.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/mhqreset.version"

	if current_version > local_version then
		--download the new version
		set local_file to the POSIX path of (resources_directory & "mhqreset.sh")
		do shell script "curl https://raw.githubusercontent.com/nilness/mhqtools/master/mhqreset.sh > \"" & local_file & "\""
		--update the local version string
		set local_file to the POSIX path of (resources_directory & "mhqreset.version")
		do shell script "curl https://raw.githubusercontent.com/nilness/mhqtools/master/mhqreset.version > \"" & local_file & "\""
		--display dialog "Need to update reset script!"
	end if

end try

-- now launch the main script

set theScript to (scripts_directory & "main.applescript") as alias

run script theScript


update cerca script

update cerca script

tell application "iTerm2"
  activate

  set cercaWindow to (current window)

  tell cercaWindow

    tell current session
      split vertically with default profile
      write text "tcd"
    end tell

    tell last session of current tab
      write text "tcs"
    end tell

    set secondTab to (create tab with default profile)
    secondTab
    tell secondTab
      tell current session
        split vertically with default profile
        write text "tcf"
      end tell

      tell last session
        write text "tc; ty; stt aux"
      end tell
    end tell

    set thirdTab to (create tab with default profile)
    thirdTab
    tell thirdTab
      tell first session
        write text "tcv"
      end tell
    end tell

    set fourthTab to (create tab with default profile)
    fourthTab
    tell fourthTab
      tell first session
        write text "tc"
      end tell
    end tell
  end tell
end tell

tell application "iTerm2"
  activate

  set cercaWindow to (current window)

  tell cercaWindow

    tell current session
      split vertically with default profile
      write text "tcd"
    end tell

    tell last session of current tab
      write text "tcs"
    end tell

    set secondTab to (create tab with default profile)
    secondTab
    tell secondTab
      tell current session
        split vertically with default profile
        write text "tcf"
      end tell

      tell last session
        write text "tc"
      end tell
    end tell

    set thirdTab to (create tab with default profile)
    thirdTab
    tell thirdTab
      tell first session
        write text "tcv"
      end tell
    end tell
  end tell
end tell


Update headphone connect script for Big Sur

-- Source: https://www.reddit.com/r/MacOS/comments/i4czgu/big_sur_airpods_script/gck3gz3
-- Works on macOS 11 Big Sur

use framework "IOBluetooth"
use scripting additions

set DeviceName to "Rosco's Headphones"

on getFirstMatchingDevice(deviceName)
    repeat with device in (current application's IOBluetoothDevice's pairedDevices() as list)
        if (device's nameOrAddress as string) contains deviceName then return device
    end repeat
end getFirstMatchingDevice

on toggleDevice(device)
    if not (device's isConnected as boolean) then
        device's openConnection()
        return "Connecting " & (device's nameOrAddress as string)
    else
        device's closeConnection()
        return "Disconnecting " & (device's nameOrAddress as string)
    end if
end toggleDevice

return toggleDevice(getFirstMatchingDevice(DeviceName))

activate application "SystemUIServer"
tell application "System Events"
    tell process "SystemUIServer"
        set btMenu to (menu bar item 1 of menu bar 1 whose description contains "bluetooth")
        tell btMenu
            click
            try
                tell (menu item "Rosco's Headphones" of menu 1)
                    click
                    if exists menu item "Connect" of menu 1 then
                        click menu item "Connect" of menu 1
                        return "Connecting..."
                    else if exists menu item "Disconnect" of menu 1 then
                        click menu item "Disconnect" of menu 1
                        return "Disconnecting..."
                    end if
                end tell
            end try
        end tell
    end tell
    key code 53
    return "Device not found or Bluetooth turned off"
end tell


Update for Yosemite compatibility

Update for Yosemite compatibility

Main change is that Yosemite no longer runs /var/root/.profile when booting single user mode, it not runs /var/root/.bashrc

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

--display dialog SWUpdateServer

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 MHQ User & Reset CPU", "Remove Current User & Reset CPU", "Install Tech User Reset Script", "Test for Flashback Trojan", "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
		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
	on error
		display dialog "Using default Apple SW Update Server"
	end try
end listSWUpdateServer

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

		if (osVersion < "7" and osVersion > "3") then
			do shell script "/usr/bin/defaults delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL"
		else
			do shell script "defaults delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL" with administrator privileges
		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}\"

defaults write com.apple.Finder ShowHardDrivesOnDesktop -bool true #this will make sure the Finder is set to show drives on desktop

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

	if (osVersion < "7" and osVersion > "3") then
		do shell script theSetScript
	else
		do shell script theSetScript with administrator privileges
	end if

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 < "7" and osVersion > "3") then
		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

	else
		tell application "Finder"
			duplicate TheFile to (path to startup items from local domain as alias) with replacing
		end tell
	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
	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 | 10) dscacheutil -flushcache;sudo killall -HUP mDNSResponder ;;
      *) echo \"Unsupported client OS\"; exit 1 ;;
esac

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

	if (osVersion < "7" and osVersion > "3") then
		do shell script theSetScript
	else
		do shell script theSetScript with administrator privileges
	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

	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

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

--display dialog SWUpdateServer

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 MHQ User & Reset CPU", "Remove Current User & Reset CPU", "Install Tech User Reset Script", "Test for Flashback Trojan", "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
		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
	on error
		display dialog "Using default Apple SW Update Server"
	end try
end listSWUpdateServer

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

		if (osVersion ≥ "7") then
			do shell script "/usr/bin/defaults delete /Library/Preferences/com.apple.SoftwareUpdate CatalogURL" with administrator privileges
		else
			do shell script "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}\"

defaults write com.apple.Finder ShowHardDrivesOnDesktop -bool true #this will make sure the Finder is set to show drives on desktop

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\" ;;
      *) 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

	if (osVersion ≥ "7") then
		do shell script theSetScript with administrator privileges
	else
		do shell script theSetScript
	end if

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()
		do shell script "echo \"/mhqreset.sh\" >> /private/var/root/.profile" 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()
		do shell script "echo '/mhqreset.sh' '\"" & current_user & "\"' >> /private/var/root/.profile" 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 ≥ "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
	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 ;;
      *) echo \"Unsupported client OS\"; exit 1 ;;
esac

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

	if (osVersion ≥ "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

	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


Updates to applescript

Updates to applescript

FasdUAS 1.101.10
k
l[U This script records video via the ezcap VideoCapture software. To launch the script:		 This script records video via the ezcap VideoCapture software. To launch the script:

l

l[U from terminal  osascript /path/to/script/RawVideoRec.scpt savePath vidName recLength from terminal  osascript /path/to/script/RawVideoRec.scpt savePath vidName recLength

l
l from matlab  system(sprintf('osascript /path/to/script/RawVideoRec.scpt %s %s %s', savePath, vidName1, num2str(recTime+postBufferTime))); from matlab  system(sprintf('osascript /path/to/script/RawVideoRec.scpt %s %s %s', savePath, vidName1, num2str(recTime+postBufferTime)));
l
i
I
.aevtoappnull****
o0argv
k !
 r"#
"I$
.sysoexecTEXTTEXT
$m%%&&6/usr/local/bin/gdate +%s.%N
#o0
beforetell
BeforeTell!'(
'OG)*
)kF++,-
,I.
.aevtodocnullalis
.4/

cwin
/m0011$ezcap VideoGrabber-23
2r45
4I6
.sysoexecTEXTTEXT
6m77886/usr/local/bin/gdate +%s.%N
5o0beforestartBeforeStart39:
9I:;
.efxcStarnullnull;<=

kWch
<m >>??$ezcap VideoGrabber=@A

kFil
@4!/B

psxf
Bl#.C
Cb#.DE
Db#,FG
Fn#'HI
H4$'J

cobj
Jm%&
Io#$0argv
Gn'+KL
K4(+M

cobj
Mm)*
Lo'(0argv
Em,-NNOO.movAP

kDur
Pn04QR
Q414S

cobj
Sm23
Ro010argv:T
Tr;FUV
UI;BW
.sysoexecTEXTTEXT
Wm;>XXYY6/usr/local/bin/gdate +%s.%N
Vo0
afterstart
AfterStart
*m	ZZ@alisMacintosh HDA'H+}Qezcap VideoCapture.app}R	 ezcap VideoGrabberAmJZ}QIEMacintosh HD:Applications:ezcap VideoGrabber:ezcap VideoCapture.app.ezcap VideoCapture.appMacintosh HD6Applications/ezcap VideoGrabber/ezcap VideoCapture.app/([\
[rHS]^
]IHO_
.sysoexecTEXTTEXT
_mHK``aa6/usr/local/bin/gdate +%s.%N
^o0	aftertell	AfterTell\bc
brTdde
dJT`ffgh
goTU0
beforetell
BeforeTellhij
ioUV0beforestartBeforeStartjkl
koVY0
afterstart
AfterStartlm
moY\0	aftertell	AfterTell
eo0mylistmyListcno
nreppq
pcelrs
rmehttuu
smhk

ctxt
qo0mystringmyStringovw
vXqxy
xrz{
zb|}
|b~
~o0mystringmyString
o0myitemmyItem
}1

lnfd
{o0mystringmyString0myitemmyItem
yotw0mylistmyListw
L
o0mystringmyString
l
l

.aevtoappnull****0
beforetell
BeforeTell0beforestartBeforeStart0
afterstart
AfterStart0	aftertell	AfterTell0mylistmyList0mystringmyString
.aevtoappnull****0argv0argv0myitemmyItem%Z07>NX`t
.sysoexecTEXTTEXT0
beforetell
BeforeTell

cwin
.aevtodocnullalis0beforestartBeforeStart

kWch

kFil

psxf

cobj

kDur
.efxcStarnullnull0
afterstart
AfterStart0	aftertell	AfterTell0mylistmyList

ctxt0mystringmyString

kocl
.corecnte********

lnfdjEO<*/jOjEO**k/l/%%/m/aOajE`UOajE`O__avE`Oaa&E`O%_[alkh_%_%E`[OYO_(1475503738.525951000(1475503738.535010000(1475503738.567056000(1475503738.5731240001475503738.525951000
1475503738.535010000
1475503738.567056000
1475503738.573124000
ascr
ޭ

FasdUAS 1.101.10
k
l[U This script records video via the ezcap VideoCapture software. To launch the script:		 This script records video via the ezcap VideoCapture software. To launch the script:

l

l[U from terminal  osascript /path/to/script/RawVideoRec.scpt savePath vidName recLength from terminal  osascript /path/to/script/RawVideoRec.scpt savePath vidName recLength

l
l from matlab  system(sprintf('osascript /path/to/script/RawVideoRec.scpt %s %s %s', savePath, vidName1, num2str(recTime+postBufferTime))); from matlab  system(sprintf('osascript /path/to/script/RawVideoRec.scpt %s %s %s', savePath, vidName1, num2str(recTime+postBufferTime)));
l
i
I
.aevtoappnull****
o0argv
k !
 r"#
"I$
.sysoexecTEXTTEXT
$m%%&&6/usr/local/bin/gdate +%s.%N
#o0
beforetell
BeforeTell!'(
'OG)*
)kF++,-
,I.
.aevtodocnullalis
.4/

cwin
/m0011$ezcap VideoGrabber-23
2r45
4I6
.sysoexecTEXTTEXT
6m77886/usr/local/bin/gdate +%s.%N
5o0beforestartBeforeStart39:
9I:;
.efxcStarnullnull;<=

kWch
<m >>??$ezcap VideoGrabber=@A

kFil
@4!/B

psxf
Bl#.C
Cb#.DE
Db#,FG
Fn#'HI
H4$'J

cobj
Jm%&
Io#$0argv
Gn'+KL
K4(+M

cobj
Mm)*
Lo'(0argv
Em,-NNOO.movAP

kDur
Pn04QR
Q414S

cobj
Sm23
Ro010argv:T
Tr;FUV
UI;BW
.sysoexecTEXTTEXT
Wm;>XXYY6/usr/local/bin/gdate +%s.%N
Vo0
afterstart
AfterStart
*m	ZZ@alisMacintosh HDA'H+}Qezcap VideoCapture.app}R	 ezcap VideoGrabberAmJZ}QIEMacintosh HD:Applications:ezcap VideoGrabber:ezcap VideoCapture.app.ezcap VideoCapture.appMacintosh HD6Applications/ezcap VideoGrabber/ezcap VideoCapture.app/([\
[rHS]^
]IHO_
.sysoexecTEXTTEXT
_mHK``aa6/usr/local/bin/gdate +%s.%N
^o0	aftertell	AfterTell\bc
brTdde
dJT`ffgh
goTU0
beforetell
BeforeTellhij
ioUV0beforestartBeforeStartjkl
koVY0
afterstart
AfterStartlm
moY\0	aftertell	AfterTell
eo0mylistmyListcno
nreppq
pcelrs
rmehttuu
smhk

ctxt
qo0mystringmyStringovw
vXqxy
xrz{
zb|}
|b~
~o0mystringmyString
o0myitemmyItem
}1

lnfd
{o0mystringmyString0myitemmyItem
yotw0mylistmyListw
L
o0mystringmyString
l
l

.aevtoappnull****0
beforetell
BeforeTell0beforestartBeforeStart0
afterstart
AfterStart0	aftertell	AfterTell0mylistmyList0mystringmyString
.aevtoappnull****0argv0argv0myitemmyItem%Z07>NX`t
.sysoexecTEXTTEXT0
beforetell
BeforeTell

cwin
.aevtodocnullalis0beforestartBeforeStart

kWch

kFil

psxf

cobj

kDur
.efxcStarnullnull0
afterstart
AfterStart0	aftertell	AfterTell0mylistmyList

ctxt0mystringmyString

kocl
.corecnte********

lnfdjEO<*/jOjEO**k/l/%%/m/aOajE`UOajE`O__avE`Oaa&E`O%_[alkh_%_%E`[OYO_(1475185821.534117000(1475185821.543151000(1475185821.588931000(1475185821.5954390001475185821.534117000
1475185821.543151000
1475185821.588931000
1475185821.595439000
ascr
ޭ


perhaps some hidden character

perhaps some hidden character

-- fmGUI_ManageLayouts_Layout_CreateOrUpdate({layoutName:null})
-- Daniel A. Shockley, NYHTC
-- Create/Update a layout.

(*
HISTORY:
	2020-03-03 ( dshockley, hdu ): Updated as standalone function for fm-scripts git repository. Use clickObjectByCoords instead of clickObjFromHtcLib.
	-- 1.4 - 2017-06-14 ( eshagdar ): narrowed scope
	-- 1.3 - 2017-05-18 ( eshagdar ): updated for FM15.
	-- 1.2 - 2016-08-24 ( eshagdar ): wait until 'Layout Setup' window comes up.
	-- 1.1 - 2013-11-22 ( dshockley ): If oldLayoutName is specified, will look for and change layout name, even if otherwise doNotChangeExisting.

	-- TODO: NOT HANDLING SCRIPT TRIGGERS YET!!! 2013-11-20-dshockley

REQUIRES:
	clickObjectByCoords
	logConsole
	fmGUI_CheckboxSet
	fmGUI_DataViewer_Close
	fmGUI_ManageLayouts_LayoutFolderSelect
	fmGUI_ManageLayouts_Open
	fmGUI_ManageLayouts_PopupNewItemOfType
	fmGUI_ManageLayouts_Select
	fmGUI_PopupSet
	windowWaitUntil_FrontIS
*)

on run
	fmGUI_ManageLayouts_Layout_CreateOrUpdate({layoutName:"Directory"})
end run

--------------------
-- START OF CODE
--------------------

on fmGUI_ManageLayouts_Layout_CreateOrUpdate(layoutOptions)
	-- version 1.4

	set defaultPrefs to {layoutName:null, oldLayoutName:null, doNotChangeExisting:false, baseTableName:null, layoutParentFolder:"", includeInLayoutMenus:0, menuSet:null, formViewEnabled:1, listViewEnabled:1, tableViewEnabled:1, defaultView:"Form View", scriptTriggers:{}}

	set layoutOptions to layoutOptions & defaultPrefs

	set layoutName to layoutName of layoutOptions
	set oldLayoutName to oldLayoutName of layoutOptions

	-- Select a Layout and Edit it, or create it if it didn't exist yet.
	try
		fmGUI_DataViewer_Close()
		fmGUI_ManageLayouts_Open({})

		-- INIT:
		set foundThisLayout to false
		set foundOldLayout to false
		set layoutSelected to false

		set foundThisLayout to fmGUI_ManageLayouts_Select({layoutName:layoutName})
		set layoutSelected to foundThisLayout

		if oldLayoutName is not null then
			set foundOldLayout to fmGUI_ManageLayouts_Select({layoutName:oldLayoutName})
			if foundThisLayout and foundOldLayout then
				error "Couldn't fmGUI_ManageLayouts_Layout_CreateOrUpdate: Both the old '" & oldLayoutName & "' and the 'new' layout name '" & layoutName & "' already exist - PROBLEM!"
			else if foundOldLayout then
				set layoutSelected to true
			end if

		end if

		tell application "System Events"
			tell application process "FileMaker Pro Advanced"
				set manageLayoutsWindow to window 1
			end tell
		end tell

		if layoutSelected then
			if doNotChangeExisting of layoutOptions and not foundOldLayout then
				-- do NOT change if it already exists with the correct name.
			else
				-- exists and was selected, so click Edit:

				tell application "System Events"
					tell application process "FileMaker Pro Advanced"
						set buttonRef to first button of manageLayoutsWindow whose title is "Edit"
					end tell
				end tell

				clickObjectByCoords(buttonRef)
				windowWaitUntil_FrontIS({windowName:"Layout Setup"})

				tell application "System Events"
					tell application process "FileMaker Pro Advanced"
						set layoutSetupDialog to window 1
						set interfaceParent to tab group 1 of layoutSetupDialog

						if foundOldLayout then
							-- need to rename this layout:
							set value of text field "Layout Name" of interfaceParent to layoutName
						end if
					end tell
				end tell

				if doNotChangeExisting of layoutOptions then

				else -- ALLOWED to CHANGE the other properties of the layout:
					tell application "System Events"
						tell application process "FileMaker Pro Advanced"
							click (first radio button of interfaceParent whose name is "General")
							set showRecordsButton to pop up button "Show records from:" of interfaceParent
							set inludeInMenuButton to checkbox "Include in layout menus" of interfaceParent
							set menuSetButton to pop up button "Menu Set:" of interfaceParent
						end tell
					end tell

					if baseTableName of layoutOptions is not null then fmGUI_PopupSet({objRef:my coerceToString(showRecordsButton), objValue:baseTableName of layoutOptions})
					if includeInLayoutMenus of layoutOptions is not null then fmGUI_CheckboxSet(inludeInMenuButton, includeInLayoutMenus of layoutOptions)
					if menuSet of layoutOptions is not null then fmGUI_PopupSet({objRef:my coerceToString(menuSetButton), objValue:menuSet of layoutOptions})

					tell application "System Events"
						tell application process "FileMaker Pro Advanced"
							click (first radio button of interfaceParent whose name is "Views")
							set formCheckbox to checkbox "Form View" of interfaceParent
							set listCheckbox to checkbox "List View" of interfaceParent
							set tableCheckbox to checkbox "Table View" of interfaceParent
							set defaultButton to pop up button "Default view:" of interfaceParent
						end tell
					end tell

					if formViewEnabled of layoutOptions is not null then fmGUI_CheckboxSet(formCheckbox, formViewEnabled of layoutOptions)
					if listViewEnabled of layoutOptions is not null then fmGUI_CheckboxSet(listCheckbox, listViewEnabled of layoutOptions)
					if tableViewEnabled of layoutOptions is not null then fmGUI_CheckboxSet(tableCheckbox, tableViewEnabled of layoutOptions)
					if defaultView of layoutOptions is not null then fmGUI_PopupSet({objRef:my coerceToString(defaultButton), objValue:defaultView of layoutOptions})

				end if

				tell application "System Events"
					tell application process "FileMaker Pro Advanced"
						click button "OK" of layoutSetupDialog
					end tell
				end tell
			end if

			-- END IF: existing to edit.

		else
			-- BEGIN: does not exist - need to create it:

			if length of (layoutParentFolder of layoutOptions) is greater than 0 then
				-- create it IN a layout folder:
				-- Select the folder, or create it if it doesn't exist yet:
				if not fmGUI_ManageLayouts_LayoutFolderSelect(layoutParentFolder of layoutOptions) then
					fmGUI_ManageLayouts_PopupNewItemOfType("Folder")
					tell application "System Events"
						tell application process "FileMaker Pro Advanced"
							set value of text field "Folder Name:" of window 1 to layoutParentFolder of layoutOptions
							click button "OK" of window 1
							set newFolderRow to first row of (outline 1 of scroll area 1 of manageLayoutsWindow) whose value of text field 1 of group 1 is layoutParentFolder of layoutOptions
							set checkboxRef to checkbox 1 of newFolderRow
						end tell
					end tell
					fmGUI_CheckboxSet(checkboxRef, 1)

				end if
			end if

			-- Create the layout:
			if debugMode then tell application "htcLib" to logConsole(ScriptName, "creating layout: " & (layoutName of layoutOptions))
			tell application "System Events"
				tell application process "FileMaker Pro Advanced"
					set buttonRef to first button of manageLayoutsWindow whose title is "New"
				end tell
			end tell

			-- BEGIN: NEW WINDOW CODE
			clickObjFromHtcLib(buttonRef)
			tell application "htcLib" to windowWaitUntil_FrontIS({windowName:"New Layout/Report"})

			tell application "System Events"
				tell application process "FileMaker Pro Advanced"
					set newLayoutDialog to window 1
					set value of text field 1 of newLayoutDialog to layoutName of layoutOptions
					set buttonRef to pop up button 1 of newLayoutDialog
				end tell
			end tell
			tell application "htcLib" to fmGUI_PopupSet({objRef:my coerceToString(buttonRef), objValue:baseTableName of layoutOptions})
			tell application "System Events"
				tell application process "FileMaker Pro Advanced"
					click button 4 of newLayoutDialog -- select 'Computer'
					click button 6 of newLayoutDialog -- select 'Form'

					-- we don't care which mode to view in, so Finish:
					click button "Finish" of newLayoutDialog
				end tell
			end tell

			delay 1

			-- Now, believe it or not, need to call ITSELF since not all options available during Create:
			fmGUI_ManageLayouts_Layout_CreateOrUpdate(layoutOptions)

			-- END IF: does not exist - need to create it.
		end if

		return true
	on error errMsg number errNum
		error "unable to fmGUI_ManageLayouts_Layout_CreateOrUpdate '" & layoutName of layoutOptions & "' - " & errMsg number errNum
	end try

end fmGUI_ManageLayouts_Layout_CreateOrUpdate

--------------------
-- END OF CODE
--------------------

on clickObjectByCoords(prefs)
	tell application "htcLib" to clickObjectByCoords(my coerceToString(prefs))
end clickObjectByCoords

on fmGUI_CheckboxSet(prefs)
	set objRefStr to coerceToString(objRef of prefs)
	tell application "htcLib" to fmGUI_CheckboxSet({objRef:objRefStr} & prefs)
end fmGUI_CheckboxSet

on fmGUI_DataViewer_Close()
	tell application "htcLib" to fmGUI_DataViewer_Close()
end fmGUI_DataViewer_Close

on fmGUI_ManageLayouts_LayoutFolderSelect(prefs)
	tell application "htcLib" to fmGUI_ManageLayouts_LayoutFolderSelect(prefs)
end fmGUI_ManageLayouts_LayoutFolderSelect

on fmGUI_ManageLayouts_Open(prefs)
	tell application "htcLib" to fmGUI_ManageLayouts_Open(prefs)
end fmGUI_ManageLayouts_Open

on fmGUI_ManageLayouts_PopupNewItemOfType(prefs)
	tell application "htcLib" to fmGUI_ManageLayouts_PopupNewItemOfType(prefs)
end fmGUI_ManageLayouts_PopupNewItemOfType

on fmGUI_ManageLayouts_Select(prefs)
	tell application "htcLib" to fmGUI_ManageLayouts_Select(prefs)
end fmGUI_ManageLayouts_Select

on fmGUI_PopupSet(prefs)
	set objRefStr to coerceToString(objRef of prefs)
	tell application "htcLib" to fmGUI_PopupSet({objRef:objRefStr} & prefs)
end fmGUI_PopupSet

on logConsole(prefs)
	tell application "htcLib" to logConsole(prefs)
end logConsole

on windowWaitUntil_FrontIS(prefs)
	tell application "htcLib" to windowWaitUntil_FrontIS(prefs)
end windowWaitUntil_FrontIS

on coerceToString(incomingObject)
	-- 2017-07-12 ( eshagdar ): bootstrap code to bring a coerceToString into this file for the sample to run ( instead of having a copy of the handler locally ).

	tell application "Finder" to set coercePath to (container of (container of (path to me)) as text) & "text parsing:coerceToString.applescript"
	set codeCoerce to read file coercePath as text
	tell application "htcLib" to set codeCoerce to "script codeCoerce " & return & getTextBetween({sourceText:codeCoerce, beforeText:"-- START OF CODE", afterText:"-- END OF CODE"}) & return & "end script" & return & "return codeCoerce"
	set codeCoerce to run script codeCoerce
	tell codeCoerce to coerceToString(incomingObject)
end coerceToString