package git

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

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

func setup() {
	teardown()

	if err := os.Mkdir(os.ExpandEnv("$ABRA_DIR"), 0764); err != nil {
		if !os.IsExist(err) {
			log.Fatal(err)
		}
	}

	if err := os.Mkdir(os.ExpandEnv("$ABRA_DIR/recipes"), 0764); err != nil {
		if !os.IsExist(err) {
			log.Fatal(err)
		}
	}
}

func teardown() {
	abraDir := os.ExpandEnv("$ABRA_DIR")
	if abraDir == fmt.Sprintf("%s/.abra", os.ExpandEnv("$HOME")) {
		log.Fatal("set $ABRA_DIR before running the test suite")
	}

	if err := os.RemoveAll(abraDir); err != nil {
		log.Fatal(err)
	}
}

func TestClone(t *testing.T) {
	setup()
	t.Cleanup(func() { teardown() })

	dir := path.Join(config.RECIPES_DIR, "gitea")
	if err := os.RemoveAll(dir); err != nil {
		t.Fatal(err)
	}

	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) {
	t.Skip("https://git.coopcloud.tech/toolshed/abra/issues/814")

	setup()
	t.Cleanup(func() { teardown() })

	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")
	}
}
