package main

import (
	"bytes"
	"encoding/base64"
	"flag"
	"fmt"
	"io"
	"net"
	"os"
	"strings"

	"github.com/golang/glog"
)

var addr = flag.String("addr", "localhost:10143", "IMAP addr")

type client struct {
	net.Conn
	msgCount int
}

func (c *client) cmd(tagged bool, msg ...string) {
	w := io.MultiWriter(c.Conn, os.Stdout)
	var b bytes.Buffer
	if tagged {
		fmt.Fprintf(&b, "a%04d ", c.msgCount)
		c.msgCount++
	}
	fmt.Fprintln(&b, strings.Join(msg, " "))
	if _, err := io.Copy(w, &b); err != nil {
		panic(err)
	}
}

func (c *client) Close() error {
	return c.Conn.Close()
}

func main() {
	flag.Parse()
	defer glog.Flush()

	conn, err := net.Dial("tcp", *addr)
	if err != nil {
		glog.Exitf("Failed to connect to %q: %v", *addr, err)
	}
	c := &client{Conn: conn}
	defer c.Close()
	defer func() {
		if _, err := io.Copy(os.Stdout, c); err != nil {
			glog.Exitf("Failed to read from connection: %v", err)
		}
	}()

	c.cmd(true, "AUTHENTICATE PLAIN ")
	c.cmd(false, base64.StdEncoding.EncodeToString([]byte("\x00username\x00password")))
	c.cmd(true, "SELECT INBOX")
	c.cmd(true, "FETCH 1:* (FLAGS INTERNALDATE RFC822.SIZE BODY[HEADER])")
	c.cmd(true, "CLOSE")
	c.cmd(true, "LOGOUT")
}
