#!/bin/ash

# Remount original rootfs as read-write 
echo "Mounting / as read-write"
mount -o remount,rw /

# Define the location of detected packages file
DETECTED_PACKAGES_FILE="/tmp/detected_packages.tmp"
LIST_FILE_DELETED=false

# Clear temp file before begining
rm -f "$DETECTED_PACKAGES_FILE" 
# Function to check if a specific bundled package is already installed and delete its list file
detect_and_remove_list_files() {
    local package_name="$1"
    local list_file="/usr/lib/opkg/info/${package_name}.list"

    # Check if the bundled package is installed by checking its .list file
    if [ -f "$list_file" ]; then
        echo "$package_name is already installed. Deleting its $list_file to avoid future conflicts."
        rm -f "$list_file"
        echo "$package_name" >> "$DETECTED_PACKAGES_FILE"
        LIST_FILE_DELETED=true
    else
        echo "$package_name is not currently installed."
		echo "$package_name is included in this package and will be installed."
    fi
}

# Check for installed packages and handle accordingly
detect_and_remove_list_files "libinotifytools"
detect_and_remove_list_files "inotifywait"

# Report if any packages were detected and list them
if [ -f "$DETECTED_PACKAGES_FILE" ]; then
    echo "Detected the following installed packages, which were handled to avoid clashes:"
    cat "$DETECTED_PACKAGES_FILE"
else
    echo "No pre-existing bundled packages detected."
fi

# If any list files were deleted, show a warning message at the end of the script
if [ "$LIST_FILE_DELETED" = true ]; then
    echo -e "\e[31m================================================\e[0m"
    echo -e "\e[31mPre-bundled packages detected\e[0m"
    echo -e "\e[32mAssociation between said packages and respective files has been removed\e[0m"
    echo -e "\e[31m================================================\e[0m"
    echo -e "\e[31mopkg will fail now\e[0m"
    echo -e "\e[32mYou need to try installing this package again\e[0m"
    echo -e "\e[32mThen it will work\e[0m"
    echo -e "\e[31m================================================\e[0m"
    echo -e "\e[32m================================================\e[0m"
fi

# Check if /etc is mounted
if grep -qs '/etc' /proc/mounts; then
    echo "Unmounting /etc..."
    umount -lf /etc
fi

# Check if /usrdata is mounted
if grep -qs '/usrdata' /proc/mounts; then
    echo "/usrdata is mounted. Unmounting /etc again to access rootfs /etc..."
    umount -lf /etc
fi

exit 0
