package main

import (
	"context"
	"encoding/json"
	"io"
	"log"
	"net/http"
	"os"
	"os/exec"
)

func main() {
	req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://git.mthie.com/api/v1/repos/mthie/vault-action/releases", nil)
	if err != nil {
		log.Panicf("error creating download request: %s", err)
	}

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		log.Panicf("error getting download information: %s", err)
	}

	type releaseInfo []struct {
		Assets []struct {
			URL string `json:"browser_download_url"`
		} `json:"assets"`
	}

	downloadData := releaseInfo{}
	if err := json.NewDecoder(resp.Body).Decode(&downloadData); err != nil {
		log.Panicf("error decoding release information: %s", err)
	}

	resp.Body.Close()

	if len(downloadData) == 0 || len(downloadData[0].Assets) == 0 {
		log.Panic("no binary found")
	}

	req, err = http.NewRequestWithContext(context.Background(), http.MethodGet, downloadData[0].Assets[0].URL, nil)
	if err != nil {
		log.Panicf("error creating download request: %s", err)
	}

	resp, err = http.DefaultClient.Do(req)
	if err != nil {
		log.Panicf("error downloading binary: %s", err)
	}
	out, err := os.OpenFile("vault", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0755)
	if err != nil {
		log.Panicf("error creating file: %s", err)
	}

	if _, err = io.Copy(out, resp.Body); err != nil {
		log.Panicf("error writing download data: %s", err)
	}

	out.Close()
	resp.Body.Close()

	cmd := exec.Command("./vault")
	if err := cmd.Run(); err != nil {
		log.Panicf("error executing: %s", err)
	}
}
