package utils

import (
	"fmt"
	"syscall"
	"unsafe"
)

// These constants are from /usr/include/linux/ipc.h
const (
	ipcPrivate = 0
	ipcRmID    = 0
	ipcCreate  = 00001000
)

func ShmCreate(size int, key uint32) (shmid uintptr, addr unsafe.Pointer, err error) {
	shmid, _, errno0 := syscall.RawSyscall(syscall.SYS_SHMGET, uintptr(key), uintptr(size), 0600|ipcCreate)
	if errno0 != 0 {
		return 0, unsafe.Pointer(uintptr(0)), fmt.Errorf("shmget: %v", errno0)
	}
	p, _, errno1 := syscall.RawSyscall(syscall.SYS_SHMAT, shmid, 0, 0)

	if errno1 != 0 {
		return 0, unsafe.Pointer(uintptr(0)), fmt.Errorf("shmat: %v", errno1)
	}

	return shmid, unsafe.Pointer(p), nil
}

func ShmDT(p unsafe.Pointer) error {
	_, _, errno := syscall.RawSyscall(syscall.SYS_SHMDT, uintptr(p), 0, 0)
	if errno != 0 {
		return fmt.Errorf("shmdt: %v", errno)
	}
	return nil
}

func ShmRm(shmid uintptr) error {
	_, _, errno := syscall.RawSyscall(syscall.SYS_SHMCTL, shmid, ipcRmID, 0)
	if errno != 0 {
		return fmt.Errorf("shmrm: %v", errno)
	}
	return nil
}
