#!/bin/bash

# -------------------------------------------------------------------------- #
# Copyright 2002-2021, OpenNebula Project, OpenNebula Systems                #
#                                                                            #
# Licensed under the Apache License, Version 2.0 (the "License"); you may    #
# not use this file except in compliance with the License. You may obtain    #
# a copy of the License at                                                   #
#                                                                            #
# http://www.apache.org/licenses/LICENSE-2.0                                 #
#                                                                            #
# Unless required by applicable law or agreed to in writing, software        #
# distributed under the License is distributed on an "AS IS" BASIS,          #
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #
# See the License for the specific language governing permissions and        #
# limitations under the License.                                             #
#--------------------------------------------------------------------------- #

# exit when any command fails
set -e

CGROUP_PATH=""
CPU_VAL=""
SYSDS_PATH=""
VM_ID=""

while getopts ":c:p:s:v:" opt; do
    case $opt in
        c) CGROUP_PATH="$OPTARG" ;; # root of cgroup FS
        p) CPU_VAL="$OPTARG" ;;     # cpu.shares value
        s) SYSDS_PATH="$OPTARG" ;;  # system datastore path
        v) VM_ID="$OPTARG" ;;       # VM id
    esac
done

# Check $CGROUP_PATH is an existing directory
if [ ! -d "$CGROUP_PATH" ]; then
    exit -1
fi

# Check $SYSDS_PATH is an existing directory
if [ ! -d "$SYSDS_PATH" ]; then
    exit -1
fi

regex_num='^[0-9]+$'

# Check $VM_ID is an integer
if ! [[ "$VM_ID" =~ $regex_num ]]; then
    exit -1
fi

# Check $CPU_VAL is an integer
if ! [[ "$CPU_VAL" =~ $regex_num ]]; then
    exit -1
fi

# Check $SYSDS_PATH/$VM_ID is a directory and not a symlink
if [ ! -d "$SYSDS_PATH/$VM_ID" ] || [ -L "$SYSDS_PATH/$VM_ID" ]; then
    exit -1
fi

###############################################################################
# Map the jailer chroot path to the OpenNebula VM location
###############################################################################
ROOTFS_PATH="/srv/jailer/firecracker/one-$VM_ID/root"
mkdir -p "$ROOTFS_PATH"
mount -o bind "$SYSDS_PATH/$VM_ID" "$ROOTFS_PATH"

###############################################################################
# Set cpu.shares value to restrict cpu usage
###############################################################################
mkdir -p "$CGROUP_PATH/cpu/firecracker/one-$VM_ID"
echo "$CPU_VAL" > "$CGROUP_PATH/cpu/firecracker/one-$VM_ID/cpu.shares"

