package main

import (
	"floares/service/auth"
	"floares/service/containers"
	"floares/service/images"
	"floares/service/network"
	"floares/service/system"
	"github.com/containers/podman/v5/cmd/podman/registry"
	api "github.com/containers/podman/v5/pkg/api/server"
	"github.com/containers/podman/v5/pkg/domain/entities"
	"github.com/containers/storage/pkg/reexec"
	"github.com/spf13/cobra"
	"net"

	"floares/service/volume"
	"github.com/containers/podman/v5/pkg/domain/infra"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
)

func main() {

	if reexec.Init() {
		// We were invoked with a different argv[0] indicating that we
		// had a specific job to do as a subprocess, and it's done.
		return
	}
	//c := cobra.Command{}
	r := gin.Default()
	r.Use(func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", c.Request.Header.Get("Origin"))
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PATCH")
		c.Header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Content-Type,Authorization")
		c.Header("Access-Control-Expose-Headers", "Content-Length")
		c.Header("Access-Control-Allow-Credentials", "true")
		if c.Request.Method == "OPTIONS" {
			c.Status(http.StatusNoContent)
			c.Abort()
		}
		return

	})
	a := r.Group("/api/auth")
	a.POST("/sign-in", auth.Sign)
	a.GET("/me", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{})
	})
	a.POST("/sign-up", auth.Sign)
	system.RegisterRouter(r.Group("/system"))
	containers.RegisterRouter(r.Group("/containers"))
	images.RegisterRouter(r.Group("/images"))
	network.RegisterRouter(r.Group("/network"))
	volume.RegisterRouter(r.Group("/volumes"))
	//flags := flag.NewFlagSet("", flag.ExitOnError)
	cmd := &cobra.Command{}
	cfg := registry.PodmanConfig()
	de := cfg.ContainersConfDefaultsRO
	de.Engine.OCIRuntime = "youki"
	rootFlags(cmd, cfg)
	persistentPreRunE(cmd, nil)
	log.Println(*cfg)
	libpodRuntime, err := infra.GetRuntime(registry.Context(), cmd.PersistentFlags(), cfg)
	if err != nil {
		log.Fatal(err)
	}
	listener, err := net.Listen("tcp", "127.0.0.1:8888")
	if err != nil {
		panic(err)
	}
	libpodRuntime.SetRemoteURI("tcp://localhost:8888")
	infra.StartWatcher(libpodRuntime)

	server, err := api.NewServerWithSettings(libpodRuntime, listener, entities.ServiceOptions{
		URI: "tcp://localhost:8888",
	})
	if err != nil {
		log.Fatal(err)
	}
	go server.Serve()
	r.Run()
}
