package git

import (
	"fmt"
	"os"
	"path"
	"syscall"
	"testing"

	"coopcloud.tech/abra/pkg/config"
)

func TestClone(t *testing.T) {
	dir := path.Join(config.RECIPES_DIR, "gitea")
	os.RemoveAll(dir)

	gitURL := fmt.Sprintf("%s/%s.git", config.REPOS_BASE_URL, "gitea")
	if err := Clone(dir, gitURL); err != nil {
		t.Fatalf("unable to git clone gitea: %s", err)
	}

	if _, err := os.Stat(dir); err != nil && os.IsNotExist(err) {
		t.Fatal("gitea repo was not cloned successfully")
	}
}

func TestCancelGitClone(t *testing.T) {
	dir := path.Join(config.RECIPES_DIR, "gitea")
	os.RemoveAll(dir)

	go func() {
		p, err := os.FindProcess(os.Getpid())
		if err != nil {
			t.Fatalf("unable to find current process: %s", err)
		}

		p.Signal(syscall.SIGINT)
	}()

	gitURL := fmt.Sprintf("%s/%s.git", config.REPOS_BASE_URL, "gitea")
	if err := Clone(dir, gitURL); err == nil {
		t.Fatal("cloning should have been interrupted")
	}

	if _, err := os.Stat(dir); err != nil && !os.IsNotExist(err) {
		t.Fatal("recipe repo was not deleted")
	}
}
