#!/bin/bash
#
# cagefs        Startup script for CageFS

solo_marker="/etc/cloudlinux-edition-solo"
container_marker="/etc/cloudlinux-container"
cagefs_bin="/usr/sbin/cagefsctl"
lvectl_bin="/usr/sbin/lvectl"

if [ -e "$solo_marker" ] || [ -e "$container_marker" ]; then
    lvectl_bin="/bin/true"
fi

RETVAL=0

start() {
    $cagefs_bin --mount-skel
    RETVAL=$?
    if [ $RETVAL -ne 0 ]; then
        return $RETVAL
    fi

    $lvectl_bin destroy all --force
    RETVAL=$?
    if [ $RETVAL -ne 0 ]; then
        return $RETVAL
    fi

    if [ -e "$solo_marker" ] || [ -e "$container_marker" ]; then
        # CL in container
        /usr/sbin/cagefsctl --delete-namespaces
    fi

    sleep 1

    $cagefs_bin --remove-unused-mount-points

    if [ -e "$solo_marker" ] || [ -e "$container_marker" ]; then
        # CL in container
        /usr/sbin/cagefsctl --create-namespaces
    fi

    $lvectl_bin apply all --force
    RETVAL=$?
    rm -f /usr/share/cagefs/need.remount
    return $RETVAL
}

restart() {
    start
}

stop() {
    $cagefs_bin --unmount-skel
    RETVAL=$?
    if [ $RETVAL -ne 0 ]; then
        return $RETVAL
    fi

    $lvectl_bin destroy all
    RETVAL=$?
    if [ $RETVAL -ne 0 ]; then
        return $RETVAL
    fi

    sleep 1

    if [ -e "$solo_marker" ] || [ -e "$container_marker" ]; then
        # CL in container
        /usr/sbin/cagefsctl --delete-namespaces
    fi

    $cagefs_bin --remove-unused-mount-points

    $lvectl_bin apply all
    RETVAL=$?
    return $RETVAL
}


# See how we were called.
case "$1" in
    start)
        start
        ;;
    restart)
        if [ -e /usr/share/cagefs/skip.cagefs.restart ]; then
            rm -f /usr/share/cagefs/skip.cagefs.restart
            exit 0
        fi
        restart
        ;;
    stop)
        stop
        ;;
    *)
        echo $"Usage: $0 {start|restart|stop}"
        exit 1
esac

exit $RETVAL
