#!/bin/bash
SOURCE="$0"
source /usr/lib/elive-tools/functions
EL_REPORTS="1"
el_make_environment
. gettext.sh
TEXTDOMAIN="deliver"
export TEXTDOMAIN

export EL_DEBUG=0

# do not run on virtual machines, there's no USB and snapshotting it does false positives
source /etc/elive/machine-profile 2>/dev/null || true
if [[ "$MACHINE_VIRTUAL" = "yes" ]] ; then
    exit 0
fi

# determine the mount version
if grep -qsE "(^7\.|wheezy)" /etc/debian_version ; then
    LIVE_MOUNT_MAIN_d="/lib/live/mount"
else
    LIVE_MOUNT_MAIN_d="/run/live"
fi


main(){

    # get the partiton where the live system is mounted
    medium_part="$( cat /proc/mounts | grep "^/dev/.*${LIVE_MOUNT_MAIN_d}/medium" | awk '{print $1}' | grep -v "/dev/mapper/" | tail -1 )"
    if [[ ! -b "$medium_part" ]] ; then
        # this is like a strange buggy useless remount that happens here, replacing the previous one
        if ls $LIVE_MOUNT_MAIN_d/persistence/*/live/filesystem.*  1>/dev/null 2>&1 ; then
            medium_part="$( ls $LIVE_MOUNT_MAIN_d/persistence/*/live/filesystem.* | sed -e 's|/live/filesystem\..*$||g' | sort -u | head -1 )"
            medium_part="$( cat /proc/mounts | grep "${medium_part}" | awk '{print $1}' | tail -1 )"
        fi
        if [[ ! -b "$medium_part" ]] ; then
            medium_part="$( cat /proc/mounts | grep "${LIVE_MOUNT_MAIN_d}/persistence/sd.3" | awk '{print $1}' | grep "^/dev/" | grep -Fv "/dev/mapper/" | tail -1 )"
            if [[ ! -b "$medium_part" ]] ; then
                medium_part="$( cat /proc/mounts | grep "${LIVE_MOUNT_MAIN_d}/persistence/sd.2" | awk '{print $1}' | grep "^/dev/" | grep -Fv "/dev/mapper/" | tail -1 )"
                if [[ ! -b "$medium_part" ]] ; then
                    medium_part="$( cat /proc/mounts | grep "${LIVE_MOUNT_MAIN_d}/persistence/sd.1" | awk '{print $1}' | grep "^/dev/" | grep -Fv "/dev/mapper/" | tail -1 )"
                    if [[ ! -b "$medium_part" ]] ; then
                        medium_part="$( cat /proc/mounts | grep "${LIVE_MOUNT_MAIN_d}/persistence/sd.4" | awk '{print $1}' | grep "^/dev/" | grep -Fv "/dev/mapper/" | tail -1 )"
                        if [[ ! -b "$medium_part" ]] ; then
                            medium_part="$( cat /proc/mounts | grep "${LIVE_MOUNT_MAIN_d}/persistence/sd.5" | awk '{print $1}' | grep "^/dev/" | grep -Fv "/dev/mapper/" | tail -1 )"
                            if [[ ! -b "$medium_part" ]] ; then
                                # nvme ?
                                medium_part="$( cat /proc/mounts | grep "${LIVE_MOUNT_MAIN_d}/persistence/nvme" | awk '{print $1}' | grep "^/dev/" | grep -Fv "/dev/mapper/" | tail -1 )"
                                if [[ ! -b "$medium_part" ]] ; then
                                    medium_part="$( cat /proc/mounts | grep "${LIVE_MOUNT_MAIN_d}/persistence/mmcblk" | awk '{print $1}' | grep "^/dev/" | grep -Fv "/dev/mapper/" | tail -1 )"
                                fi
                            fi
                        fi
                    fi
                fi
            fi
        fi
        # try to detect systems like /dev/mapper/ventoy that doesn't exist on /dev/mapper/ later
        if [[ ! -b "$medium_part" ]] ; then
            medium_part="$( cat /proc/mounts | grep "^/dev/.*${LIVE_MOUNT_MAIN_d}/medium" | awk '{print $1}' | tail -1 )"
            if [[ "$medium_part" = "/dev/mapper/"* ]] ; then
                medium_part="${medium_part#/dev/mapper/}"
                if [[ -n "$medium_part" ]] ; then
                    medium_part="$( sudo -H partitions-list --show-all 2>/dev/null | grep -i "$medium_part" | awk -v FS="::" '{print $1}' | tail -1 )"
                fi
            fi
        fi
    fi
    if [[ "$medium_part" = "/dev/nvme"* ]] || [[ "$medium_part" = "/dev/mmcblk"* ]] ; then
        medium_dev="${medium_part%%p[0-9]*}"
    else
        medium_dev="${medium_part%%[0-9]*}"
    fi



    message_title="$( printf "$( eval_gettext "Error: OS access lost" )" "" )"
    message_body="$( printf "$( eval_gettext "Errors have been found in your live session. This may be due to your USB being moved, which causes a loss of access to the OS. Another possible cause could be errors on your USB/DVD. If this is the case, we recommend downloading Elive again and recording it onto a different medium." )" "" )"
    message_body_squashfs="$( printf "$( eval_gettext "It seems you accidentally moved your USB device, causing the OS access to be lost. Your system is now blocked; reboot your computer and avoid touching it while Elive is running." )" "" )"

    local message_disk_usage_title
    message_disk_usage_title="$( printf "$( eval_gettext "RAM Disk Usage Monitor" )" "" )"
    # local message_disk_usage_title_alert
    # message_disk_usage_title_alert="$( printf "$( eval_gettext "RAM Disk Space Alert" )" "" )"

    local message_disk_usage_warning
    message_disk_usage_warning="$( printf "$( eval_gettext "Warning: The free space on your RAM disk has reached 80% capacity. Your Live system may become unresponsive. We recommend deleting some temporary files you created or downloaded." )" "" )"
    local message_disk_usage_alert
    message_disk_usage_alert="$( printf "$( eval_gettext "Warning: Your free disk space on the RAM is nearly full. Delete some temporary files, or your Live system may soon become blocked due to lack of space." )" "" )"


    _CMDLINE="$(cat /proc/cmdline)"
    for arg in $_CMDLINE
    do
        [[ "$arg" = "persistence" ]] && is_persistence=1
        #[[ "$arg" = "thanatests" ]] && is_thanatests=1
        #[[ "$arg" = "boot=live" ]] && is_live=1
        #[[ "$arg" = "debug" ]] && is_debug=1
    done

    source /etc/default/locale
    if [[ -s "/usr/share/locale/${LANG%%_*}/LC_MESSAGES/deliver.mo" ]] ; then
        messages="/usr/share/locale/${LANG%%_*}/LC_MESSAGES/deliver.mo"
    else
        messages="/usr/share/locale/*/LC_MESSAGES/deliver.mo"
    fi

    # precache a notification:
    precache "$( which notify-send )"
    notify-send -t 10 -e -i bomb "test" "all good"
    #timeout 0.1 zenity --info

    while true ; do
        if ((is_persistence)) ; then
            if dmesg | grep -qs "I/O error.*dev.*${medium_dev}" ; then
                notify-send -u critical -e -t 903000 -i bomb "$message_title" "$message_body"
                sleep 10
                exit
            else
                if dmesg | grep -Fqs "SQUASHFS error" ; then
                    notify-send -u critical -e -t 903000 -i bomb "$message_title" "$message_body_squashfs"
                    sleep 10
                    exit
                fi
            fi
        else
            # [ 288.909561] SQUASHFS error: Unable to read page, block 11b3773e, size 17512
            # [ 288.909574] SQUASHFS error: Unable to read data cache entry [11b3773e]
            if dmesg | grep -Fqs "SQUASHFS error" ; then
                notify-send -u critical -e -t 903000 -i bomb "$message_title" "$message_body_squashfs"
                sleep 10
                exit
            fi

            # check for full disk too:
            disk_usage="$( df -m -P | awk '{if ($1 == "overlay") print $5}' | tail -1 )"
            disk_usage="${disk_usage%\%}"
            # alert
            if [[ "$disk_usage" -ge 94 ]] && ! el_flag check "is_disk_limit_alerted"; then
                el_notify "important" "dialog-warning" "$message_disk_usage_title" "$message_disk_usage_alert"
                el_flag add "is_disk_limit_alerted"
            else
                # warning
                if [[ "$disk_usage" -ge 72 ]] && ! el_flag check "is_disk_limit_warned"; then
                    el_notify "important" "dialog-information" "$message_disk_usage_title" "$message_disk_usage_warning"

                    el_flag add "is_disk_limit_warned"
                fi
            fi
        fi

        #precache "$0" /usr/bin/dmesg /usr/bin/grep /usr/lib/elive-tools/functions /usr/lib/notification-daemon/notification-daemon /usr/bin/notify-send /usr/share/icons/gnome/256x256/apps/bomb.png ${messages} /usr/bin/zenity  1>/dev/null
        precache "$0" /usr/bin/dmesg /usr/bin/grep /usr/lib/elive-tools/functions /usr/lib/notification-daemon/notification-daemon /usr/bin/notify-send /usr/share/icons/gnome/256x256/apps/bomb.png /usr/share/icons/gnome/256x256/status/dialog-information.png /usr/share/icons/gnome/256x256/status/dialog-warning.png  ${messages}  1>/dev/null
        sleep 20
    done

    # alternative to zenity:
    #yad --on-top --image=bomb --width=500 --center --no-buttons --title="$message_title" --text="$message_body"

}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
