#!/bin/bash

set -e

# Function to create and mount overlay
mount_overlay() {
    local target_dir=$1
    local size=$2

    # Create base directory
    if [ ! -d "/overlayfs/${target_dir}" ]; then
        sudo mkdir -p "/overlayfs/${target_dir}"
        sudo chmod 755 "/overlayfs/${target_dir}"
    fi

    # Mount tmpfs
    if ! mountpoint -q "/overlayfs/${target_dir}"; then
        sudo mount -t tmpfs -o size=${size} tmpfs "/overlayfs/${target_dir}" -o mode=0755
        echo "mounted tmpfs ${target_dir}"
    fi

    # Create upper and work directories
    if [ ! -d "/overlayfs/${target_dir}/upper" ]; then
        sudo mkdir -p "/overlayfs/${target_dir}/upper"
        sudo chmod 755 "/overlayfs/${target_dir}/upper"
    fi
    if [ ! -d "/overlayfs/${target_dir}/work" ]; then
        sudo mkdir -p "/overlayfs/${target_dir}/work"
        sudo chmod 755 "/overlayfs/${target_dir}/work"
    fi

    # Mount overlay
    if ! mountpoint -q "${target_dir}"; then
        sudo mount -t overlay overlay -o lowerdir="${target_dir}",upperdir="/overlayfs/${target_dir}/upper",workdir="/overlayfs/${target_dir}/work" "${target_dir}"
        echo "mounted overlay ${target_dir}"
    fi
}

# /var directory with max RAM size
#mount_overlay /etc 100M

# /var directory with max RAM size
mount_overlay /var 200M

# /tmp directory with max RAM size
mount_overlay /tmp 100M

# /run directory with max RAM size
mount_overlay /run 100M

echo "OverlayFS setup completed successfully."
