package main

import (
	"os"
	"os/exec"
	"path/filepath"
)

func instanceDir(dataDir, instanceID string) string {
	return filepath.Join(dataDir, "instances", instanceID)
}

func getContainerEngine() string {
	if _, err := exec.LookPath("podman"); err == nil {
		return "podman"
	}
	return "docker"
}

func writeCompose(dataDir, instanceID, compose string) error {
	dir := instanceDir(dataDir, instanceID)
	if err := os.MkdirAll(dir, 0755); err != nil {
		return err
	}
	f := filepath.Join(dir, "docker-compose.yml")
	return os.WriteFile(f, []byte(compose), 0644)
}

func dockerComposeUp(dataDir, instanceID string) error {
	dir := instanceDir(dataDir, instanceID)
	cmd := exec.Command(getContainerEngine(), "compose", "-f", filepath.Join(dir, "docker-compose.yml"), "up", "-d")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}

func dockerComposeDown(dataDir, instanceID string) error {
	dir := instanceDir(dataDir, instanceID)
	cmd := exec.Command(getContainerEngine(), "compose", "-f", filepath.Join(dir, "docker-compose.yml"), "down")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}

func dockerComposeRm(dataDir, instanceID string) error {
	dir := instanceDir(dataDir, instanceID)
	cmd := exec.Command(getContainerEngine(), "compose", "-f", filepath.Join(dir, "docker-compose.yml"), "down", "-v")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		return err
	}
	return os.RemoveAll(dir)
}
