package pods

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

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

// CopySkelToContainer copies an Archive into the containers root
func CopySkelToContainer(id string) error {
	log.Println("Copying skel Archive to container")
	var err error
	conn, err := bindings.GetClient(Socket)
	if err != nil {
		return err
	}
	file, err := os.Open(viper.GetString("skel"))
	if err != nil {
		log.Println("Could not open skel archive", err)
		return err
	}

	fileInfo, err := os.Stat(viper.GetString("skel"))
	log.Println("Skel Archive is ", fileInfo.Size(), "b")

	defer file.Close()

	params := url.Values{}
	params.Set("path", "/")

	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: ")
		return err
	}
	log.Println(response.StatusCode, response.Body)
	return response.Process(nil)
}
