package main

/*
 * An example of how to use lxd's golang /dev/lxd client. This is intended to
 * be run from inside a container.
 */

import (
	"bufio"
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net"
	"net/http"
	"os"
	"strconv"
	"time"

	"github.com/gorilla/websocket"
	"gopkg.in/yaml.v2"

	"github.com/canonical/lxd/shared/api"
)

type devLxdDialer struct {
	Path string
}

func (d devLxdDialer) devLxdDial(ctx context.Context, network, path string) (net.Conn, error) {
	addr, err := net.ResolveUnixAddr("unix", d.Path)
	if err != nil {
		return nil, err
	}

	conn, err := net.DialUnix("unix", nil, addr)
	if err != nil {
		return nil, err
	}

	return conn, err
}

var devLxdTransport = &http.Transport{
	DialContext: devLxdDialer{"/dev/lxd/sock"}.devLxdDial,
}

func devlxdMonitorStream() {
	client := http.Client{
		Transport: &http.Transport{
			DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
				return net.Dial("unix", "/dev/lxd/sock")
			},
		},
	}

	resp, err := client.Get("http://unix/1.0/events")
	if err != nil {
		panic(err)
	}

	scanner := bufio.NewScanner(resp.Body)

	for scanner.Scan() {
		message := make(map[string]any)
		err = json.Unmarshal(scanner.Bytes(), &message)
		if err != nil {
			return
		}

		message["timestamp"] = nil

		msg, err := yaml.Marshal(&message)
		if err != nil {
			return
		}

		fmt.Printf("%s\n", msg)
	}
}

func devlxdMonitorWebsocket(c http.Client) {
	dialer := websocket.Dialer{
		NetDialContext:   devLxdTransport.DialContext,
		HandshakeTimeout: time.Second * 5,
	}

	conn, _, err := dialer.Dial("ws://unix.socket/1.0/events", nil)
	if err != nil {
		return
	}

	for {
		_, data, err := conn.ReadMessage()
		if err != nil {
			return
		}

		message := make(map[string]any)
		err = json.Unmarshal(data, &message)
		if err != nil {
			return
		}

		message["timestamp"] = nil

		msg, err := yaml.Marshal(&message)
		if err != nil {
			return
		}

		fmt.Printf("%s\n", msg)
	}
}

func devlxdState(ready bool) {
	client := http.Client{
		Transport: &http.Transport{
			DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
				return net.Dial("unix", "/dev/lxd/sock")
			},
		},
	}

	var body bytes.Buffer
	payload := struct {
		State string `json:"state"`
	}{}

	if ready {
		payload.State = api.Ready.String()
	} else {
		payload.State = api.Started.String()
	}

	err := json.NewEncoder(&body).Encode(&payload)
	if err != nil {
		return
	}

	req, err := http.NewRequest("PATCH", "http://unix/1.0", &body)
	if err != nil {
		return
	}

	req.Header.Set("Content-Type", "application/json")

	_, err = client.Do(req)
	if err != nil {
		return
	}
}

func main() {
	c := http.Client{Transport: devLxdTransport}
	raw, err := c.Get("http://meshuggah-rocks/")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	if raw.StatusCode != http.StatusOK {
		fmt.Println("http error", raw.StatusCode)
		result, err := io.ReadAll(raw.Body)
		if err != nil {
			os.Exit(1)
		}

		fmt.Println(string(result))
	}

	result := []string{}
	err = json.NewDecoder(raw.Body).Decode(&result)
	if err != nil {
		fmt.Println("err decoding response", err)
		os.Exit(1)
	}

	if result[0] != "/1.0" {
		fmt.Println("unknown response", result)
		os.Exit(1)
	}

	if len(os.Args) > 1 {
		var path string
		switch os.Args[1] {
		case "monitor-websocket":
			devlxdMonitorWebsocket(c)
			os.Exit(0)
		case "monitor-stream":
			devlxdMonitorStream()
			os.Exit(0)
		case "ready-state":
			ready, err := strconv.ParseBool(os.Args[2])
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}

			devlxdState(ready)
			os.Exit(0)
		case "devices":
			path = "devices"
		case "image-export":
			if len(os.Args) < 3 {
				fmt.Println("Image fingerprint is needed as second argument")
				os.Exit(1)
			}

			path = fmt.Sprintf("images/%s/export", os.Args[2])
		default:
			path = fmt.Sprintf("config/%s", os.Args[1])
		}

		raw, err := c.Get(fmt.Sprintf("http://meshuggah-rocks/1.0/%s", path))
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		// Avoid printing the entire image to stdout
		if !(os.Args[1] == "image-export" && (raw.StatusCode == 0 || raw.StatusCode == http.StatusOK)) {
			value, err := io.ReadAll(raw.Body)
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}

			fmt.Println(string(value))
		}
	} else {
		fmt.Println("/dev/lxd ok")
	}
}
