package geoip

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"

	geoip2 "github.com/oschwald/geoip2-golang"
)

var RootURL = "https://git.paulbsd.com/paulbsd/GeoLite.mmdb/releases/download/%s/%s"
var APIUrl = "https://git.paulbsd.com/api/v1/repos/paulbsd/GeoLite.mmdb/releases"

func GetLastVersion() string {
	var apiresults []struct {
		Tag string `json:"tag_name"`
	}
	res, err := http.Get(APIUrl)
	if err != nil {
		log.Println(err)
	}
	body, err := io.ReadAll(res.Body)
	if err != nil {
		log.Println(err)
	}
	err = json.Unmarshal(body, &apiresults)
	if err != nil {
		log.Println(err)
	}
	return apiresults[0].Tag
}

func InitGeoIP() (citydb *geoip2.Reader, asndb *geoip2.Reader, err error) {
	var version = GetLastVersion()
	var dbs map[string]string = map[string]string{
		"city": fmt.Sprintf(RootURL, version, "GeoLite2-City.mmdb"),
		"asn":  fmt.Sprintf(RootURL, version, "GeoLite2-ASN.mmdb")}
	log.Printf("Fetching GeoLite.mmdb version %s\n", version)
	citydb, err = FetchDB(dbs["city"], version)
	if err != nil {
		return
	}
	asndb, err = FetchDB(dbs["asn"], version)
	if err != nil {
		return
	}
	return
}

func FetchDB(db string, version string) (reader *geoip2.Reader, err error) {
	if _, err := os.Stat("geoip"); err != nil {
		os.MkdirAll("geoip", 0777)
	}

	splited := strings.Split(db, "/")
	filename := strings.Replace(splited[len(splited)-1], ".", fmt.Sprintf("-%s.", version), 1)
	dbpath := fmt.Sprintf("%s/%s", "geoip", filename)

	if _, err := os.Stat(dbpath); err != nil {
		resp, err := http.Get(db)
		if err != nil {
			return nil, nil
		}
		file, err := os.Create(dbpath)
		if err != nil {
			return nil, nil
		}
		_, err = io.Copy(file, resp.Body)
		if err != nil {
			return nil, nil
		}
	}

	return geoip2.Open(dbpath)
}
