package main

import (
	"archive/zip"
	"fmt"
	"io"
	"log"
	"strings"

	"srs.epita.fr/fic-server/admin/sync"
	"srs.epita.fr/fic-server/libfic"
)

func checkZip(file *fic.EFile, exceptions *sync.CheckExceptions) (errs []error) {
	fd, closer, err := sync.GetFile(sync.GlobalImporter, file.GetOrigin())
	if err != nil {
		log.Printf("Unable to open %q: %s", file.GetOrigin(), err.Error())
		return
	}
	defer closer()

	fdat, ok := fd.(io.ReaderAt)
	if !ok {
		log.Printf("The current Importer (%t) doesn't allow me to check the archive: %s. Please test-it yourself", sync.GlobalImporter, file.GetOrigin())
		return
	}

	size, err := sync.GetFileSize(sync.GlobalImporter, file.GetOrigin())
	if err != nil {
		log.Printf("Unable to calculate size of %q: %s", file.GetOrigin(), err.Error())
		return
	}

	r, err := zip.NewReader(fdat, size)
	if err != nil {
		log.Printf("Unable to open %q: %s", file.GetOrigin(), err.Error())
		return
	}

	if len(r.File) < 2 {
		if !exceptions.HasException(":one-file-tarball") {
			errs = append(errs, fmt.Errorf("don't make a ZIP archive for one file, use gzip instead"))
		}
	} else if len(r.File) < 5 && false {
		if !exceptions.HasException(":few-files-tarball") {
			errs = append(errs, fmt.Errorf("don't make a ZIP archive for so little files (:few-files-tarball)"))
		}
	} else {
		log.Printf("%d files found in %q", len(r.File), file.Name)
	}

	foundEtcDir := false
	foundHomeDir := false
	foundRootDir := false
	foundVarDir := false
	for _, file := range r.File {
		if strings.HasPrefix(file.Name, "etc") {
			foundEtcDir = true
		}
		if strings.HasPrefix(file.Name, "home") {
			foundHomeDir = true
		}
		if strings.HasPrefix(file.Name, "root") {
			foundRootDir = true
		}
		if strings.HasPrefix(file.Name, "var") {
			foundVarDir = true
		}
	}

	nbLinuxDirFound := 0
	if foundEtcDir {
		nbLinuxDirFound += 1
	}
	if foundHomeDir {
		nbLinuxDirFound += 1
	}
	if foundRootDir {
		nbLinuxDirFound += 1
	}
	if foundVarDir {
		nbLinuxDirFound += 1
	}

	if nbLinuxDirFound > 2 && !exceptions.HasException(":not-a-linux-rootfs") {
		errs = append(errs, fmt.Errorf("don't use a ZIP archive to store an Unix file system, prefer a tarball (:not-a-linux-rootfs)"))
	}

	return
}
