aboutsummaryrefslogtreecommitdiff
path: root/cmd/eno/cobra_new.go
blob: 7d4654658d0a9c8fff819f414e1124293347ec07 (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
package main

import (
	"os"
	"path/filepath"
	"strings"

	"github.com/spf13/cobra"
	"gitlab.com/whiteboardguy/eno/internal/config"
	"gitlab.com/whiteboardguy/eno/internal/crud"
	"gitlab.com/whiteboardguy/eno/internal/utils"
)

var newCmd = &cobra.Command{
	Use: "new <note>",
	Short: "create a new encrypted note",
	Args: cobra.MinimumNArgs(1),
	Run: func(cmd *cobra.Command, args []string) {

		output, err := cmd.Flags().GetString("output")
		if err != nil {
			cmd.PrintErrln("Error:", err)
			os.Exit(1)
		}

		editFlag, err := cmd.Flags().GetBool("edit")
		if err != nil {
			cmd.PrintErrln("Error:", err)
			os.Exit(1)
		}

		sshFlag, err := cmd.Flags().GetBool("ssh")
		if err != nil {
			cmd.PrintErrln("Error:", err)
			os.Exit(1)
		}

		noteName := strings.Join(args, " ")
		if output == "" {
			if strings.ContainsRune(noteName, filepath.Separator) {
				output = noteName + ".eno"
			} else {
				output = filepath.Join(config.Conf.DataDir, noteName+".eno")
			}
		}

		if _, err := os.Stat(config.Conf.DataDir); os.IsNotExist(err) {
			if err := os.MkdirAll(config.Conf.DataDir, 0700); err != nil {
				cmd.PrintErrln("Error:", err)
				os.Exit(1)
			}
			cmd.Println("Created data directory:", config.Conf.DataDir)
		}

		if _, err := os.Stat(output); err == nil {
			ok, err := utils.AskUserYesNo("file '"+output+"' already exists. Overwrite?", false)
			if err != nil {
				cmd.PrintErrln("Error:", err)
				os.Exit(1)
			}
			if !ok {
				cmd.PrintErrln("Error: write aborted")
				os.Exit(1)
			}
		}

		if sshFlag && editFlag {
			pubKeyBytes, err := os.ReadFile(config.Conf.DefaultSSHPubPath)
			if err != nil {
				cmd.PrintErrln("Error:", err)
				os.Exit(1)
			}

			err = crud.NewNoteSSHEdit(output, pubKeyBytes, config.Conf.DefaultSSHPrivPath, config.Conf.EditorString)
			if err != nil {
				cmd.PrintErrln("Error:", err)
				os.Exit(1)
			}
			return
		}

		if sshFlag {
			pubKeyBytes, err := os.ReadFile(config.Conf.DefaultSSHPubPath)
			if err != nil {
				cmd.PrintErrln("Error:", err)
				os.Exit(1)
			}

			err = crud.NewNoteSSH(output, pubKeyBytes)
			if err != nil {
				cmd.PrintErrln("Error:", err)
				os.Exit(1)
			}
			return
		}
		
		if editFlag {
			err = crud.NewNotePassEdit(output, config.Conf.EditorString)
			if err != nil {
				cmd.PrintErrln("Error:", err)
				os.Exit(1)
			}
		}

		err = crud.NewNotePass(output)
		if err != nil {
			cmd.PrintErrln("Error:", err)
			os.Exit(1)
		}
	},
}