#!/bin/sh /etc/rc.common
# NFSV4 init script for OpenWrt
# Copyright (C) 2025 OpenWrt.org

START=99
STOP=60
USE_PROCD=1

CONFIG_FILE="/etc/config/nfsd"
NFS_D=/var/lib/nfs
RPC_PIPEFS_D=/var/lib/nfs/rpc_pipefs
NFSDCLD_PID=/var/run/nfsdcld.pid

start_service() {
	logger -t "nfsd" -p notice "Starting the NFSV4 daemon"
	mkdir -p "$RPC_PIPEFS_D" "$NFS_D"
	chown nfs:nfs "$NFS_D"

	grep -q /proc/fs/nfsd /proc/mounts || mount -t nfsd nfsd /proc/fs/nfsd
	grep -q "$RPC_PIPEFS_D" /proc/mounts || mount -t rpc_pipefs sunrpc "$RPC_PIPEFS_D"

	procd_open_instance
	procd_set_param command /usr/sbin/nfsv4.exportd -f
	procd_close_instance

	procd_open_instance
	procd_set_param command /usr/sbin/rpc.idmapd -f
	procd_close_instance

	procd_open_instance
	procd_set_param command /usr/sbin/nfsdcld
	procd_append_param -F
	procd_close_instance

	/usr/sbin/exportfs -r

	procd_open_instance
	procd_set_param command /usr/sbin/rpc.nfsd -N 3
	procd_close_instance
}

stop_service() {
	/usr/sbin/rpc.nfsd 0
	/usr/sbin/exportfs -au
	/usr/sbin/exportfs -f
	/usr/bin/killall nfsdcld 2>/dev/null
	(
		sleep 1s
		grep -q "$RPC_PIPEFS_D" /proc/mounts && umount "$RPC_PIPEFS_D"
		grep -q /proc/fs/nfsd /proc/mounts && umount /proc/fs/nfsd
		) &
}

service_triggers() {
	export_dirs="$(while read -r mp _r; do echo "$mp "; done < /etc/exports)"
	procd_add_reload_mount_trigger "$export_dirs"
}
