#!/bin/bash

set -e

# Function to unmount overlay and tmpfs, and remove directories
unmount_overlay() {
    local target_dir=$1
    local base_dir="/overlayfs/${target_dir}"

    # Unmount tmpfs
    if mountpoint -q "${base_dir}"; then
        echo "Unmounting tmpfs from ${base_dir}"
        echo "Command: sudo umount -l ${base_dir}"
        sudo umount -l "${base_dir}" || { echo "Failed to unmount tmpfs from ${base_dir}"; exit 1; }
        echo "Unmounted tmpfs from ${base_dir}"
    else
        echo "No tmpfs mounted on ${base_dir}"
    fi

    # Unmount overlay
    if mountpoint -q "/${target_dir}"; then
        echo "Unmounting overlay from ${target_dir}"
        echo "Command: sudo umount -l /${target_dir}"
        sudo umount -l /"${target_dir}" || { echo "Failed to unmount overlay from ${target_dir}"; exit 1; }
        echo "Unmounted overlay from ${target_dir}"
    else
        echo "No overlay mounted on ${target_dir}"
    fi

    # Remove directories
    if [ -d "${base_dir}" ]; then
        echo "Clearing work and upper directories in ${base_dir}"
        sudo rm -rf "${base_dir}/work/*"
        sudo rm -rf "${base_dir}/upper/*"
        echo "Removed work and upper directories in ${base_dir}"
    else
        echo "Directory ${base_dir} does not exist"
    fi
}

# /var directory
unmount_overlay etc

# /var directory
unmount_overlay var

# /tmp directory
unmount_overlay tmp

# /run directory
unmount_overlay run

echo "OverlayFS cleanup completed successfully."
