Skip to content
Snippets Groups Projects
main.go 1.96 KiB
package main

import (
	"flag"
	"fmt"
	"os"
	"path"
	"gitlab.ssec.wisc.edu/brucef/efftp/commands"
)

func printUsage() {
	fmt.Fprintf(os.Stderr, `
USAGE: %s <command> [<args>]

Commands:

  put		Put a file atomically
  get		Download a file
  rm		Remove a file
  ls		List a directory

Options:

`, path.Base(os.Args[0]))
	flag.PrintDefaults()
}

func main() {
	opts := commands.Options{}
	flag.IntVar(&opts.ConnectTimeout, "connect-timeout", 30, "Connection timeout in seconds.")
	flag.StringVar(&opts.Userpass, "credentials", "anonymous:anonymous",
	`FTP credential string. It can be either a user:password to explicitly
	specify credentials, or the string 'netrc' to retreive credentials from
	./netrc or ~/.netrc, in that order. If not provided default credentials are
	used. If there are credentials present in the URL they will take precedence
	over any other specified method or credentials.`)

	flag.Usage = printUsage

	putFlags := flag.NewFlagSet("put", flag.ExitOnError)
	put := commands.NewPutCommand(putFlags)
	getFlags := flag.NewFlagSet("get", flag.ExitOnError)
	get := commands.NewGetCommand(getFlags)
	rmFlags := flag.NewFlagSet("rm", flag.ExitOnError)
	rm := commands.NewRmCommand(rmFlags)
	lsFlags := flag.NewFlagSet("ls", flag.ExitOnError)
	ls := commands.NewLsCommand(lsFlags)

	if len(os.Args) == 1 {
		flag.Usage()
		os.Exit(1)
		return
	}

	switch os.Args[1] {
	case "put":
		putFlags.Parse(os.Args[2:])
	case "get":
		getFlags.Parse(os.Args[2:])
	case "rm":
		rmFlags.Parse(os.Args[2:])
	case "ls":
		lsFlags.Parse(os.Args[2:])
	default:
		fmt.Printf("%q is not valid command.\n", os.Args[1])
		os.Exit(2)
	}

	var cmd commands.Command
	if putFlags.Parsed() {
		cmd = put
	} else if getFlags.Parsed() {
		cmd = get
	} else if rmFlags.Parsed() {
		cmd = rm
	} else if lsFlags.Parsed() {
		cmd = ls
	} else {
		panic("invalid command, we should never get here")
	}

	status := 0
	if err := cmd.Run(&opts); err != nil {
		fmt.Printf("ERROR: %s\n", err)
		status = 1
	}
	os.Exit(status)
}