-- ================================================================================================================= -- Wake on LAN via pfSense Actions -- -- Sends Wake-on-LAN requests through pfSense Actions to power on remote PCs, waits for them to boot, and launches a -- remote desktop application of your choice. Supports multiple PCs with a management UI. -- -- PC configuration is stored at: -- ~/.config/pfsense-actions-wol/config.plist -- -- Notes: -- * Requires pfSense Actions 2.0.0 or later at an HTTPS address, such as one behind a reverse proxy -- * Each PC needs a personal access token with the "wol:execute" and "reachability:read" scopes, created in the -- pfSense Actions console under Access tokens -- * This script is interactive only -- * Per-PC access tokens are stored in macOS Keychain (service: "Wake on LAN via pfSense Actions") -- -- Good to know: -- * Deleting a PC also permanently removes its access token from Keychain -- * pfSense Actions allows 3 action requests per 10 seconds, so the script pauses when it reaches that limit -- -- Accepted Risks: -- * Access tokens are briefly written to a curl config file during API calls (cleaned up afterward) -- * If a PC rename fails mid-save, an orphaned Keychain entry may remain; the old config and token are still intact -- * Access tokens appear briefly in process arguments during Keychain operations (inherent to the macOS "security" CLI) -- ================================================================================================================= use framework "Foundation" use scripting additions ------------------------------------------------------------------ -- Properties ------------------------------------------------------------------ property notificationTitle : "Wake on LAN via pfSense Actions" property notificationSound : "Blow" property candidateApps : {{"Moonlight", "com.moonlight-stream.Moonlight"}, {"Parsec", "tv.parsec.www"}, {"Windows App", "com.microsoft.rdc.macos"}} property managePcsLabel : "Manage PCs..." property accessTokenPattern : "^pfa_[A-Za-z0-9_-]{43}$" property baseUrlPattern : "^https://[A-Za-z0-9._-]+(:[0-9]+)?/?$" property maximumBootWaitSeconds : 600 ------------------------------------------------------------------ -- Helper: yieldForUi ------------------------------------------------------------------ on yieldForUi(durationSeconds) current application's NSRunLoop's currentRunLoop()'s runUntilDate:(current application's NSDate's dateWithTimeIntervalSinceNow:durationSeconds) end yieldForUi ------------------------------------------------------------------ -- Helper: trimTrailingLineEndings ------------------------------------------------------------------ on trimTrailingLineEndings(theText) set trimmedText to theText as text repeat while trimmedText ends with linefeed or trimmedText ends with return if (count of trimmedText) is 1 then set trimmedText to "" else set trimmedText to text 1 thru -2 of trimmedText end if end repeat return trimmedText end trimTrailingLineEndings ------------------------------------------------------------------ -- Helper: readUtf8File ------------------------------------------------------------------ on readUtf8File(filePath) set fileData to current application's NSData's dataWithContentsOfFile:filePath if fileData is missing value then return "" set fileText to current application's NSString's alloc()'s initWithData:fileData encoding:(current application's NSUTF8StringEncoding) if fileText is missing value then error "Shell command returned output that is not valid UTF-8." return fileText as text end readUtf8File ------------------------------------------------------------------ -- Helper: removeTemporaryFile ------------------------------------------------------------------ on removeTemporaryFile(filePath) if filePath is missing value then return current application's NSFileManager's defaultManager()'s removeItemAtPath:filePath |error|:(missing value) end removeTemporaryFile ------------------------------------------------------------------ -- Helper: doShellResponsive ------------------------------------------------------------------ on doShellResponsive(commandText) set uniqueId to current application's NSUUID's UUID()'s UUIDString() as text set tempDirectory to current application's NSTemporaryDirectory() as text set stdoutPath to tempDirectory & "applescript-shell-" & uniqueId & ".stdout" set stderrPath to tempDirectory & "applescript-shell-" & uniqueId & ".stderr" set stdoutHandle to missing value set stderrHandle to missing value set shellTask to missing value try set fileManager to current application's NSFileManager's defaultManager() set secureFileAttributes to current application's NSDictionary's dictionaryWithObject:384 forKey:(current application's NSFilePosixPermissions) set createdStdout to fileManager's createFileAtPath:stdoutPath |contents|:(missing value) attributes:secureFileAttributes set createdStderr to fileManager's createFileAtPath:stderrPath |contents|:(missing value) attributes:secureFileAttributes if not (createdStdout as boolean) or not (createdStderr as boolean) then error "Could not create temporary shell output files." set stdoutHandle to current application's NSFileHandle's fileHandleForWritingAtPath:stdoutPath set stderrHandle to current application's NSFileHandle's fileHandleForWritingAtPath:stderrPath if stdoutHandle is missing value or stderrHandle is missing value then error "Could not open temporary shell output files." set shellTask to current application's NSTask's alloc()'s init() shellTask's setLaunchPath:"/bin/zsh" shellTask's setArguments:{"-c", commandText} shellTask's setStandardInput:(current application's NSFileHandle's fileHandleWithNullDevice()) shellTask's setStandardOutput:stdoutHandle shellTask's setStandardError:stderrHandle shellTask's |launch|() repeat while (shellTask's isRunning() as boolean) current application's NSRunLoop's currentRunLoop()'s runUntilDate:(current application's NSDate's dateWithTimeIntervalSinceNow:0.05) end repeat shellTask's waitUntilExit() stdoutHandle's closeFile() stderrHandle's closeFile() set stdoutHandle to missing value set stderrHandle to missing value set stdoutText to my trimTrailingLineEndings(my readUtf8File(stdoutPath)) set stderrText to my trimTrailingLineEndings(my readUtf8File(stderrPath)) set exitStatus to shellTask's terminationStatus() as integer my removeTemporaryFile(stdoutPath) my removeTemporaryFile(stderrPath) if exitStatus is not 0 then if stderrText is not "" then error stderrText number exitStatus if stdoutText is not "" then error stdoutText number exitStatus error "Shell command failed with exit status " & exitStatus & "." number exitStatus end if return stdoutText on error errMsg number errNum try if shellTask is not missing value and (shellTask's isRunning() as boolean) then shellTask's terminate() set terminationDeadline to current application's NSDate's dateWithTimeIntervalSinceNow:1 repeat while (shellTask's isRunning() as boolean) and ((terminationDeadline's timeIntervalSinceNow()) as real) > 0 current application's NSRunLoop's currentRunLoop()'s runUntilDate:(current application's NSDate's dateWithTimeIntervalSinceNow:0.05) end repeat if shellTask's isRunning() as boolean then shellTask's interrupt() set interruptDeadline to current application's NSDate's dateWithTimeIntervalSinceNow:1 repeat while (shellTask's isRunning() as boolean) and ((interruptDeadline's timeIntervalSinceNow()) as real) > 0 current application's NSRunLoop's currentRunLoop()'s runUntilDate:(current application's NSDate's dateWithTimeIntervalSinceNow:0.05) end repeat if shellTask's isRunning() as boolean then set killTask to current application's NSTask's launchedTaskWithLaunchPath:"/bin/kill" arguments:{"-KILL", (shellTask's processIdentifier() as text)} killTask's waitUntilExit() shellTask's waitUntilExit() end if end if end if end try try if stdoutHandle is not missing value then stdoutHandle's closeFile() end try try if stderrHandle is not missing value then stderrHandle's closeFile() end try my removeTemporaryFile(stdoutPath) my removeTemporaryFile(stderrPath) error errMsg number errNum end try end doShellResponsive ------------------------------------------------------------------ -- Helper: getConfigPath ------------------------------------------------------------------ on getConfigPath() set configDir to do shell script "echo ~/.config/pfsense-actions-wol" set configPath to configDir & "/config.plist" log "DEBUG -> getConfigPath: " & configPath -- Create directory if needed (owner-only permissions) do shell script "mkdir -p " & quoted form of configDir & " && chmod 700 " & quoted form of configDir -- Initialize empty plist if missing (owner-only permissions) try do shell script "[ -f " & quoted form of configPath & " ]" on error log "DEBUG -> getConfigPath: creating new config plist" do shell script "/usr/libexec/PlistBuddy -c " & quoted form of "Add :PCs array" & " " & quoted form of configPath do shell script "chmod 600 " & quoted form of configPath end try return configPath end getConfigPath ------------------------------------------------------------------ -- Helper: getPcCount ------------------------------------------------------------------ on getPcCount() set configPath to my getConfigPath() set arrayCount to 0 repeat try do shell script "/usr/libexec/PlistBuddy -c " & quoted form of ("Print :PCs:" & arrayCount) & " " & quoted form of configPath & " >/dev/null 2>&1" set arrayCount to arrayCount + 1 on error exit repeat end try end repeat return arrayCount end getPcCount ------------------------------------------------------------------ -- Helper: loadPcNames ------------------------------------------------------------------ on loadPcNames() set configPath to my getConfigPath() set pcNames to {} set pcCount to my getPcCount() log "DEBUG -> loadPcNames: array has " & pcCount & " entries" repeat with idx from 0 to (pcCount - 1) try set pcName to do shell script "/usr/libexec/PlistBuddy -c " & quoted form of ("Print :PCs:" & idx & ":computerName") & " " & quoted form of configPath set end of pcNames to pcName on error log "DEBUG -> loadPcNames: skipping corrupted entry at index " & idx end try end repeat log "DEBUG -> loadPcNames: found " & (count of pcNames) & " PCs" return pcNames end loadPcNames ------------------------------------------------------------------ -- Helper: findPcIndex ------------------------------------------------------------------ on findPcIndex(targetName) set configPath to my getConfigPath() set pcCount to my getPcCount() repeat with idx from 0 to (pcCount - 1) try set pcName to do shell script "/usr/libexec/PlistBuddy -c " & quoted form of ("Print :PCs:" & idx & ":computerName") & " " & quoted form of configPath if pcName is targetName then return idx end if on error log "DEBUG -> findPcIndex: skipping corrupted entry at index " & idx end try end repeat return -1 end findPcIndex ------------------------------------------------------------------ -- Helper: loadPc ------------------------------------------------------------------ on loadPc(targetName) set idx to my findPcIndex(targetName) if idx is -1 then error "PC not found: " & targetName end if set configPath to my getConfigPath() set prefix to ":PCs:" & idx set pcComputerName to do shell script "/usr/libexec/PlistBuddy" & ¬ " -c " & quoted form of ("Print " & prefix & ":computerName") & ¬ " -c " & quoted form of ("Print " & prefix & ":pfsenseActionsUrl") & ¬ " -c " & quoted form of ("Print " & prefix & ":broadcastAddress") & ¬ " -c " & quoted form of ("Print " & prefix & ":ipAddress") & ¬ " -c " & quoted form of ("Print " & prefix & ":macAddress") & ¬ " -c " & quoted form of ("Print " & prefix & ":pingCount") & ¬ " " & quoted form of configPath set fieldLines to paragraphs of pcComputerName log "DEBUG -> loadPc: loaded " & (item 1 of fieldLines) set pcRecord to {computerName:item 1 of fieldLines, pfsenseActionsUrl:item 2 of fieldLines, broadcastAddress:item 3 of fieldLines, ipAddress:item 4 of fieldLines, macAddress:item 5 of fieldLines, pingCount:item 6 of fieldLines} my validatePcRecord(pcRecord) return pcRecord end loadPc ------------------------------------------------------------------ -- Helper: addPcToConfig ------------------------------------------------------------------ on addPcToConfig(pcRecord) set configPath to my getConfigPath() set entryCount to my getPcCount() set prefix to ":PCs:" & entryCount log "DEBUG -> addPcToConfig: adding at index " & entryCount do shell script "/usr/libexec/PlistBuddy" & ¬ " -c " & quoted form of ("Add " & prefix & " dict") & ¬ " -c " & quoted form of ("Add " & prefix & ":computerName string " & computerName of pcRecord) & ¬ " -c " & quoted form of ("Add " & prefix & ":pfsenseActionsUrl string " & pfsenseActionsUrl of pcRecord) & ¬ " -c " & quoted form of ("Add " & prefix & ":broadcastAddress string " & broadcastAddress of pcRecord) & ¬ " -c " & quoted form of ("Add " & prefix & ":ipAddress string " & ipAddress of pcRecord) & ¬ " -c " & quoted form of ("Add " & prefix & ":macAddress string " & macAddress of pcRecord) & ¬ " -c " & quoted form of ("Add " & prefix & ":pingCount string " & pingCount of pcRecord) & ¬ " " & quoted form of configPath log "DEBUG -> addPcToConfig: saved " & computerName of pcRecord end addPcToConfig ------------------------------------------------------------------ -- Helper: updatePcInConfig ------------------------------------------------------------------ on updatePcInConfig(originalName, pcRecord) set idx to my findPcIndex(originalName) if idx is -1 then error "PC not found: " & originalName end if set configPath to my getConfigPath() set prefix to ":PCs:" & idx log "DEBUG -> updatePcInConfig: updating index " & idx do shell script "/usr/libexec/PlistBuddy" & ¬ " -c " & quoted form of ("Set " & prefix & ":computerName " & computerName of pcRecord) & ¬ " -c " & quoted form of ("Set " & prefix & ":pfsenseActionsUrl " & pfsenseActionsUrl of pcRecord) & ¬ " -c " & quoted form of ("Set " & prefix & ":broadcastAddress " & broadcastAddress of pcRecord) & ¬ " -c " & quoted form of ("Set " & prefix & ":ipAddress " & ipAddress of pcRecord) & ¬ " -c " & quoted form of ("Set " & prefix & ":macAddress " & macAddress of pcRecord) & ¬ " -c " & quoted form of ("Set " & prefix & ":pingCount " & pingCount of pcRecord) & ¬ " " & quoted form of configPath log "DEBUG -> updatePcInConfig: saved " & computerName of pcRecord end updatePcInConfig ------------------------------------------------------------------ -- Helper: deletePcFromConfig ------------------------------------------------------------------ on deletePcFromConfig(targetName) set idx to my findPcIndex(targetName) if idx is -1 then error "PC not found: " & targetName end if set configPath to my getConfigPath() log "DEBUG -> deletePcFromConfig: deleting index " & idx do shell script "/usr/libexec/PlistBuddy -c " & quoted form of ("Delete :PCs:" & idx) & " " & quoted form of configPath log "DEBUG -> deletePcFromConfig: deleted " & targetName end deletePcFromConfig ------------------------------------------------------------------ -- Helper: getAccessToken ------------------------------------------------------------------ on getAccessToken(pcName) set keychainService to "Wake on LAN via pfSense Actions" log "DEBUG -> getAccessToken: looking up Keychain (service=" & keychainService & ", account=" & pcName & ")" -- Try to read the token from Keychain try set theToken to my doShellResponsive("security find-generic-password -s " & quoted form of keychainService & " -a " & quoted form of pcName & " -w") log "DEBUG -> getAccessToken: found token in Keychain" return theToken on error log "DEBUG -> getAccessToken: token not found in Keychain, prompting user" end try return my promptForAccessToken(pcName, "Enter the pfSense Actions access token for " & pcName & ":") end getAccessToken ------------------------------------------------------------------ -- Helper: promptForAccessToken ------------------------------------------------------------------ on promptForAccessToken(pcName, promptText) repeat set userResponse to display dialog promptText & return & return & "Create it in the pfSense Actions console under Access tokens, with the \"wol:execute\" and \"reachability:read\" scopes. It will be saved to your macOS Keychain." default answer "" with title notificationTitle buttons {"Cancel", "Save to Keychain"} cancel button "Cancel" default button "Save to Keychain" with hidden answer set theToken to text returned of userResponse if theToken is "" then display dialog "Access token cannot be empty." with icon stop buttons {"OK"} default button "OK" else if not my matchesPattern(theToken, accessTokenPattern) then display dialog "That doesn't look like a pfSense Actions access token. Tokens start with \"pfa_\", and API keys from pfSense Actions 1.x no longer work." with icon stop buttons {"OK"} default button "OK" else exit repeat end if end repeat my yieldForUi(0.2) -- Save the token to Keychain my setAccessToken(pcName, theToken) return theToken end promptForAccessToken ------------------------------------------------------------------ -- Helper: setAccessToken ------------------------------------------------------------------ on setAccessToken(pcName, theToken) set keychainService to "Wake on LAN via pfSense Actions" log "DEBUG -> setAccessToken: saving token to Keychain for " & pcName my doShellResponsive("security add-generic-password -U -s " & quoted form of keychainService & " -a " & quoted form of pcName & " -w " & quoted form of theToken) log "DEBUG -> setAccessToken: token saved successfully" end setAccessToken ------------------------------------------------------------------ -- Helper: deleteAccessToken ------------------------------------------------------------------ on deleteAccessToken(pcName) set keychainService to "Wake on LAN via pfSense Actions" log "DEBUG -> deleteAccessToken: deleting token from Keychain for " & pcName try my doShellResponsive("security delete-generic-password -s " & quoted form of keychainService & " -a " & quoted form of pcName) log "DEBUG -> deleteAccessToken: token deleted" on error log "DEBUG -> deleteAccessToken: token not found (already removed)" end try end deleteAccessToken ------------------------------------------------------------------ -- Helper: replaceAccessToken ------------------------------------------------------------------ on replaceAccessToken(pcName, response) if httpStatus of response is "403" then set problemText to "The access token for " & pcName & " is missing a scope. It needs both \"wol:execute\" and \"reachability:read\"." else set problemText to "pfSense Actions didn't accept the access token for " & pcName & ". It may have expired or been revoked, or it may be an API key from pfSense Actions 1.x." end if display dialog problemText with title notificationTitle buttons {"Cancel", "Replace Token"} cancel button "Cancel" default button "Replace Token" with icon caution my yieldForUi(0.2) return my promptForAccessToken(pcName, "Enter a new pfSense Actions access token for " & pcName & ":") end replaceAccessToken ------------------------------------------------------------------ -- Helper: matchesPattern ------------------------------------------------------------------ on matchesPattern(theText, thePattern) try do shell script "printf '%s' " & quoted form of theText & " | grep -qE " & quoted form of thePattern return true on error return false end try end matchesPattern ------------------------------------------------------------------ -- Helper: validatePcRecord ------------------------------------------------------------------ on validatePcRecord(pcRecord) set pcName to computerName of pcRecord if not my matchesPattern(pfsenseActionsUrl of pcRecord, baseUrlPattern) then error "Configuration for \"" & pcName & "\" has an invalid URL. It must be the HTTPS address of pfSense Actions without a path (e.g. https://actions.example.com). Please edit this PC to fix it." end if if not my matchesPattern(broadcastAddress of pcRecord, "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$") then error "Configuration for \"" & pcName & "\" has an invalid broadcast address. Please edit this PC to fix it." end if if not my matchesPattern(ipAddress of pcRecord, "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$") then error "Configuration for \"" & pcName & "\" has an invalid IP address. Please edit this PC to fix it." end if if not my matchesPattern(macAddress of pcRecord, "^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$") then error "Configuration for \"" & pcName & "\" has an invalid MAC address. Please edit this PC to fix it." end if if not my matchesPattern(pingCount of pcRecord, "^[1-9][0-9]*$") then error "Configuration for \"" & pcName & "\" has an invalid boot wait. Please edit this PC to fix it." end if if (pingCount of pcRecord as integer) > maximumBootWaitSeconds then error "Configuration for \"" & pcName & "\" has a boot wait over " & maximumBootWaitSeconds & " seconds. Please edit this PC to fix it." end if end validatePcRecord ------------------------------------------------------------------ -- Helper: applicationPathForBundleId ------------------------------------------------------------------ on applicationPathForBundleId(bundleId) set applicationDirectories to current application's NSSearchPathForDirectoriesInDomains(current application's NSApplicationDirectory, current application's NSAllDomainsMask, true) set fileManager to current application's NSFileManager's defaultManager() repeat with applicationDirectory in applicationDirectories set directoryUrl to current application's NSURL's fileURLWithPath:applicationDirectory set appEnumerator to fileManager's enumeratorAtURL:directoryUrl includingPropertiesForKeys:{} options:6 errorHandler:(missing value) if appEnumerator is not missing value then repeat set appUrl to appEnumerator's nextObject() if appUrl is missing value then exit repeat if (appUrl's pathExtension() as text) is "app" then set appBundle to current application's NSBundle's bundleWithURL:appUrl if appBundle is not missing value then set discoveredBundleId to appBundle's bundleIdentifier() if discoveredBundleId is not missing value and (discoveredBundleId as text) is bundleId then return appUrl's |path|() as text end if end if end if end repeat end if end repeat return "" end applicationPathForBundleId ------------------------------------------------------------------ -- Helper: getInstalledApps ------------------------------------------------------------------ on getInstalledApps(candidates) log "DEBUG -> getInstalledApps: checking " & (count of candidates) & " candidates" set appNames to {} set appBundleIDs to {} repeat with pair in candidates set appName to item 1 of pair set appBundleID to item 2 of pair try if my applicationPathForBundleId(appBundleID) is not "" then log "DEBUG -> getInstalledApps: found " & appName set end of appNames to appName set end of appBundleIDs to appBundleID end if end try end repeat log "DEBUG -> getInstalledApps: " & (count of appNames) & " installed" return {appNames:appNames, appBundleIDs:appBundleIDs} end getInstalledApps ------------------------------------------------------------------ -- Helper: lowercaseText ------------------------------------------------------------------ on lowercaseText(theText) return ((current application's NSString's stringWithString:theText)'s lowercaseString()) as text end lowercaseText ------------------------------------------------------------------ -- Helper: apiUrl ------------------------------------------------------------------ on apiUrl(baseUrl, endpoint) set trimmedUrl to baseUrl as text repeat while trimmedUrl ends with "/" set trimmedUrl to text 1 thru -2 of trimmedUrl end repeat return trimmedUrl & endpoint end apiUrl ------------------------------------------------------------------ -- Helper: errorDetails ------------------------------------------------------------------ on errorDetails(responseBody) -- pfSense Actions answers errors with {"error": {"code": "...", "message": "..."}} set errorCode to "" set errorMessage to "" try set bodyData to (current application's NSString's stringWithString:responseBody)'s dataUsingEncoding:(current application's NSUTF8StringEncoding) set parsedBody to current application's NSJSONSerialization's JSONObjectWithData:bodyData options:0 |error|:(missing value) if parsedBody is not missing value and ((parsedBody's isKindOfClass:(current application's NSDictionary)) as boolean) then set errorObject to parsedBody's objectForKey:"error" if errorObject is not missing value and ((errorObject's isKindOfClass:(current application's NSDictionary)) as boolean) then set codeValue to errorObject's objectForKey:"code" set messageValue to errorObject's objectForKey:"message" if codeValue is not missing value then set errorCode to codeValue as text if messageValue is not missing value then set errorMessage to messageValue as text end if end if end try return {errorCode:errorCode, errorMessage:errorMessage} end errorDetails ------------------------------------------------------------------ -- Helper: describeFailure ------------------------------------------------------------------ on describeFailure(response) set details to my errorDetails(responseBody of response) if errorMessage of details is not "" then return errorMessage of details & " (HTTP " & httpStatus of response & ")" end if if responseBody of response is not "" then return "HTTP " & httpStatus of response & ": " & responseBody of response end if return "HTTP " & httpStatus of response end describeFailure ------------------------------------------------------------------ -- Helper: authenticatedPost ------------------------------------------------------------------ on authenticatedPost(endpoint, requestBody, theToken, theBaseUrl, maxTime) log "DEBUG -> authenticatedPost: " & endpoint set connectionErrorMessage to "Could not connect to " & theBaseUrl & "." & return & return & "Please check the URL and your network connection." -- Defense-in-depth: only write tokens that can't break curl config parsing if not my matchesPattern(theToken, accessTokenPattern) then error "The saved access token isn't a pfSense Actions access token." set authConfigPath to do shell script "mktemp" try -- Writes in place, so the file keeps the owner-only permissions that mktemp gave it set authConfig to current application's NSString's stringWithString:("header = \"Authorization: Bearer " & theToken & "\"") set didWrite to authConfig's writeToFile:authConfigPath atomically:false encoding:(current application's NSUTF8StringEncoding) |error|:(missing value) if not (didWrite as boolean) then error "Could not write the curl config file." set curlResult to my doShellResponsive("curl --connect-timeout 10 --max-time " & maxTime & " --config " & quoted form of authConfigPath & " -s -w '\\n%{http_code}' -X POST " & quoted form of (my apiUrl(theBaseUrl, endpoint)) & " -H 'Content-Type: application/json' -d " & quoted form of requestBody) do shell script "rm -f " & quoted form of authConfigPath on error errMsg number errNum do shell script "rm -f " & quoted form of authConfigPath if errNum is -128 then error errMsg number errNum display dialog connectionErrorMessage with icon stop buttons {"OK"} default button "OK" error number -128 end try -- Parse response set resultParagraphs to paragraphs of curlResult set httpStatus to last item of resultParagraphs if (count of resultParagraphs) > 1 then set {oldTID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, linefeed} set responseBody to (items 1 thru -2 of resultParagraphs) as text set AppleScript's text item delimiters to oldTID else set responseBody to "" end if if httpStatus is "000" then display dialog connectionErrorMessage with icon stop buttons {"OK"} default button "OK" error number -128 end if return {httpStatus:httpStatus, responseBody:responseBody} end authenticatedPost ------------------------------------------------------------------ -- Core: sendWakeOnLan ------------------------------------------------------------------ on sendWakeOnLan(pcRecord, theToken) set pcName to computerName of pcRecord log "DEBUG -> sendWakeOnLan: sending WoL request for " & pcName display notification "Attempting to power on " & pcName & " ..." with title notificationTitle -- pfSense Actions accepts MAC addresses in all lowercase or all uppercase set requestBody to "{\"broadcastAddress\": \"" & broadcastAddress of pcRecord & "\", \"macAddress\": \"" & my lowercaseText(macAddress of pcRecord) & "\"}" set limitRetries to 0 repeat set response to my authenticatedPost("/api/v1/wol", requestBody, theToken, pfsenseActionsUrl of pcRecord, 30) set responseStatus to httpStatus of response log "DEBUG -> sendWakeOnLan: httpStatus=" & responseStatus if responseStatus is "200" then log "DEBUG -> sendWakeOnLan: success" return theToken else if responseStatus is "401" or responseStatus is "403" then set theToken to my replaceAccessToken(pcName, response) else if responseStatus is "429" and limitRetries < 3 then -- A rate-limited request is rejected before pfSense runs anything, so sending it again is safe set limitRetries to limitRetries + 1 my yieldForUi(10) else set failureText to "Failed to power on " & pcName & " via Wake-on-LAN." & return & return & my describeFailure(response) display dialog failureText with icon stop buttons {"OK"} default button "OK" error number -128 end if end repeat end sendWakeOnLan ------------------------------------------------------------------ -- Core: waitForBoot ------------------------------------------------------------------ on waitForBoot(pcRecord, theToken) set pcName to computerName of pcRecord set bootWaitSeconds to (pingCount of pcRecord) as integer log "DEBUG -> waitForBoot: waiting up to " & bootWaitSeconds & " seconds for " & pcName display notification "Waiting for " & pcName & " to complete booting ..." with title notificationTitle set deadline to (current date) + bootWaitSeconds repeat -- Each ping attempt takes about 5 seconds, and one request allows up to 10 attempts set secondsLeft to deadline - (current date) set attemptCount to (secondsLeft + 4) div 5 if attemptCount > 10 then set attemptCount to 10 if attemptCount < 1 then set attemptCount to 1 set requestBody to "{\"count\": " & attemptCount & ", \"ipAddress\": \"" & ipAddress of pcRecord & "\", \"strict\": true}" set response to my authenticatedPost("/api/v1/ping", requestBody, theToken, pfsenseActionsUrl of pcRecord, (attemptCount * 10) + 30) set responseStatus to httpStatus of response set responseCode to errorCode of (my errorDetails(responseBody of response)) log "DEBUG -> waitForBoot: httpStatus=" & responseStatus & ", attempts=" & attemptCount if responseStatus is "200" then log "DEBUG -> waitForBoot: boot confirmed" return theToken else if responseStatus is "503" and responseCode is "target_unreachable" then if (current date) ≥ deadline then display dialog pcName & " didn't answer within " & bootWaitSeconds & " seconds." & return & return & "It may still be starting, or Wake-on-LAN may be turned off in its firmware or operating system." with icon stop buttons {"OK"} default button "OK" error number -128 end if else if responseStatus is "429" and (current date) < deadline then my yieldForUi(10) else if responseStatus is "401" or responseStatus is "403" then set theToken to my replaceAccessToken(pcName, response) else set failureText to "Could not determine if " & pcName & " has woken up via Wake-on-LAN." & return & return & my describeFailure(response) display dialog failureText with icon stop buttons {"OK"} default button "OK" error number -128 end if end repeat end waitForBoot ------------------------------------------------------------------ -- Core: chooseAndLaunchApp ------------------------------------------------------------------ on chooseAndLaunchApp(pcName) log "DEBUG -> chooseAndLaunchApp: detecting installed apps" set installedApps to my getInstalledApps(candidateApps) set appNames to appNames of installedApps set appBundleIDs to appBundleIDs of installedApps if (count of appNames) is 0 then display dialog "No supported remote desktop applications are installed." with icon stop buttons {"OK"} default button "OK" error number -128 end if display notification pcName & " has successfully booted! Choose an app to launch ..." with title notificationTitle set chosenApp to choose from list appNames with title notificationTitle with prompt "Select an application to open:" default items {item 1 of appNames} if chosenApp is false then error number -128 end if my yieldForUi(0.2) set chosenAppName to item 1 of chosenApp log "DEBUG -> chooseAndLaunchApp: user chose " & chosenAppName -- Find the matching bundle ID set chosenBundleID to missing value repeat with i from 1 to count of appNames if item i of appNames is chosenAppName then set chosenBundleID to item i of appBundleIDs exit repeat end if end repeat log "DEBUG -> chooseAndLaunchApp: launching " & chosenAppName & " (" & chosenBundleID & ")" my doShellResponsive("open -b " & quoted form of chosenBundleID) return chosenAppName end chooseAndLaunchApp ------------------------------------------------------------------ -- Core: runPowerOn ------------------------------------------------------------------ on runPowerOn(pcRecord) set pcName to computerName of pcRecord log "DEBUG -> runPowerOn: start for " & pcName set theToken to my getAccessToken(pcName) if not my matchesPattern(theToken, accessTokenPattern) then -- An API key saved for pfSense Actions 1.x can't be used with 2.0.0 set theToken to my replaceAccessToken(pcName, {httpStatus:"401", responseBody:""}) end if set theToken to my sendWakeOnLan(pcRecord, theToken) my waitForBoot(pcRecord, theToken) set chosenAppName to my chooseAndLaunchApp(pcName) log "DEBUG -> runPowerOn: showing completion notification" display notification chosenAppName & " has been launched." with title notificationTitle sound name notificationSound log "DEBUG -> runPowerOn: completed" end runPowerOn ------------------------------------------------------------------ -- Core: promptForPcFields ------------------------------------------------------------------ on promptForPcFields(defaults) -- Name set nameDefault to computerName of defaults repeat set userResponse to display dialog "Enter the PC name:" default answer nameDefault with title notificationTitle buttons {"Cancel", "OK"} default button "OK" if button returned of userResponse is not "OK" then error number -128 set pcName to text returned of userResponse if pcName is "" then display dialog "PC name cannot be empty." with icon stop buttons {"OK"} default button "OK" else if not my matchesPattern(pcName, "^[^\"\\\\[:cntrl:]]+$") then display dialog "PC name cannot contain quotes, backslashes, or control characters." with icon stop buttons {"OK"} default button "OK" else if pcName is managePcsLabel then display dialog "The name \"" & managePcsLabel & "\" is reserved. Please choose a different name." with icon stop buttons {"OK"} default button "OK" else if my findPcIndex(pcName) is not -1 then display dialog "A PC named \"" & pcName & "\" already exists." with icon stop buttons {"OK"} default button "OK" else exit repeat end if set nameDefault to pcName end repeat -- pfSense Actions URL set urlDefault to pfsenseActionsUrl of defaults repeat set userResponse to display dialog "Enter the HTTPS address of pfSense Actions for " & pcName & ":" & return & "(e.g. https://actions.example.com)" default answer urlDefault with title notificationTitle buttons {"Cancel", "OK"} default button "OK" if button returned of userResponse is not "OK" then error number -128 set theUrl to text returned of userResponse if theUrl is "" then display dialog "URL cannot be empty." with icon stop buttons {"OK"} default button "OK" else if not my matchesPattern(theUrl, baseUrlPattern) then display dialog "URL must be an HTTPS address without a path (e.g. https://actions.example.com)." with icon stop buttons {"OK"} default button "OK" else exit repeat end if set urlDefault to theUrl end repeat -- Access token set tokenDefault to accessToken of defaults repeat set userResponse to display dialog "Enter the pfSense Actions access token for " & pcName & ":" & return & "(needs the wol:execute and reachability:read scopes)" default answer tokenDefault with title notificationTitle buttons {"Cancel", "OK"} default button "OK" with hidden answer if button returned of userResponse is not "OK" then error number -128 set theToken to text returned of userResponse if theToken is "" then display dialog "Access token cannot be empty." with icon stop buttons {"OK"} default button "OK" else if not my matchesPattern(theToken, accessTokenPattern) then display dialog "That doesn't look like a pfSense Actions access token. Tokens start with \"pfa_\" and come from the console's Access tokens page." with icon stop buttons {"OK"} default button "OK" else exit repeat end if set tokenDefault to theToken end repeat -- Broadcast address set broadcastDefault to broadcastAddress of defaults repeat set userResponse to display dialog "Enter the broadcast address for " & pcName & ":" & return & "(e.g. 192.168.1.255)" default answer broadcastDefault with title notificationTitle buttons {"Cancel", "OK"} default button "OK" if button returned of userResponse is not "OK" then error number -128 set theBroadcast to text returned of userResponse if theBroadcast is "" then display dialog "Broadcast address cannot be empty." with icon stop buttons {"OK"} default button "OK" else if not my matchesPattern(theBroadcast, "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$") then display dialog "Invalid broadcast address format (expected: e.g. 192.168.1.255)." with icon stop buttons {"OK"} default button "OK" else exit repeat end if set broadcastDefault to theBroadcast end repeat -- IP address set ipDefault to ipAddress of defaults repeat set userResponse to display dialog "Enter the IP address for " & pcName & ":" & return & "(e.g. 192.168.1.100)" default answer ipDefault with title notificationTitle buttons {"Cancel", "OK"} default button "OK" if button returned of userResponse is not "OK" then error number -128 set theIp to text returned of userResponse if theIp is "" then display dialog "IP address cannot be empty." with icon stop buttons {"OK"} default button "OK" else if not my matchesPattern(theIp, "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$") then display dialog "Invalid IP address format (expected: e.g. 192.168.1.100)." with icon stop buttons {"OK"} default button "OK" else exit repeat end if set ipDefault to theIp end repeat -- MAC address set macDefault to macAddress of defaults repeat set userResponse to display dialog "Enter the MAC address for " & pcName & ":" & return & "(e.g. aa:bb:cc:dd:ee:ff)" default answer macDefault with title notificationTitle buttons {"Cancel", "OK"} default button "OK" if button returned of userResponse is not "OK" then error number -128 set theMac to text returned of userResponse if theMac is "" then display dialog "MAC address cannot be empty." with icon stop buttons {"OK"} default button "OK" else if not my matchesPattern(theMac, "^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$") then display dialog "Invalid MAC address format (expected: e.g. aa:bb:cc:dd:ee:ff)." with icon stop buttons {"OK"} default button "OK" else exit repeat end if set macDefault to theMac end repeat -- Boot wait (stored as pingCount, in seconds) set bootWaitDefault to pingCount of defaults repeat set userResponse to display dialog "Enter how long to wait for " & pcName & " to boot, in seconds:" & return & "(1 to " & maximumBootWaitSeconds & ")" default answer bootWaitDefault with title notificationTitle buttons {"Cancel", "OK"} default button "OK" if button returned of userResponse is not "OK" then error number -128 set theBootWait to text returned of userResponse if theBootWait is "" then display dialog "Boot wait cannot be empty." with icon stop buttons {"OK"} default button "OK" else if not my matchesPattern(theBootWait, "^[1-9][0-9]*$") then display dialog "Boot wait must be a whole number of seconds." with icon stop buttons {"OK"} default button "OK" else if (theBootWait as integer) > maximumBootWaitSeconds then display dialog "Boot wait cannot exceed " & maximumBootWaitSeconds & " seconds (10 minutes)." with icon stop buttons {"OK"} default button "OK" else exit repeat end if set bootWaitDefault to theBootWait end repeat set pcRecord to {computerName:pcName, pfsenseActionsUrl:theUrl, broadcastAddress:theBroadcast, ipAddress:theIp, macAddress:theMac, pingCount:theBootWait} return {pcRecord:pcRecord, accessToken:theToken} end promptForPcFields ------------------------------------------------------------------ -- Core: runAddPc ------------------------------------------------------------------ on runAddPc() log "DEBUG -> runAddPc: start" set emptyDefaults to {computerName:"", pfsenseActionsUrl:"", accessToken:"", broadcastAddress:"", ipAddress:"", macAddress:"", pingCount:"60"} set promptResult to my promptForPcFields(emptyDefaults) set pcRecord to pcRecord of promptResult set theToken to accessToken of promptResult set pcName to computerName of pcRecord my yieldForUi(0.2) -- Save to Keychain first (a dangling token is safer than a tokenless config entry) my setAccessToken(pcName, theToken) try my addPcToConfig(pcRecord) on error errMsg number errNum my deleteAccessToken(pcName) error errMsg number errNum end try display notification "Added \"" & pcName & "\" to configuration." with title notificationTitle log "DEBUG -> runAddPc: completed" end runAddPc ------------------------------------------------------------------ -- Core: runEditPc ------------------------------------------------------------------ on runEditPc() log "DEBUG -> runEditPc: start" repeat set pcNames to my loadPcNames() if (count of pcNames) is 0 then display dialog "No PCs configured to edit." with icon stop buttons {"OK"} default button "OK" return end if set chosenPc to choose from list pcNames with title notificationTitle with prompt "Select a PC to edit:" default items {item 1 of pcNames} if chosenPc is false then exit repeat set targetName to item 1 of chosenPc set pcRecord to my loadPc(targetName) set originalName to computerName of pcRecord set pendingAccessToken to "" -- Field picker loop set fieldChoices to {"Name", "URL", "Access Token", "Broadcast Address", "IP Address", "MAC Address", "Boot Wait", "Done"} set editCancelled to false repeat set chosenField to choose from list fieldChoices with title notificationTitle with prompt "Editing \"" & (computerName of pcRecord) & "\". Select a field to edit:" default items {"Done"} if chosenField is false then set editCancelled to true exit repeat end if set fieldName to item 1 of chosenField if fieldName is "Done" then exit repeat else if fieldName is "Name" then set editDefault to computerName of pcRecord repeat set userResponse to display dialog "Enter the new PC name:" default answer editDefault with title notificationTitle buttons {"Cancel", "OK"} default button "OK" if button returned of userResponse is not "OK" then exit repeat set newValue to text returned of userResponse if newValue is "" then exit repeat else if not my matchesPattern(newValue, "^[^\"\\\\[:cntrl:]]+$") then display dialog "PC name cannot contain quotes, backslashes, or control characters." with icon stop buttons {"OK"} default button "OK" set editDefault to newValue else if newValue is managePcsLabel then display dialog "The name \"" & managePcsLabel & "\" is reserved. Please choose a different name." with icon stop buttons {"OK"} default button "OK" set editDefault to newValue else if newValue is not (computerName of pcRecord) and my findPcIndex(newValue) is not -1 then display dialog "A PC named \"" & newValue & "\" already exists." with icon stop buttons {"OK"} default button "OK" set editDefault to newValue else set computerName of pcRecord to newValue exit repeat end if end repeat else if fieldName is "URL" then set editDefault to pfsenseActionsUrl of pcRecord repeat set userResponse to display dialog "Enter the new pfSense Actions URL:" default answer editDefault with title notificationTitle buttons {"Cancel", "OK"} default button "OK" if button returned of userResponse is not "OK" then exit repeat set newValue to text returned of userResponse if newValue is "" then exit repeat else if not my matchesPattern(newValue, baseUrlPattern) then display dialog "URL must be an HTTPS address without a path (e.g. https://actions.example.com)." with icon stop buttons {"OK"} default button "OK" set editDefault to newValue else set pfsenseActionsUrl of pcRecord to newValue exit repeat end if end repeat else if fieldName is "Access Token" then set editDefault to "" repeat set userResponse to display dialog "Enter the new access token:" default answer editDefault with title notificationTitle buttons {"Cancel", "OK"} default button "OK" with hidden answer if button returned of userResponse is not "OK" then exit repeat set newValue to text returned of userResponse if newValue is "" then exit repeat else if not my matchesPattern(newValue, accessTokenPattern) then display dialog "That doesn't look like a pfSense Actions access token. Tokens start with \"pfa_\" and come from the console's Access tokens page." with icon stop buttons {"OK"} default button "OK" set editDefault to newValue else set pendingAccessToken to newValue exit repeat end if end repeat else if fieldName is "Broadcast Address" then set editDefault to broadcastAddress of pcRecord repeat set userResponse to display dialog "Enter the new broadcast address:" default answer editDefault with title notificationTitle buttons {"Cancel", "OK"} default button "OK" if button returned of userResponse is not "OK" then exit repeat set newValue to text returned of userResponse if newValue is "" then exit repeat else if not my matchesPattern(newValue, "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$") then display dialog "Invalid broadcast address format (expected: e.g. 192.168.1.255)." with icon stop buttons {"OK"} default button "OK" set editDefault to newValue else set broadcastAddress of pcRecord to newValue exit repeat end if end repeat else if fieldName is "IP Address" then set editDefault to ipAddress of pcRecord repeat set userResponse to display dialog "Enter the new IP address:" default answer editDefault with title notificationTitle buttons {"Cancel", "OK"} default button "OK" if button returned of userResponse is not "OK" then exit repeat set newValue to text returned of userResponse if newValue is "" then exit repeat else if not my matchesPattern(newValue, "^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$") then display dialog "Invalid IP address format (expected: e.g. 192.168.1.100)." with icon stop buttons {"OK"} default button "OK" set editDefault to newValue else set ipAddress of pcRecord to newValue exit repeat end if end repeat else if fieldName is "MAC Address" then set editDefault to macAddress of pcRecord repeat set userResponse to display dialog "Enter the new MAC address:" default answer editDefault with title notificationTitle buttons {"Cancel", "OK"} default button "OK" if button returned of userResponse is not "OK" then exit repeat set newValue to text returned of userResponse if newValue is "" then exit repeat else if not my matchesPattern(newValue, "^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$") then display dialog "Invalid MAC address format (expected: e.g. aa:bb:cc:dd:ee:ff)." with icon stop buttons {"OK"} default button "OK" set editDefault to newValue else set macAddress of pcRecord to newValue exit repeat end if end repeat else if fieldName is "Boot Wait" then set editDefault to pingCount of pcRecord repeat set userResponse to display dialog "Enter the new boot wait, in seconds:" default answer editDefault with title notificationTitle buttons {"Cancel", "OK"} default button "OK" if button returned of userResponse is not "OK" then exit repeat set newValue to text returned of userResponse if newValue is "" then exit repeat else if not my matchesPattern(newValue, "^[1-9][0-9]*$") then display dialog "Boot wait must be a whole number of seconds." with icon stop buttons {"OK"} default button "OK" set editDefault to newValue else if (newValue as integer) > maximumBootWaitSeconds then display dialog "Boot wait cannot exceed " & maximumBootWaitSeconds & " seconds (10 minutes)." with icon stop buttons {"OK"} default button "OK" set editDefault to newValue else set pingCount of pcRecord to newValue exit repeat end if end repeat end if end repeat if editCancelled then -- Discard changes, loop back to PC selector else my yieldForUi(0.2) -- Handle Keychain updates before config (a dangling token is safer than a tokenless config entry) set newName to computerName of pcRecord if newName is not originalName then if pendingAccessToken is not "" then -- New token provided + rename: save under new name first log "DEBUG -> runEditPc: name changed + new access token; saving under " & newName my setAccessToken(newName, pendingAccessToken) else -- Rename only: copy existing token to new name first log "DEBUG -> runEditPc: name changed; migrating token from " & originalName & " to " & newName try set keychainService to "Wake on LAN via pfSense Actions" set existingToken to my doShellResponsive("security find-generic-password -s " & quoted form of keychainService & " -a " & quoted form of originalName & " -w") my setAccessToken(newName, existingToken) on error log "DEBUG -> runEditPc: no existing token to migrate" end try end if else if pendingAccessToken is not "" then -- Name unchanged, but access token was edited log "DEBUG -> runEditPc: saving new access token for " & newName my setAccessToken(newName, pendingAccessToken) end if -- Save changes to config my updatePcInConfig(originalName, pcRecord) -- Clean up old Keychain entry after successful config update if newName is not originalName then my deleteAccessToken(originalName) end if display notification "Updated \"" & newName & "\" configuration." with title notificationTitle log "DEBUG -> runEditPc: completed" return end if end repeat log "DEBUG -> runEditPc: done" end runEditPc ------------------------------------------------------------------ -- Core: runDeletePc ------------------------------------------------------------------ on runDeletePc() log "DEBUG -> runDeletePc: start" repeat set pcNames to my loadPcNames() if (count of pcNames) is 0 then display dialog "No PCs configured to delete." with icon stop buttons {"OK"} default button "OK" return end if set chosenPc to choose from list pcNames with title notificationTitle with prompt "Select a PC to delete:" default items {item 1 of pcNames} if chosenPc is false then exit repeat set targetName to item 1 of chosenPc -- Show details before confirming set pcRecord to my loadPc(targetName) set detailText to "Name: " & computerName of pcRecord & return & ¬ "URL: " & pfsenseActionsUrl of pcRecord & return & ¬ "Broadcast: " & broadcastAddress of pcRecord & return & ¬ "IP: " & ipAddress of pcRecord & return & ¬ "MAC: " & macAddress of pcRecord & return & ¬ "Boot Wait: " & pingCount of pcRecord & " seconds" try display dialog "Delete this PC?" & return & return & detailText & return & return & "This will also remove its access token from Keychain." with title notificationTitle buttons {"Cancel", "Delete"} cancel button "Cancel" default button "Cancel" with icon stop -- If we get here, user clicked Delete my yieldForUi(0.2) my deletePcFromConfig(targetName) my deleteAccessToken(targetName) display notification "Deleted \"" & targetName & "\" from configuration." with title notificationTitle log "DEBUG -> runDeletePc: completed" on error errMsg number errNum if errMsg contains "User canceled" or errNum is equal to -128 then -- Cancel at confirmation: loop back to PC selector else error errMsg number errNum end if end try end repeat log "DEBUG -> runDeletePc: done" end runDeletePc ------------------------------------------------------------------ -- Core: runManagePcs ------------------------------------------------------------------ on runManagePcs() log "DEBUG -> runManagePcs: start" set manageChoices to {"Add PC", "Edit PC", "Delete PC"} repeat set chosenAction to choose from list manageChoices with title notificationTitle with prompt "Manage PCs:" default items {"Add PC"} if chosenAction is false then exit repeat set actionName to item 1 of chosenAction try if actionName is "Add PC" then my runAddPc() else if actionName is "Edit PC" then my runEditPc() else if actionName is "Delete PC" then my runDeletePc() end if on error errMsg number errNum if errMsg contains "User canceled" or errNum is equal to -128 then -- Cancel within sub-flow: return to manage menu else error errMsg number errNum end if end try end repeat log "DEBUG -> runManagePcs: done" end runManagePcs ------------------------------------------------------------------ -- Core: runMain ------------------------------------------------------------------ on runMain() log "DEBUG -> runMain: start" repeat set pcNames to my loadPcNames() if (count of pcNames) is 0 then -- Cancel here exits the script (nothing to go back to) display dialog "No PCs configured yet. Would you like to add one?" with title notificationTitle buttons {"Cancel", "Add PC"} cancel button "Cancel" default button "Add PC" try my runAddPc() on error errMsg number errNum if errMsg contains "User canceled" or errNum is equal to -128 then -- Cancel within Add flow: loop back else error errMsg number errNum end if end try else -- Build menu with PC names + manage option set menuItems to pcNames & {managePcsLabel} set chosenItem to choose from list menuItems with title notificationTitle with prompt "Select a PC to wake, or manage your PCs:" default items {item 1 of menuItems} if chosenItem is false then exit repeat end if set selectedItem to item 1 of chosenItem my yieldForUi(0.2) if selectedItem is managePcsLabel then my runManagePcs() else try set pcRecord to my loadPc(selectedItem) my runPowerOn(pcRecord) exit repeat on error errMsg number errNum if errMsg contains "User canceled" or errNum is equal to -128 then -- Cancel from power-on flow: return to main menu else error errMsg number errNum end if end try end if end if end repeat log "DEBUG -> runMain: done" end runMain ------------------------------------------------------------------ -- Entry: run ------------------------------------------------------------------ on run argv if (count of argv) > 0 then display dialog "This script must be run interactively. Command-line arguments are not supported." buttons {"OK"} with icon stop default button "OK" return end if try log "DEBUG -> run: start" my runMain() log "DEBUG -> run: done" on error errMsg number errNum if errMsg contains "User canceled" or errNum is equal to -128 then return end if display dialog errMsg buttons {"OK"} with icon stop default button "OK" end try end run