Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
executable file 81 lines (74 sloc) 2.41 KB
#!/bin/bash
set -e -f -u -o pipefail
output_plist() {
local app="$1" label="$2"
# Set up launchd to automatically restart the app when it exits.
# https://developer.apple.com/library/content/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html
# man launchd.plist
cat <<END_OF_PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>RunAtLoad</key> <true/>
<key>KeepAlive</key> <true/>
<key>Label</key> <string>${label}</string>
<key>ProgramArguments</key>
<array>
<string>${HOME}/bin/restart-app-automatically-wrapper</string>
<string>${app}</string>
</array>
</dict>
</plist>
END_OF_PLIST
}
main() {
if [[ "$#" -ne 4 ]]; then
printf "Usage: %s DEST_FILE APP_PATH SERVICE_LABEL ACTION\\n" "$0" >&2
printf "E.g. %s %s %s %s %s\\n" "$0" "pauses.restart.plist" \
"/Applications/Pauses.app/Contents/MacOS/Pauses" "Pauses.restart" \
"start" >&2
printf "ACTION must be one of: %s\\n" \
"list load remove restart start stop unload" >&2
exit 1
fi
local DEST_FILE="$1" APP="$2" LABEL="$3" ACTION="$4"
local DEST="${HOME}/Library/LaunchAgents/${DEST_FILE}"
if launchctl list | grep -q "${LABEL}"; then
if ! diff -u "${DEST}" <(output_plist "${APP}" "${LABEL}"); then
# This will kill the app, which is really annoying, but there doesn't seem
# to be any other way to get launchd to reread the config :(
launchctl unload "${DEST}"
# Give the app some time to exit.
sleep 10
output_plist "${APP}" "${LABEL}" > "${DEST}"
launchctl load "${DEST}"
fi
fi
case "${ACTION}" in
stop)
printf "WARNING: stop is unreliable, consider using unload unstead\\n" >&2
launchctl "${ACTION}" "${LABEL}"
;;
list|remove|start)
launchctl "${ACTION}" "${LABEL}"
;;
load|unload)
launchctl "${ACTION}" "${DEST}"
;;
restart)
launchctl unload "${DEST}"
sleep 1
launchctl load "${DEST}"
launchctl start "${LABEL}"
;;
*)
printf "Unknown action: %s\\n" "${ACTION}" >&2
printf "Usage: %s ACTION\\n" "$0" >&2
printf "ACTION must be one of: %s\\n" \
"list load remove restart start stop unload" >&2
return 1
;;
esac
}
main "$@"
You can’t perform that action at this time.