// SPDX-License-Identifier: BSD-2-Clause
//
// Copyright (c) 2025 The FreeBSD Foundation.
//
// This software was developed by Hayzam Sherif <hayzam@alchemilla.io>
// of Alchemilla Ventures Pvt. Ltd. <hello@alchemilla.io>,
// under sponsorship from the FreeBSD Foundation.

package startup

import (
	"os"
	"strings"

	"github.com/alchemillahq/sylve/internal/config"
	sambaModels "github.com/alchemillahq/sylve/internal/db/models/samba"
	"github.com/alchemillahq/sylve/internal/logger"
	"github.com/alchemillahq/sylve/pkg/system"
	"github.com/alchemillahq/sylve/pkg/utils"

	sambaUtils "github.com/alchemillahq/sylve/pkg/system/samba"
)

func (s *Service) InitSamba() error {
	const marker = "# === This file is automatically generated by Sylve, don't edit! ==="
	cfgPath := "/usr/local/etc/smb4.conf"
	backupPath := "/usr/local/etc/smb4.conf.pre-sylve"

	data, err := os.ReadFile(cfgPath)
	if err != nil {
		if !os.IsNotExist(err) {
			return err
		}
	} else {
		if !strings.Contains(string(data), marker) {
			exists, err := utils.FileExists(backupPath)
			if err != nil {
				return err
			}
			if !exists {
				if err := utils.CopyFile(cfgPath, backupPath); err != nil {
					return err
				}
			}
		}
	}

	var count int64
	if err := s.DB.Model(&sambaModels.SambaSettings{}).Count(&count).Error; err != nil {
		return err
	}
	if count == 0 {
		defaultSettings := sambaModels.SambaSettings{
			UnixCharset: "UTF-8",
			Workgroup:   "WORKGROUP",
		}
		if err := s.DB.Create(&defaultSettings).Error; err != nil {
			return err
		}
	}

	if err := s.Samba.WriteConfig(false); err != nil {
		return err
	}

	if exists, err := utils.FileExists("/var/log/samba4/audit.log"); err != nil {
		return err
	} else if !exists {
		if err := os.MkdirAll("/var/log/samba4", 0755); err != nil {
			return err
		}
		if _, err := os.Create("/var/log/samba4/audit.log"); err != nil {
			return err
		}
	}

	return system.ServiceAction("samba_server", "restart")
}

func (s *Service) InitSambaAdmins() error {
	cfg := config.ParsedConfig
	if cfg == nil {
		return nil
	}

	smbExists, err := sambaUtils.SambaUserExists("admin")
	if err != nil {
		logger.L.Error().Msgf("Error checking if Samba user 'admin' exists: %v", err)
		return err
	}

	if !smbExists {
		err = sambaUtils.CreateSambaUser("admin", cfg.Admin.Password)
		if err != nil {
			logger.L.Error().Msgf("Failed to create Samba user 'admin': %v", err)
			return err
		}
	} else {
		err = sambaUtils.EditSambaUser("admin", cfg.Admin.Password)
		if err != nil {
			logger.L.Error().Msgf("Failed to update Samba user 'admin': %v", err)
			return err
		}
	}

	return nil
}
