package main

import (
	"github.com/lxc/lxd/client"
	"github.com/lxc/lxd/shared/api"
	"os"
	"syscall"
	"fmt"
	"io/ioutil"
	"github.com/lxc/lxd/shared/termios"
)

func main() {
	stdout := captureStdout(e)
	fmt.Printf("%s", stdout)
}

func captureStdout(f func() error) []byte {
  oldStdout := os.Stdout
  oldStderr := os.Stderr
  r, w, _ := os.Pipe()
  os.Stdout = w
  os.Stderr = w

  f()

  w.Close()
  
  out, _ := ioutil.ReadAll(r)
  
  os.Stdout = oldStdout
  os.Stderr = oldStderr

  return out
}

func e() error{
	c, err := lxd.ConnectLXDUnix("", nil)
	if err != nil {
		return err
	}

	// Setup the exec request
	req := api.ContainerExecPost{
		Command: []string{"bash", "-c", "sleep 10; id; wei"},
		WaitForWS: true,
		Interactive: false,
		Width: 80,
		Height: 15,
	}

	// Setup the exec arguments (fds)
	args := lxd.ContainerExecArgs{
		Stdin: os.Stdin,
		Stdout: os.Stdout,
		Stderr: os.Stderr,
	}

	// Setup the terminal (set to raw mode)
	if req.Interactive {
		cfd := int(syscall.Stdin)
		oldttystate, err := termios.MakeRaw(cfd)
		if err != nil {
			return err
		}

		defer termios.Restore(cfd, oldttystate)
	}

	// Get the current state
	op, err := c.ExecContainer("container1", req, &args)
	if err != nil {
		return err
	}

	// Wait for it to complete
	err = op.Wait()
	if err != nil {
		return err
	}
	return nil
}