package main

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"errors"
	"io/ioutil"
)

type Id struct {
	Eni string `json:"eni"`
	Mac string `json:"mac"`
}

func initId() (*Id, error) {
	id := &Id{}
	eni, err := getFirstNetInterface()
	if err != nil {
		return id, errors.New("could not init ID file")
	}
	id.Eni = eni.Name
	id.Mac = eni.HardwareAddr
	data, err := json.Marshal(id)
	if err != nil {
		return id, errors.New("could not init ID file")
	}
	err = ioutil.WriteFile("id.json", data, 0660)
	if err != nil {
		return id, errors.New("could not init ID file")
	}
	return id, nil
}

func loadId() (*Id, error) {
	id := &Id{}
	data, err := ioutil.ReadFile("id.json")
	if err != nil {
		return id, errors.New("could not load ID file")
	}
	err = json.Unmarshal(data, &id)
	if err != nil {
		return id, errors.New("could not load ID file")
	}
	return id, nil
}

func getId() (string, error) {
	data, err := loadId()
	if err != nil {
		data, err = initId()
		if err != nil {
			return "", errors.New("Could not init id!")
		}
	}
	h := md5.New()
	h.Write([]byte(data.Eni + data.Mac))
	id := hex.EncodeToString(h.Sum(nil))
	return id, nil
}
