summaryrefslogtreecommitdiffstats
path: root/cmd/ship/init.go
blob: b495702a4e06bff2b3f20c106e9eda696b0392b8 (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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package main

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"

	"github.com/bdw/ship/internal/ssh"
	"github.com/bdw/ship/internal/state"
	"github.com/bdw/ship/internal/templates"
	"github.com/spf13/cobra"
)

var initCmd = &cobra.Command{
	Use:   "init <name>",
	Short: "Initialize a git-deployed project",
	Long: `Create a bare git repo on the VPS and generate local .ship/ config files.

Pushing to the remote triggers an automatic docker build and deploy (for apps)
or a static file checkout (for static sites). If no Dockerfile is present in an
app repo, pushes are accepted without triggering a deploy.

Examples:
  # Initialize an app (Docker-based)
  ship init myapp

  # Initialize with a custom domain
  ship init myapp --domain custom.example.com

  # Initialize a static site
  ship init mysite --static

  # Initialize a public repo (cloneable via go get / git clone over HTTPS)
  ship init mylib --public`,
	Args: cobra.ExactArgs(1),
	RunE: runInit,
}

func init() {
	initCmd.Flags().Bool("static", false, "Initialize as static site")
	initCmd.Flags().Bool("public", false, "Make repo publicly cloneable over HTTPS (for go get)")
	initCmd.Flags().String("domain", "", "Custom domain (default: name.basedomain)")
}

func runInit(cmd *cobra.Command, args []string) error {
	name := args[0]
	if err := validateName(name); err != nil {
		return err
	}
	static, _ := cmd.Flags().GetBool("static")
	public, _ := cmd.Flags().GetBool("public")
	domain, _ := cmd.Flags().GetString("domain")

	st, err := state.Load()
	if err != nil {
		return fmt.Errorf("error loading state: %w", err)
	}

	host := hostFlag
	if host == "" {
		host = st.GetDefaultHost()
	}
	if host == "" {
		return fmt.Errorf("--host is required")
	}

	hostState := st.GetHost(host)
	if !hostState.GitSetup {
		return fmt.Errorf("git deployment not set up on %s (run 'ship host init --base-domain example.com' first)", host)
	}

	// Check if app already exists
	if _, err := st.GetApp(host, name); err == nil {
		return fmt.Errorf("app %s already exists", name)
	}

	appType := "git-app"
	if static {
		appType = "git-static"
	}

	// Resolve domain
	if domain == "" && hostState.BaseDomain != "" {
		domain = name + "." + hostState.BaseDomain
	}
	if domain == "" {
		return fmt.Errorf("--domain required (or configure base domain)")
	}

	// Allocate port for apps only
	port := 0
	if !static {
		port = st.AllocatePort(host)
	}

	fmt.Printf("Initializing %s: %s\n", appType, name)

	client, err := ssh.Connect(host)
	if err != nil {
		return fmt.Errorf("error connecting to VPS: %w", err)
	}
	defer client.Close()

	// Create bare repo
	fmt.Println("-> Creating bare git repo...")
	repo := fmt.Sprintf("/srv/git/%s.git", name)
	if _, err := client.RunSudo(fmt.Sprintf("sudo -u git git init --bare -b main %s", repo)); err != nil {
		return fmt.Errorf("error creating bare repo: %w", err)
	}

	if public {
		if _, err := client.RunSudo(fmt.Sprintf("sudo -u git touch %s/git-daemon-export-ok", repo)); err != nil {
			return fmt.Errorf("error setting repo public: %w", err)
		}
	}

	if static {
		// Create web root
		fmt.Println("-> Creating web root...")
		if _, err := client.RunSudo(fmt.Sprintf("mkdir -p /var/www/%s", name)); err != nil {
			return fmt.Errorf("error creating web root: %w", err)
		}
		if _, err := client.RunSudo(fmt.Sprintf("chown git:git /var/www/%s", name)); err != nil {
			return fmt.Errorf("error setting web root ownership: %w", err)
		}

		// Write post-receive hook
		fmt.Println("-> Writing post-receive hook...")
		hookContent, err := templates.PostReceiveHookStatic(map[string]string{
			"Name": name,
		})
		if err != nil {
			return fmt.Errorf("error generating hook: %w", err)
		}
		if err := writeHook(client, repo, hookContent); err != nil {
			return err
		}
	} else {
		// Create env file
		fmt.Println("-> Creating environment file...")
		envContent := fmt.Sprintf("PORT=%d\nDATA_DIR=/data\n", port)
		envPath := fmt.Sprintf("/etc/ship/env/%s.env", name)
		if err := client.WriteSudoFile(envPath, envContent); err != nil {
			return fmt.Errorf("error creating env file: %w", err)
		}

		// Write post-receive hook (handles dir creation on first push)
		fmt.Println("-> Writing post-receive hook...")
		hookContent, err := templates.PostReceiveHook(map[string]string{
			"Name": name,
		})
		if err != nil {
			return fmt.Errorf("error generating hook: %w", err)
		}
		if err := writeHook(client, repo, hookContent); err != nil {
			return err
		}
	}

	// Save state
	st.AddApp(host, name, &state.App{
		Type:   appType,
		Domain: domain,
		Port:   port,
		Repo:   repo,
		Public: public,
	})
	if err := st.Save(); err != nil {
		return fmt.Errorf("error saving state: %w", err)
	}

	// Generate local .ship/ files
	fmt.Println("-> Generating local .ship/ config...")
	if err := os.MkdirAll(".ship", 0755); err != nil {
		return fmt.Errorf("error creating .ship directory: %w", err)
	}

	if static {
		caddyContent, err := templates.DefaultStaticCaddy(map[string]string{
			"Domain": domain,
			"Name":   name,
		})
		if err != nil {
			return fmt.Errorf("error generating Caddyfile: %w", err)
		}
		if err := os.WriteFile(filepath.Join(".ship", "Caddyfile"), []byte(caddyContent), 0644); err != nil {
			return fmt.Errorf("error writing Caddyfile: %w", err)
		}
	} else {
		caddyContent, err := templates.DefaultAppCaddy(map[string]string{
			"Domain": domain,
			"Port":   strconv.Itoa(port),
		})
		if err != nil {
			return fmt.Errorf("error generating Caddyfile: %w", err)
		}
		if err := os.WriteFile(filepath.Join(".ship", "Caddyfile"), []byte(caddyContent), 0644); err != nil {
			return fmt.Errorf("error writing Caddyfile: %w", err)
		}

		serviceContent, err := templates.DockerService(map[string]string{
			"Name": name,
			"Port": strconv.Itoa(port),
		})
		if err != nil {
			return fmt.Errorf("error generating service file: %w", err)
		}
		if err := os.WriteFile(filepath.Join(".ship", "service"), []byte(serviceContent), 0644); err != nil {
			return fmt.Errorf("error writing service file: %w", err)
		}
	}

	// Initialize local git repo if needed
	if _, err := os.Stat(".git"); os.IsNotExist(err) {
		fmt.Println("-> Initializing git repo...")
		gitInit := exec.Command("git", "init")
		gitInit.Stdout = os.Stdout
		gitInit.Stderr = os.Stderr
		if err := gitInit.Run(); err != nil {
			return fmt.Errorf("error initializing git repo: %w", err)
		}
	}

	// Add origin remote (replace if it already exists)
	sshHost := host
	remoteURL := fmt.Sprintf("git@%s:%s", sshHost, repo)
	exec.Command("git", "remote", "remove", "origin").Run() // ignore error if not exists
	addRemote := exec.Command("git", "remote", "add", "origin", remoteURL)
	if err := addRemote.Run(); err != nil {
		return fmt.Errorf("error adding git remote: %w", err)
	}

	fmt.Printf("\nProject initialized: %s\n", name)
	fmt.Println("\nGenerated:")
	fmt.Println("  .ship/Caddyfile    — Caddy config (edit to customize routing)")
	if !static {
		fmt.Println("  .ship/service      — systemd unit (edit to customize resources, ports)")
	}
	fmt.Println("\nNext steps:")
	if static {
		fmt.Println("  git add .ship/")
	} else {
		fmt.Println("  git add .ship/ Dockerfile")
	}
	fmt.Println("  git commit -m \"initial deploy\"")
	fmt.Println("  git push origin main")
	if !static {
		fmt.Println("\n  (No Dockerfile? Just push — deploy is skipped until one is added.)")
	}

	return nil
}

func writeHook(client *ssh.Client, repo, content string) error {
	hookPath := fmt.Sprintf("%s/hooks/post-receive", repo)
	if err := client.WriteSudoFile(hookPath, content); err != nil {
		return fmt.Errorf("error writing hook: %w", err)
	}
	if _, err := client.RunSudo(fmt.Sprintf("chmod +x %s", hookPath)); err != nil {
		return fmt.Errorf("error making hook executable: %w", err)
	}
	if _, err := client.RunSudo(fmt.Sprintf("chown git:git %s", hookPath)); err != nil {
		return fmt.Errorf("error setting hook ownership: %w", err)
	}
	return nil
}