|
| 1 | +package cmd |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "fmt" |
| 6 | + "os/exec" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/cupcakearmy/autorestic/internal" |
| 10 | + "github.com/cupcakearmy/autorestic/internal/colors" |
| 11 | + "github.com/cupcakearmy/autorestic/internal/lock" |
| 12 | + "github.com/spf13/cobra" |
| 13 | +) |
| 14 | + |
| 15 | +var unlockCmd = &cobra.Command{ |
| 16 | + Use: "unlock", |
| 17 | + Short: "Unlock autorestic only if you are sure that no other instance is running", |
| 18 | + Long: `Unlock autorestic only if you are sure that no other instance is running. |
| 19 | +To check you can run "ps aux | grep autorestic".`, |
| 20 | + Run: func(cmd *cobra.Command, args []string) { |
| 21 | + internal.GetConfig() |
| 22 | + |
| 23 | + force, _ := cmd.Flags().GetBool("force") |
| 24 | + |
| 25 | + if !force && isAutoresticRunning() { |
| 26 | + colors.Error.Print("Another autorestic instance is running. Are you sure you want to unlock? (yes/no): ") |
| 27 | + var response string |
| 28 | + fmt.Scanln(&response) |
| 29 | + if strings.ToLower(response) != "yes" { |
| 30 | + colors.Primary.Println("Unlocking aborted.") |
| 31 | + return |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + err := lock.Unlock() |
| 36 | + if err != nil { |
| 37 | + colors.Error.Println("Could not unlock:", err) |
| 38 | + return |
| 39 | + } |
| 40 | + |
| 41 | + colors.Success.Println("Unlock successful") |
| 42 | + }, |
| 43 | +} |
| 44 | + |
| 45 | +func init() { |
| 46 | + rootCmd.AddCommand(unlockCmd) |
| 47 | + unlockCmd.Flags().Bool("force", false, "force unlock") |
| 48 | +} |
| 49 | + |
| 50 | +// isAutoresticRunning checks if autorestic is running |
| 51 | +// and returns true if it is. |
| 52 | +// It also prints the processes to stdout. |
| 53 | +func isAutoresticRunning() bool { |
| 54 | + cmd := exec.Command("sh", "-c", "ps aux | grep autorestic") |
| 55 | + var out bytes.Buffer |
| 56 | + cmd.Stdout = &out |
| 57 | + err := cmd.Run() |
| 58 | + if err != nil { |
| 59 | + return false |
| 60 | + } |
| 61 | + |
| 62 | + lines := strings.Split(out.String(), "\n") |
| 63 | + autoresticProcesses := []string{} |
| 64 | + |
| 65 | + for _, line := range lines { |
| 66 | + if strings.Contains(line, "autorestic") && !strings.Contains(line, "grep autorestic") { |
| 67 | + autoresticProcesses = append(autoresticProcesses, line) |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + if len(autoresticProcesses) > 0 { |
| 72 | + colors.Faint.Println("Found autorestic processes:") |
| 73 | + for _, proc := range autoresticProcesses { |
| 74 | + colors.Faint.Println(proc) |
| 75 | + } |
| 76 | + return true |
| 77 | + } |
| 78 | + return false |
| 79 | +} |
0 commit comments