aboutsummaryrefslogtreecommitdiffstats
path: root/dec/dec.go
blob: 049bc745b17456178473578f8c424db4ee4f980d (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
package main

import (
	"flag"
	"fmt"
	"io"
	"os"

	"golang.org/x/term"
	"roseh.moe/cmd/sym/internal/sym"
)

type options struct {
	password string
	force    bool

	stdin  io.Reader
	stdout io.Writer
}

func (o *options) dec(args ...string) error {
	if o.stdin == nil {
		o.stdin = os.Stdin
	}
	if o.stdout == nil {
		o.stdout = os.Stdout
	}
	if len(args) == 0 && o.password == "" {
		return fmt.Errorf("-p is required when reading from stdin")
	}
	var password string
	if o.password != "" {
		password = o.password
	} else {
		fmt.Fprint(os.Stderr, "Enter password: ")
		pw, err := term.ReadPassword(int(os.Stdin.Fd()))
		fmt.Fprintln(os.Stderr)
		if err != nil {
			return err
		}
		password = string(pw)
	}
	if len(args) == 0 {
		return sym.Decrypt(o.stdout, o.stdin, password)
	}
	for _, fileName := range args {
		if err := sym.DecryptFile(fileName, password, sym.Force(o.force)); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	o := new(options)
	flag.StringVar(&o.password, "p", "", "use the specified password; if not provided, dec will prompt for a password")
	flag.BoolVar(&o.force, "f", false, "overwrite output files even if they already exist")
	flag.Parse()
	if err := o.dec(flag.Args()...); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}