package main

import (
	"container/list"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"strings"
)

func WalkFoldertoFolder(dirname string, searchs []string) *list.List {
	results := list.List{}
	files, err := ioutil.ReadDir(dirname)
	if err != nil {
		fmt.Println(err)
	}
	for _, f := range files {
		path := fmt.Sprintf("%s/%s", dirname, f.Name())
		if f.IsDir() {
			results.PushBackList(WalkFoldertoFolder(path, searchs))
		} else {
			for _, s := range searchs {
				if strings.Contains(f.Name(), s) {
					results.PushBack(path)
				}
			}
		}
	}
	return &results
}

func copy(src, dst string) (int64, error) {
	sourceFileStat, err := os.Stat(src)
	if err != nil {
		return 0, err
	}

	if !sourceFileStat.Mode().IsRegular() {
		return 0, fmt.Errorf("%s is not a regular file", src)
	}

	source, err := os.Open(src)
	if err != nil {
		return 0, err
	}
	defer source.Close()

	destination, err := os.Create(dst)
	if err != nil {
		return 0, err
	}
	defer destination.Close()
	nBytes, err := io.Copy(destination, source)
	return nBytes, err
}

func main() {
	ext := []string{
		".avi",
		".mkv",
		".m4v",
		".mp4",
	}
	srcfolder := os.Args[1]
	cpyfolder := os.Args[2]
	fmt.Println("HelloWorld")
	results := WalkFoldertoFolder(srcfolder, ext)
	for file := results.Front(); file != nil; file = file.Next() {
		filesrc := file.Value.(string)
		filedst := string(filesrc[len(srcfolder):len(filesrc)])
		filedst = cpyfolder + filedst
		fmt.Println(filesrc + " / " + filedst)
		dirpath := string(filedst[0:strings.LastIndex(filedst, "/")])
		fmt.Println(dirpath)
		os.MkdirAll(dirpath, 0777)
		_, err := copy(filesrc, filedst)
		if err != nil {
			panic(err)
		}
	}
}
