// dupes.go: finds duplicate files in a folder. It groups the files by size, hashes only the files that share a size
// with SHA-256 in a pool of workers, and prints each group of equal files with the space its extra copies take.
// Build and run it: go build dupes.go && ./dupes [-j 4] FOLDER   (-j is the number of workers that hash at once)
package main

import (
	"cmp"
	"crypto/sha256"
	"encoding/hex"
	"flag"
	"fmt"
	"io"
	"io/fs"
	"os"
	"path/filepath"
	"slices"
	"strings"
	"sync"
)

const amber, red, dim, bold, reset = "\033[38;5;214m", "\033[31m", "\033[2m", "\033[1m", "\033[0m"

type result struct {
	path, sum string
	err       error
}

func size(n int64) string {
	switch {
	case n >= 1<<30:
		return fmt.Sprintf("%.1f GiB", float64(n)/(1<<30))
	case n >= 1<<20:
		return fmt.Sprintf("%.1f MiB", float64(n)/(1<<20))
	}
	return fmt.Sprintf("%.1f KiB", float64(n)/(1<<10))
}

// hash reads one file through SHA-256 and returns the sum in hex.
func hash(path string) (string, error) {
	f, err := os.Open(path)
	if err != nil {
		return "", err
	}
	defer f.Close()
	h := sha256.New()
	if _, err := io.Copy(h, f); err != nil {
		return "", err
	}
	return hex.EncodeToString(h.Sum(nil)), nil
}

func main() {
	workers := flag.Int("j", 4, "the number of files hashed at the same time")
	flag.Parse()
	if flag.NArg() != 1 || *workers < 1 {
		fmt.Fprintln(os.Stderr, "Usage: dupes [-j WORKERS] FOLDER")
		os.Exit(2)
	}
	root := flag.Arg(0)

	// 1. Walk the folder and group the regular files by size; empty files are left out.
	bySize := map[int64][]string{}
	files, total := 0, int64(0)
	err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
		if err != nil { // a folder it may not read: say so and go on
			fmt.Fprintln(os.Stderr, "dupes:", err)
			return nil
		}
		if !d.Type().IsRegular() {
			return nil
		}
		info, err := d.Info()
		if err != nil || info.Size() == 0 {
			return err
		}
		bySize[info.Size()] = append(bySize[info.Size()], path)
		files, total = files+1, total+info.Size()
		return nil
	})
	if err != nil {
		fmt.Fprintln(os.Stderr, "dupes:", err)
		os.Exit(1)
	}

	// 2. Only a file that shares its size with another can have a twin: those go to the workers.
	jobs, results := make(chan string), make(chan result)
	var wg sync.WaitGroup
	for range *workers {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for path := range jobs {
				sum, err := hash(path)
				results <- result{path, sum, err}
			}
		}()
	}
	var queue []string // the files that share their size with another file
	for _, paths := range bySize {
		if len(paths) > 1 {
			queue = append(queue, paths...)
		}
	}
	go func() { // feed the jobs, then close results once every worker is done
		for _, p := range queue {
			jobs <- p
		}
		close(jobs)
		wg.Wait()
		close(results)
	}()

	// 3. Group the results by their sum; a sum with two or more files is a group of duplicates.
	bySum := map[string][]string{}
	for r := range results {
		if r.err != nil {
			fmt.Fprintln(os.Stderr, "dupes:", r.err)
			continue
		}
		bySum[r.sum] = append(bySum[r.sum], r.path)
	}
	type group struct {
		sum    string
		paths  []string
		wasted int64
	}
	var groups []group
	var wasted int64
	for sum, paths := range bySum {
		if len(paths) > 1 {
			info, _ := os.Stat(paths[0])
			slices.Sort(paths)
			groups = append(groups, group{sum, paths, int64(len(paths)-1) * info.Size()})
			wasted += groups[len(groups)-1].wasted
		}
	}
	slices.SortFunc(groups, func(a, b group) int { // the most space first; equal ones by their first file
		return cmp.Or(cmp.Compare(b.wasted, a.wasted), strings.Compare(a.paths[0], b.paths[0]))
	})

	fmt.Printf("%s%s Duplicate files in %s %s%s\n", bold, amber, root, strings.Repeat("─", max(0, 58-len(root))), reset)
	fmt.Printf("%d files, %s. %d share a size with another file; %d workers hashed them.\n\n",
		files, size(total), len(queue), *workers)
	if len(groups) == 0 {
		fmt.Println("No duplicates: every file has its own content.")
		return
	}
	for _, g := range groups {
		fmt.Printf("%s%d copies%s of %s   %ssha256 %s…%s   extra copies take %s%s%s\n", bold, len(g.paths), reset,
			size(int64(g.wasted)/int64(len(g.paths)-1)), dim, g.sum[:12], reset, red, size(g.wasted), reset)
		for _, p := range g.paths {
			fmt.Printf("    %s\n", p)
		}
		fmt.Println()
	}
	fmt.Printf("%sThe extra copies take %s%s%s in all.\n", bold, red, size(wasted), reset)
	fmt.Println("Keep one file of each group and delete the others to free that space.")
}
