package main

import (
	"encoding/json"
	"fmt"
	"github.com/go-resty/resty/v2"
	"io"
	"os"
)

const version = "1.0.1"

type VersionInfo struct {
	Version     string `json:"Version"`
	DownloadUrl string `json:"DownloadUrl"`
}

func Update(remote, local string) error {
	c := resty.New()
	r, err := c.R().Get(remote)
	if err != nil {
		return err
	}
	if r.StatusCode() != 200 {
		return fmt.Errorf("request error: %s", r)
	}
	v := VersionInfo{}
	err = json.Unmarshal(r.Body(), &v)
	if err != nil {
		return err
	}
	if v.Version == "" {
		return nil
	}
	if v.Version == version {
		return nil
	}
	if v.DownloadUrl == "" {
		return nil
	}

	r, err = c.SetDoNotParseResponse(true).R().
		Get(v.DownloadUrl)
	if err != nil {
		return err
	}
	defer r.RawBody().Close()
	f, err := os.OpenFile(local, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0744)
	if err != nil {
		return err
	}
	if r.StatusCode() != 200 {
		return fmt.Errorf("request error: %s", r)
	}
	defer f.Close()
	_, err = io.Copy(f, r.RawBody())
	if err != nil {
		return nil
	}
	return nil
}
