package utils

import (
	"log"
	"os/user"
	"strconv"
	"syscall"
)

func DropPrivileges(username string) {
	currentUser, err := user.Current()
	if err != nil {
		log.Fatal(err)
	}

	if currentUser.Uid == "0" {
		return
	}

	targetUser, err := user.Lookup(username)
	if err != nil {
		log.Fatal(err)
	}
	uid, err := strconv.Atoi(targetUser.Uid)
	if err != nil {
		log.Fatal(err)
	}
	gid, err := strconv.Atoi(targetUser.Gid)
	if err != nil {
		log.Fatal(err)
	}
	err = syscall.Setuid(uid)
	if err != nil {
		log.Fatal(err)
	}

	err = syscall.Setgid(gid)
	if err != nil {
		log.Fatal(err)
	}

}
