#!/bin/bash
# /etc/rc.d/rc.local

# AMOS Ghostnet: Execute custom user boot scripts.
# Because IMA enforces signatures on executed files (BPRM_CHECK),
# we use the '.' (source) builtin to load these scripts. 
# Sourcing reads the file as data, bypassing IMA execution checks.

# if [ -d /etc/amos/rc.local.d ]; then
#     for script in /etc/amos/rc.local.d/*.sh; do
#         if [ -r "$script" ]; then
#             echo "Running local boot script: $script"
#             bash "$script"
#         fi
#     done
# fi
mkdir -p /etc/amos/rc.local.d
chown root:root /etc/amos/rc.local.d
chmod 0700 /etc/amos/rc.local.d
# Ensure the drop-in directory exists and is secure
DROPIN_DIR="/etc/amos/rc.local.d"
if [ -d "$DROPIN_DIR" ]; then
    for script in "$DROPIN_DIR"/*; do
        [ -f "$script" ] || continue
        [ -r "$script" ] || continue

        # Read the first line to check for a shebang
        read -r first_line < "$script"

        if [[ "$first_line" =~ ^#! ]]; then
            # Extract the interpreter basename (e.g., /usr/bin/python3 -> python3)
            interp_path=$(echo "${first_line#\#\!}" | awk '{print $1}')
            interp_name=$(basename "$interp_path")

            # SECURE ALLOWLIST: Only permit known safe interpreters
            case "$interp_name" in
                bash|sh|dash)
                    echo "Running local boot script: $script (via $interp_name)"
                    "$interp_name" "$script"
                    ;;
                python3|python|node|php)
                    # Ensure the interpreter actually exists
                    if command -v "$interp_name" >/dev/null 2>&1; then
                        echo "Running local boot script: $script (via $interp_name)"
                        "$interp_name" "$script"
                    else
                        echo "Warning: $interp_name not found for $script" >&2
                    fi
                    ;;
                *)
                    # BLOCK EVERYTHING ELSE
                    echo "SECURITY WARNING: Blocked $script. Unapproved shebang: $interp_name" >&2
                    ;;
            esac
        else
            # Default to bash if there is no shebang
            echo "Running local boot script: $script (default bash)"
            bash "$script"
        fi
    done
fi

exit 0

exit 0