|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "os" |
| 6 | + "os/exec" |
| 7 | + "path/filepath" |
| 8 | + |
| 9 | + "github.com/spf13/cobra" |
| 10 | + "github.com/itzcodex24/git-guardian/internal/supervisor" |
| 11 | +) |
| 12 | + |
| 13 | +var autostartCmd = &cobra.Command{ |
| 14 | + Use: "autostart", |
| 15 | + Short: "Manage launch-at-login (launchd) autostart for guardian", |
| 16 | +} |
| 17 | + |
| 18 | +var autostartEnableCmd = &cobra.Command{ |
| 19 | + Use: "enable", |
| 20 | + Short: "Enable autostart (install launch agent and load it)", |
| 21 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 22 | + plist := supervisor.GenerateLaunchdPlist() |
| 23 | + home, _ := os.UserHomeDir() |
| 24 | + plistDir := filepath.Join(home, "Library", "LaunchAgents") |
| 25 | + if err := os.MkdirAll(plistDir, 0755); err != nil { |
| 26 | + return fmt.Errorf("failed to make launchagents dir: %w", err) |
| 27 | + } |
| 28 | + plistPath := filepath.Join(plistDir, "com.gitguardian.agent.plist") |
| 29 | + if err := os.WriteFile(plistPath, []byte(plist), 0644); err != nil { |
| 30 | + return fmt.Errorf("failed to write plist: %w", err) |
| 31 | + } |
| 32 | + exec.Command("launchctl", "load", plistPath).Run() |
| 33 | + fmt.Println("Autostart enabled. Plist:", plistPath) |
| 34 | + return nil |
| 35 | + }, |
| 36 | +} |
| 37 | + |
| 38 | +var autostartDisableCmd = &cobra.Command{ |
| 39 | + Use: "disable", |
| 40 | + Short: "Disable autostart (unload and remove launch agent)", |
| 41 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 42 | + home, _ := os.UserHomeDir() |
| 43 | + plistPath := filepath.Join(home, "Library", "LaunchAgents", "com.gitguardian.agent.plist") |
| 44 | + exec.Command("launchctl", "unload", plistPath).Run() |
| 45 | + os.Remove(plistPath) |
| 46 | + fmt.Println("Autostart disabled. Removed:", plistPath) |
| 47 | + return nil |
| 48 | + }, |
| 49 | +} |
| 50 | + |
| 51 | +func init() { |
| 52 | + autostartCmd.AddCommand(autostartEnableCmd) |
| 53 | + autostartCmd.AddCommand(autostartDisableCmd) |
| 54 | + rootCmd.AddCommand(autostartCmd) |
| 55 | +} |
0 commit comments