package util

import (
	"bytes"
	"crypto/md5"
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"os"
	"os/exec"
	"strconv"
	"strings"
)

// EncodeMD5 md5 encryption
func EncodeMD5(value string) string {
	m := md5.New()
	m.Write([]byte(value))

	return hex.EncodeToString(m.Sum(nil))
}

func GetMd5FromFile(path string) (string, error) {
	f, err := os.Open(path)
	defer f.Close()
	if err != nil {
		return "", err
	}
	h := md5.New()
	if _, err := io.Copy(h, f); err != nil {
		return "", err
	}
	return fmt.Sprintf("%x", h.Sum(nil)), nil

}

func GetSHA256FromFile(path string) (string, error) {
	f, err := os.Open(path)
	defer f.Close()
	if err != nil {
		return "", err
	}
	h := sha256.New()
	if _, err := io.Copy(h, f); err != nil {
		return "", err
	}
	sum := fmt.Sprintf("%x", h.Sum(nil))
	return sum, nil
}

func GetFileSizeByBytes(file string) (int64, error) {
	var buf bytes.Buffer
	cmd := exec.Command("du", "-b", file)
	cmd.Stdout = &buf
	err := cmd.Run()
	if err != nil {
		return 0, err
	}
	list := strings.Split(buf.String(), "\t")
	if len(list) >= 2 {
		size, err := strconv.Atoi(list[0])
		if err != nil {
			return 0, err
		}
		return int64(size), nil
	}
	return 0, nil
}
