aboutsummaryrefslogtreecommitdiffstats
path: root/cmd/lftpq/main.go
blob: 3183d75617576eb5a0d93c72ac51af205e1f74e4 (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
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
package main

import (
	"flag"
	"fmt"
	"io"
	"os"
	"os/signal"
	"path/filepath"
	"syscall"

	"github.com/mpolden/lftpq/lftp"
	"github.com/mpolden/lftpq/queue"
)

type lister interface {
	List(site, path string) ([]os.FileInfo, error)
}

type CLI struct {
	Config   string
	Dryrun   bool
	Format   string
	Test     bool
	Quiet    bool
	Import   bool
	LocalDir string
	LftpPath string
	consumer queue.Consumer
	lister   lister
	stderr   io.Writer
	stdout   io.Writer
	stdin    io.Reader
}

func New() *CLI {
	sig := make(chan os.Signal, 1)
	signal.Notify(sig, syscall.SIGTERM, syscall.SIGINT, syscall.SIGPIPE)
	cli := CLI{}
	go func() {
		<-sig
		cli.unlock()
		os.Exit(1)
	}()
	return &cli
}

func (c *CLI) Run() error {
	cfg, err := queue.ReadConfig(c.Config)
	if err != nil {
		return err
	}
	if c.LocalDir != "" {
		if err := cfg.SetLocalDir(c.LocalDir); err != nil {
			return err
		}
	}
	if c.Test {
		json, err := cfg.JSON()
		if err != nil {
			return err
		}
		fmt.Fprintf(c.stdout, "%s\n", json)
		return nil
	}
	var queues []queue.Queue
	if c.Import {
		if queues, err = queue.Read(cfg.Sites, c.stdin); err != nil {
			return err
		}
	} else {
		if err := c.lock(); err != nil {
			return fmt.Errorf("already running: %s", err)
		}
		defer c.unlock()
		queues = c.queuesFor(cfg.Sites)
	}
	for _, q := range queues {
		if err := c.transfer(q); err != nil {
			c.printf("error while transferring queue for %s: %s\n", q.Site.Name, err)
			continue
		}
	}
	return nil
}

func (c *CLI) lockfile() string { return filepath.Join(os.TempDir(), ".lftpqlock") }

func (c *CLI) lock() error {
	_, err := os.OpenFile(c.lockfile(), os.O_CREATE|os.O_EXCL, 0644)
	return err
}

func (c *CLI) unlock() { os.Remove(c.lockfile()) }

func (c *CLI) printf(format string, vs ...interface{}) {
	alwaysPrint := false
	for _, v := range vs {
		if _, ok := v.(error); ok {
			alwaysPrint = true
			break
		}
	}
	if !c.Quiet || alwaysPrint {
		fmt.Fprint(c.stderr, "lftpq: ")
		fmt.Fprintf(c.stderr, format, vs...)
	}
}

func (c *CLI) queuesFor(sites []queue.Site) []queue.Queue {
	var queues []queue.Queue
	for _, s := range sites {
		if s.Skip {
			c.printf("skipping site %s\n", s.Name)
			continue
		}
		var files []os.FileInfo
		for _, dir := range s.Dirs {
			f, err := c.lister.List(s.Name, dir)
			if err != nil {
				c.printf("error while listing %s on %s: %s\n", dir, s.Name, err)
				continue
			}
			files = append(files, f...)
		}
		queue := queue.New(s, files)
		queues = append(queues, queue)
	}
	return queues
}

func (c *CLI) transfer(q queue.Queue) error {
	if c.Dryrun {
		var (
			out []byte
			err error
		)
		if c.Format == "json" {
			out, err = q.MarshalJSON()
			out = append(out, 0x0a) // Add trailing newline
		} else {
			out, err = q.MarshalText()
		}
		if err == nil {
			fmt.Fprint(c.stdout, string(out))
		}
		return err
	}
	if len(q.Transferable()) == 0 {
		c.printf("%s queue is empty\n", q.Site.Name)
		return nil
	}
	if err := q.Transfer(c.consumer); err != nil {
		return err
	}
	return q.PostProcess(!c.Quiet)
}

func main() {
	cli := New()
	cli.stderr = os.Stderr
	cli.stdout = os.Stdout
	cli.stdin = os.Stdin
	flag.StringVar(&cli.Config, "f", "~/.lftpqrc", "Path to config")
	flag.BoolVar(&cli.Dryrun, "n", false, "Print queue and exit")
	flag.StringVar(&cli.Format, "F", "lftp", "Format to use in dry-run mode")
	flag.BoolVar(&cli.Test, "t", false, "Test and print config")
	flag.BoolVar(&cli.Quiet, "q", false, "Do not print output from lftp")
	flag.BoolVar(&cli.Import, "i", false, "Build queues from stdin")
	flag.StringVar(&cli.LocalDir, "l", "", "Override local dir for this run")
	flag.StringVar(&cli.LftpPath, "p", "lftp", "Path to lftp program")
	flag.Parse()
	client := lftp.Client{Path: cli.LftpPath, InheritIO: !cli.Quiet}
	cli.lister = &client
	cli.consumer = &client
	if err := cli.Run(); err != nil {
		cli.printf("%s\n", err)
		os.Exit(1)
	}
}