package pods

import (
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/containers/podman/v4/pkg/bindings"
	"github.com/containers/podman/v4/pkg/bindings/containers"
	"github.com/spf13/viper"
)

// CopySkelToContainer copies an Archive into the containers root
func CopySkelToContainer(id string) error {
	chownBool := viper.GetBool("skel_chown")
	log.Println("Copying skel Archive to container")
	var err error
	conn, err := bindings.GetClient(Socket)
	if err != nil {
		return err
	}
	options := containers.CopyOptions{
		Chown: &chownBool,
	}

	fileInfo, err := os.Stat(viper.GetString("skel"))

	if err != nil {
		log.Println("Could not access Skel archive")
		return err
	}
	log.Println("Skel Archive is ", fileInfo.Size(), "b")

	file, err := os.Open(viper.GetString("skel"))
	if err != nil {
		log.Println("Could not open skel archive", err)
		return err
	}
	defer file.Close()

	params, err := options.ToParams()
	if err != nil {
		log.Println("Could not parse skel options", err)
		return err
	}
	params.Set("path", viper.GetString("skel_target"))

	fmt.Println("Container", id, " Params: ", params.Encode())
	response, err := conn.DoRequest(
		Socket,
		file,
		http.MethodPut,
		"/containers/%s/archive",
		params,
		nil,
		id,
	)
	if err != nil {
		return err
	}

	if response.StatusCode != http.StatusOK {
		log.Println("Error putting archive into container: ", response.StatusCode, response.Body)
		return err
	}
	log.Println(response.StatusCode, response.Body)

	// Manually chown the Directory, because podmans chown is sometimes unreliable
	return response.Process(nil)
}
