package main

import (
	"archive/tar"
	"compress/gzip"
	"io"
	"os"
	"strings"
)

func matchIPGlob(ip, pattern string) bool {
	parts := strings.Split(pattern, ".")
	seg := strings.Split(ip, ".")
	for i, part := range parts {

		// normalize pattern to 3 digits
		switch len(part) {
		case 1:
			if part == "*" {
				part = "***"
			} else {
				part = "00" + part
			}
		case 2:
			if strings.HasPrefix(part, "*") {
				part = "*" + part
			} else if strings.HasSuffix(part, "*") {
				part = part + "*"
			} else {
				part = "0" + part
			}
		}

		// normalize ip to 3 digits
		switch len(seg[i]) {
		case 1:
			seg[i] = "00" + seg[i]
		case 2:
			seg[i] = "0" + seg[i]
		}

		for j := range part {
			if string(part[j]) == "*" {
				continue
			}
			if part[j] != seg[i][j] {
				return false
			}
		}
	}
	return true
}

func bundle(buf io.Writer, paths []string, flat bool) error {
	gw := gzip.NewWriter(buf)
	defer gw.Close()
	tw := tar.NewWriter(gw)
	defer tw.Close()

	for _, file := range paths {
		if err := func(file string) error {
			f, err := os.Open(file)
			if err != nil {
				return err
			}
			defer f.Close()

			info, err := f.Stat()
			if err != nil {
				return err
			}

			header, err := tar.FileInfoHeader(info, info.Name())
			if err != nil {
				return err
			}

			// Use full path as name (FileInfoHeader only takes the basename)
			// If we don't do this the directory strucuture would
			// not be preserved
			// https://golang.org/src/archive/tar/common.go?#L626
			if !flat {
				if !strings.HasPrefix(file, "/") {
					file = "configui/" + file
				} else {
					file = "configui" + file
				}
				header.Name = file
			}

			// Write file header to the tar archive
			err = tw.WriteHeader(header)
			if err != nil {
				return err
			}

			// Copy file content to tar archive
			_, err = io.Copy(tw, f)
			if err != nil {
				return err
			}
			return nil

		}(file); err != nil {
			return err
		}
	}

	return nil
}
