summaryrefslogtreecommitdiffstats
path: root/cmd/deploy/remove.go
blob: 5a98bf3d8e1807eeb995cd8e27175a9099e25972 (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
package main

import (
	"fmt"

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

var removeCmd = &cobra.Command{
	Use:     "remove <app>",
	Aliases: []string{"rm"},
	Short:   "Remove a deployment",
	Args:    cobra.ExactArgs(1),
	RunE:    runRemove,
}

func runRemove(cmd *cobra.Command, args []string) error {
	name := args[0]

	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")
	}

	app, err := st.GetApp(host, name)
	if err != nil {
		return err
	}

	fmt.Printf("Removing deployment: %s\n", name)

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

	if app.Type == "app" {
		fmt.Println("-> Stopping service...")
		client.RunSudo(fmt.Sprintf("systemctl stop %s", name))
		client.RunSudo(fmt.Sprintf("systemctl disable %s", name))

		client.RunSudo(fmt.Sprintf("rm -f /etc/systemd/system/%s.service", name))
		client.RunSudo("systemctl daemon-reload")

		client.RunSudo(fmt.Sprintf("rm -f /usr/local/bin/%s", name))
		client.RunSudo(fmt.Sprintf("rm -rf /var/lib/%s", name))
		client.RunSudo(fmt.Sprintf("rm -f /etc/deploy/env/%s.env", name))
		client.RunSudo(fmt.Sprintf("userdel %s", name))
	} else {
		fmt.Println("-> Removing files...")
		client.RunSudo(fmt.Sprintf("rm -rf /var/www/%s", name))
	}

	fmt.Println("-> Removing Caddy config...")
	client.RunSudo(fmt.Sprintf("rm -f /etc/caddy/sites-enabled/%s.caddy", name))

	fmt.Println("-> Reloading Caddy...")
	if _, err := client.RunSudo("systemctl reload caddy"); err != nil {
		fmt.Printf("Warning: Error reloading Caddy: %v\n", err)
	}

	if err := st.RemoveApp(host, name); err != nil {
		return fmt.Errorf("error updating state: %w", err)
	}
	if err := st.Save(); err != nil {
		return fmt.Errorf("error saving state: %w", err)
	}

	fmt.Println("Deployment removed successfully")
	return nil
}