/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2025-2026. All rights reserved.
 * KubernetesPlugin is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 * http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

// Package main run score plugin
package main

import (
	"context"
	"flag"
	"os"

	"matrixplugin/pkg/communication"
	"matrixplugin/pkg/constant"
	"matrixplugin/pkg/health"
	"matrixplugin/pkg/utils/log"
)

const (
	shmCsiKey          = "shm-csi"
	exitedStatus       = "exited"
	initializingStatus = "initializing"
)

var healthz = flag.Bool("healthz", false, "Run liveness checks")

func main() {
	// using exitCode instead of using os.Exit()
	exitCode := run()
	os.Exit(exitCode)
}

// run Execute the main process and return exitCode
func run() int {
	flag.Parse()
	if *healthz {
		return runHealthCheck()
	}

	log.GetLogger().Infof("Plugin started, %s, %s.", shmCsiKey, initializingStatus)

	_, cancel := context.WithCancel(context.Background())
	defer func() {
		log.GetLogger().Infof("Plugin exiting, %s, %s.", shmCsiKey, exitedStatus)
		cancel()
	}()

	if err := PrepareIpc(); err != nil {
		log.GetLogger().Errorf("prepareIpc err: %v", err)
		return constant.PrepareIPCFailedCode
	}

	if err := startUdsServer(); err != nil {
		return constant.StartUdsServerFailedCode
	}

	fatalErrorChan := make(chan error, 1)
	StartCentralNode(fatalErrorChan)
	go func() {
		if err := communication.StartServer(constant.ShmInnerUsdPath); err != nil {
			log.GetLogger().Errorf("StartServer failed: %v", err)
			fatalErrorChan <- err
		}
	}()

	if err := <-fatalErrorChan; err != nil {
		log.GetLogger().Infof("Received error %v, shutting down.", err)
		return 1
	}
	return 0
}

// runHealthCheck runs the liveness probe client
func runHealthCheck() int {
	if err := health.RunHealthCheck(constant.CsiHealthSocketPath); err != nil {
		log.GetLogger().Error(err.Error())
		return 1
	}
	return 0
}

// startUdsServer starts the probe server
func startUdsServer() error {
	if err := health.StartUdsServer(constant.CsiHealthSocketPath); err != nil {
		log.GetLogger().Errorf("StartUdsServer failed: %v", err)
		return err
	}
	return nil
}