package importer

import (
	"io/fs"
	"os"
	"path/filepath"
	"syscall"

	"github.com/rs/zerolog/log"
)

func createFile(recreate bool, mode fs.FileMode, pathElems ...string) (*os.File, error) {
	if recreate {
		err := os.Remove(filepath.Join(pathElems...))
		if err != nil {
			e, ok := err.(*os.PathError)
			if ok && e.Err == syscall.ENOENT {
				// File doesn't exist, ignore
			} else {
				return nil, err
			}
		}
	}
	f, err := os.OpenFile(
		filepath.Join(pathElems...), os.O_APPEND|os.O_CREATE|os.O_WRONLY, mode)
	if err != nil {
		return nil, err
	}
	f.Write([]byte("# Code generated by github.com/polytomic/terraform-provider-polytomic/importer\n"))
	return f, nil
}

func createDirectory(path string) error {
	if _, err := os.Stat(path); os.IsNotExist(err) {
		log.Info().Msgf("Creating directory %s", path)
		return os.Mkdir(path, os.ModePerm)
	}
	return nil
}
