#!/bin/sh

BACKING_DIR=/var/cache/backing
MOUNTPOINT=/var/cache/cachefs

OPTS="-o allow_other -o auto_cache -onoexec,nodev,nosuid"
PIDFILE="/var/run/cachefs"
PIDOPT="--pid-file=$PIDFILE"

SIZE=96M        # size of tmpfs to create (only uses memory as required)
FIFO=/var/run/memcache_fifo
FIFO_OPT=
PERSIST_OPT=

MEM_NOTIFY=$(find /lib/modules -type f -name mem_notify.ko)

if test -f /nvram/disable-memcachefs; then
    echo "memcachefs not enabled"
    exit 0
fi

if test -z "${MEM_NOTIFY}"; then
    echo "mem_notify not present"
    exit 0
fi

if ! test -f /nvram/disable-memcachefs-backup; then
    FIFO_OPT="--file-events=$FIFO"
    PERSIST_OPT="--persist-dirs=/sdcard0/cachefs,/nvram/cachefs"
fi

COMMAND="$1"

case $COMMAND in
start)
    mkfifo $FIFO
    insmod ${MEM_NOTIFY} $MODARGS
    if test "$(roku_platform)" = "paolo"; then
        # Paolo's kernel is so old that mdev does not wake up and create the device.
        # We cannot use "mdev -s" as paolo plays tricks with multiple mdev.conf files,
        # so create the node by hand.
        major=$(awk '/mem_notify/{print $1}' /proc/devices)
        if test -n "$major"; then
            mknod -m 0600 /dev/mem_notify0 c $major 0 &&
            mknod -m 0600 /dev/mem_notify1 c $major 1
        fi
    fi &&
    mkdir -p $MOUNTPOINT $BACKING_DIR &&
    mount -t tmpfs tmpfs $BACKING_DIR -o size=$SIZE &&
    chmod 0777 $MOUNTPOINT &&
    memcachemount -r $BACKING_DIR $OPTS $PIDOPT $FIFO_OPT $PERSIST_OPT $MOUNTPOINT
    chown app /sys/module/mem_notify/parameters/minfree /dev/mem_notify1 $FIFO
    ;;

stop)
    test -f $PIDFILE  && kill $PIDFILE
    umount $BACKING_DIR
    rmmod mem_notify
    ;;
*)
    echo "usage: $0 start|stop"
    ;;
esac
