// Copyright Martin Dosch.
// Use of this source code is governed by the BSD-2-clause
// license that can be found in the LICENSE file.
//go:build !windows

package main

import (
	"fmt"
	"log/slog"
	osUser "os/user"
	"strconv"
	"syscall"
)

func dropPrivs() error {
	slog.Info("Trying to drop root privileges before connecting to the server")
	nobody, err := osUser.Lookup("nobody")
	if err != nil {
		slog.Info("failed to look up user nobody, will not drop privileges")
		return fmt.Errorf("failed to drop root privilege: %w", err)
	} else {
		gid, err := strconv.Atoi(nobody.Gid)
		if err != nil {
			return fmt.Errorf("failed to drop root privilege: %w", err)
		}
		uid, err := strconv.Atoi(nobody.Uid)
		if err != nil {
			return fmt.Errorf("failed to drop root privilege: %w", err)
		}
		err = syscall.Setgid(gid)
		if err != nil {
			slog.Info("failed to drop privileges to user nobody", "GID", gid)
			return fmt.Errorf("failed to drop root privilege: %w", err)
		}
		err = syscall.Setuid(uid)
		if err != nil {
			slog.Info("failed to drop privileges to user nobody", "UID", uid)
			return fmt.Errorf("failed to drop root privilege: %w", err)
		}
	}
	slog.Info("user identification", "UID", syscall.Getuid())
	slog.Info("user identification", "GID", syscall.Getgid())
	return nil
}
