@@ -17,7 +17,6 @@ package config
1717import (
1818 // we need this for the ArduinoCreateAgent.plist in this package
1919 _ "embed"
20- "fmt"
2120 "os"
2221 "os/exec"
2322 "text/template"
@@ -34,18 +33,36 @@ func getLaunchdAgentPath() *paths.Path {
3433 return GetDefaultHomeDir ().Join ("Library" , "LaunchAgents" , "ArduinoCreateAgent.plist" )
3534}
3635
37- // WritePlistFile function will write the required plist file to $HOME/Library/LaunchAgents/ArduinoCreateAgent.plist
38- // it will return nil in case of success,
39- // it will error if the file is already there or in any other case
40- func WritePlistFile () error {
41-
36+ // InstallPlistFile will handle the process of creating the plist file required for the autostart
37+ // and loading it using launchd
38+ func InstallPlistFile () {
4239 launchdAgentPath := getLaunchdAgentPath ()
43- if launchdAgentPath .Exist () {
40+ if ! launchdAgentPath .Exist () {
41+ err := WritePlistFile (launchdAgentPath )
42+ if err != nil {
43+ log .Error (err )
44+ } else {
45+ err = LoadLaunchdAgent () // this will load the agent: basically starting a new instance
46+ if err != nil {
47+ log .Error (err )
48+ } else {
49+ log .Info ("Quitting, another instance of the agent has been started by launchd" )
50+ os .Exit (0 )
51+ }
52+ }
53+ } else {
4454 // we already have an existing launchd plist file, so we don't have to do anything
45- return fmt .Errorf ("the autostart file %s already exists" , launchdAgentPath )
55+ log .Infof ("the autostart file %s already exists: nothing to do" , launchdAgentPath )
56+
4657 }
58+ }
4759
60+ // WritePlistFile function will write the required plist file to launchdAgentPath
61+ // it will return nil in case of success,
62+ // it will error in any other case
63+ func WritePlistFile (launchdAgentPath * paths.Path ) error {
4864 src , err := os .Executable ()
65+
4966 if err != nil {
5067 return err
5168 }
@@ -72,6 +89,18 @@ func LoadLaunchdAgent() error {
7289 return err
7390}
7491
92+ func UninstallPlistFile () {
93+ err := UnloadLaunchdAgent ()
94+ if err != nil {
95+ log .Error (err )
96+ } else {
97+ err = RemovePlistFile ()
98+ if err != nil {
99+ log .Error (err )
100+ }
101+ }
102+ }
103+
75104// UnloadLaunchdAgent will use launchctl to load the agent, will return an error if something goes wrong
76105func UnloadLaunchdAgent () error {
77106 // https://www.launchd.info/
@@ -88,5 +117,6 @@ func RemovePlistFile() error {
88117 log .Infof ("removing: %s" , launchdAgentPath )
89118 return launchdAgentPath .Remove ()
90119 }
120+ log .Infof ("the autostart file %s do not exists: nothing to do" , launchdAgentPath )
91121 return nil
92122}
0 commit comments