aboutsummaryrefslogtreecommitdiffstats
path: root/sym.go
blob: b7265620cd5ce5d9f21644bff0febf80fdb5154f (plain) (blame)
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
// The sym command encrypts or decrypts files with a password.
//
// Sym has two subcommands, enc and dec, which perform encryption and
// decryption. The encryption key is derived from the user's password using
// argon2, and the data is then encrypted using AES-256 in chunks of 1MiB.
//
// Run sym -h for detailed usage information.
package main

import (
	"flag"
	"fmt"
	"os"
	"path/filepath"
)

type subcommand interface {
	registerFlags(*flag.FlagSet)
	run(...string) error
}

func whichSubcommand(name string) (subcommand, bool) {
	switch name {
	case "enc":
		return &encryptOptions{
			passwordIn:  termReadPassword,
			passwordOut: os.Stderr,
			stdin:       os.Stdin,
			stdout:      os.Stdout,
		}, true
	case "dec":
		return &decryptOptions{
			passwordIn: termReadPassword,
			stdin:      os.Stdin,
			stdout:     os.Stdout,
		}, true
	default:
		return nil, false
	}
}

func run(args []string) error {
	name := filepath.Base(args[0])
	cmd, ok := whichSubcommand(name)
	if !ok {
		flag.Usage = func() {
			fmt.Fprintf(os.Stderr, `usage: sym <subcommand> [OPTION]... [FILE]...
Encrypt or decrypt files using a password.

Subcommands:
  enc    encrypt
  dec    decrypt

Try sym <subcommand> -h for command-specific help.

Pro tip: use "ln sym enc" or "ln sym dec" to create shortcuts for each subcommand.
`)
		}
		flag.CommandLine.Parse(args[1:])
		args = flag.Args()
		if len(args) == 0 {
			return fmt.Errorf("missing subcommand (use sym -h for help)")
		}
		subcommand := filepath.Base(args[0])
		name = "sym " + subcommand
		cmd, ok = whichSubcommand(subcommand)
		if !ok {
			return fmt.Errorf("invalid subcommand %q", args[0])
		}
	}
	fs := flag.NewFlagSet(name, flag.ExitOnError)
	cmd.registerFlags(fs)
	fs.Parse(args[1:])
	return cmd.run(fs.Args()...)
}

func main() {
	if err := run(os.Args); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}