#!/usr/bin/bash
#
# lve-kmod      Bring up/down lve kernel interface
# description: load and unload lve module
#
if [ -f /etc/sysconfig/lve ]; then
    . /etc/sysconfig/lve
elif [ -f /etc/default/lve ]; then
    . /etc/default/lve
else
    echo "lve config not found (looked in /etc/sysconfig/lve and /etc/default/lve)" >&2
    exit 1
fi

# Mount v1 cgroup hierarchies for Docker container deployments where the
# container init may not have done so (origin: 79ba5ced, 2017). Skip on
# cgroup-v2 unified systems: kmod-lve handles v2 natively since 2.1-58
# (CLKRN-2095), and these mount calls partially succeed on v2, leaving a
# hybrid state that makes kmod-lve refuse to load with -EINVAL.
if [ -e /sys/fs/cgroup ] && [ ! -e /sys/fs/cgroup/cgroup.controllers ]; then
    mount -o remount,rw /sys/fs/cgroup
    for item in freezer devices 'cpu,cpuacct' cpuset memory; do
        CGROUP_PATH="/sys/fs/cgroup/$item"
        if [ ! -d "$CGROUP_PATH" ]; then
            mkdir -p "$CGROUP_PATH"
        fi
        grep -q "$CGROUP_PATH" /proc/mounts
        if [ $? -ne 0 ]; then
            mount -t cgroup cgroup "$CGROUP_PATH" -o "$item"
        fi
    done
fi

# Check that lve is enabled.
[ "${LVE_ENABLE}" != "yes" ] && exit 0

# See how we were called.
case "$1" in
  start)
        # loading LVE module
        modprobe kmodlve || { echo "LVE module is missing" >&2; exit 1; }

        lvectl start
        for f in /etc/sysctl.d/*cloudlinux*.conf; do
            [ -e "$f" ] && sysctl -p "$f"
        done
        touch /var/lock/subsys/lve-kmod
        ;;
  stop)
        # unloading LVE module
        lvectl destroy all
        rmmod kmodlve || { echo "Cannot unload LVE module" >&2; exit 1; }
        rm -f /var/lock/subsys/lve-kmod
        ;;
  *)
        echo "Usage: $0 {start|stop}" >&2
        exit 1
esac

exit 0
