summaryrefslogtreecommitdiff
path: root/cmd/podman-mac-helper/service.go
blob: 65cd89f349a45248863cf013125d45a1eedec10a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//go:build darwin
// +build darwin

package main

import (
	"fmt"
	"io"
	"io/fs"
	"os"
	"time"

	"github.com/spf13/cobra"
)

const (
	trigger = "GO\n"
	fail    = "NO"
	success = "OK"
)

var serviceCmd = &cobra.Command{
	Use:    "service",
	Short:  "services requests",
	Long:   "services requests",
	PreRun: silentUsage,
	Run:    serviceRun,
	Hidden: true,
}

func init() {
	rootCmd.AddCommand(serviceCmd)
}

func serviceRun(cmd *cobra.Command, args []string) {
	info, err := os.Stdin.Stat()
	if err != nil || info.Mode()&fs.ModeSocket == 0 {
		fmt.Fprintln(os.Stderr, "This is an internal command that is not intended for standard terminal usage")
		os.Exit(1)
	}

	os.Exit(service())
}

func service() int {
	defer os.Stdout.Close()
	defer os.Stdin.Close()
	defer os.Stderr.Close()
	if len(os.Args) < 3 {
		fmt.Print(fail)
		return 1
	}
	target := os.Args[2]

	request := make(chan bool)
	go func() {
		buf := make([]byte, 3)
		_, err := io.ReadFull(os.Stdin, buf)
		request <- err == nil && string(buf) == trigger
	}()

	valid := false
	select {
	case valid = <-request:
	case <-time.After(5 * time.Second):
	}

	if !valid {
		fmt.Println(fail)
		return 2
	}

	err := os.Remove(dockerSock)
	if err == nil || os.IsNotExist(err) {
		err = os.Symlink(target, dockerSock)
	}

	if err != nil {
		fmt.Print(fail)
		return 3
	}

	fmt.Print(success)
	return 0
}