#!/bin/bash
SOURCE="$0"
source /usr/lib/elive-tools/functions
EL_REPORTS="1"
el_make_environment
# gettext functions
if [[ -x "/usr/bin/gettext.sh" ]] ; then
    . gettext.sh
else
    # make it compatible
    eval_gettext(){
        echo "$@"
    }
fi
TEXTDOMAIN="deliver"
export TEXTDOMAIN

# 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(){
    # pre {{{

    # USB with HYBRID image:
    #/dev/sdc1::filesystem::iso9660::Elive_2.8.4+_2017-03-09::Elive_2.8.4+_2017-03-09::2044786688::1.9 GB::
    #/dev/sdc::filesystem::iso9660::Elive_2.8.4+_2017-03-09::Elive_2.8.4+_2017-03-09::8127512576::7.6G::
    # USB with IMG image:
    # same thing but no "sdc" (no-partition main), also vfat as filesystem

    #  booted already with persistence, we don't want to run this hook
    # Note: not really needed, E is already saved and so no hooks (like this one) are launched then.
    # TODO FIXME:
    # Note2: but this only happens after the second persistence (first one launches desktop), maybe we should copy the .e dir at least, or the full user home? or the full system used until this point? hum...
    # update: this is not needed and simply buggy
    #if grep -Fqs "/mount/persistence" /proc/mounts ; then
        ## launched from desktop start hooks:
        #if [[ "$1" = "--auto" ]] ; then
            #exit
        #fi
    #fi


    local message_1
    message_1="$( printf "$( eval_gettext "This will enable you to retain session data, such as installed applications, your configurations, downloads, and all your work. However, using a low-quality USB drive may significantly slow down your experience in this mode. We recommend installing Elive on the hard disk to fully enjoy its capabilities." )" "" )"

    local message_2
    message_2="$( printf "$( eval_gettext "Elive supports Persistence, but if you want to use it you will need to run Elive from a USB thumb drive instead." )" "" )"

    local message_3
    message_3="$( printf "$( eval_gettext "Do you want to enable the Persistence feature? (saved sessions)" )" "" )"

    local message_4
    message_4="$( printf "$( eval_gettext "To use persistence, you need to run Elive on a physical machine. If you wish to save changes in a virtual machine, we suggest installing Elive on its hard disk." )" "" )"



    # virtual environment?
    source /etc/elive/machine-profile 2>/dev/null || true


    # - pre }}}

    # early exit if virtual machine
    if [[ "$MACHINE_VIRTUAL" = "yes" ]] ; then
        if grep -Fqs "persistence" /proc/cmdline ; then
            $guitool --info --text="$message_4" 2>/dev/null || true
        fi
        exit
    fi

    # exit if we are launched from desktop hooks (persistence existing, but not booted as to use it)
    if ! grep -Fqs "persistence" /proc/cmdline ; then
        if [[ "$1" = "--auto" ]] ; then
            # exit if we simply not wanted to use persistence
            exit
        fi
    fi


    guitool="/usr/bin/zenity --window-icon=/usr/share/icons/gnome/256x256/apps/logo-elive.png"

    medium_part="$( cat /proc/mounts | grep "^/dev/.*${LIVE_MOUNT_MAIN_d}/medium" | awk '{print $1}' | grep -Fv "/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 -F "${medium_part}" | awk '{print $1}' | tail -1 )"
        fi
        if [[ ! -b "$medium_part" ]] ; then
            medium_part="$( cat /proc/mounts | grep "^/dev/.*${LIVE_MOUNT_MAIN_d}/persistence/sd.3" | awk '{print $1}' | grep -Fv "/dev/mapper/" | tail -1 )"
            if [[ ! -b "$medium_part" ]] ; then
                medium_part="$( cat /proc/mounts | grep "^/dev/.*${LIVE_MOUNT_MAIN_d}/persistence/sd.2" | awk '{print $1}' | grep -Fv "/dev/mapper/" | tail -1 )"
                if [[ ! -b "$medium_part" ]] ; then
                    medium_part="$( cat /proc/mounts | grep "^/dev/.*${LIVE_MOUNT_MAIN_d}/persistence/sd.1" | awk '{print $1}' | grep -Fv "/dev/mapper/" | tail -1 )"
                    if [[ ! -b "$medium_part" ]] ; then
                        medium_part="$( cat /proc/mounts | grep "^/dev/.*${LIVE_MOUNT_MAIN_d}/persistence/sd.4" | awk '{print $1}' | grep -Fv "/dev/mapper/" | tail -1 )"
                        if [[ ! -b "$medium_part" ]] ; then
                            medium_part="$( cat /proc/mounts | grep "^/dev/.*${LIVE_MOUNT_MAIN_d}/persistence/sd.5" | awk '{print $1}' | grep -Fv "/dev/mapper/" | tail -1 )"
                            if [[ ! -b "$medium_part" ]] ; then
                                # nvme ?
                                medium_part="$( cat /proc/mounts | grep "^/dev/.*${LIVE_MOUNT_MAIN_d}/persistence/nvme" | awk '{print $1}' | grep -Fv "/dev/mapper/" | tail -1 )"
                                if [[ ! -b "$medium_part" ]] ; then
                                    medium_part="$( cat /proc/mounts | grep "^/dev/.*${LIVE_MOUNT_MAIN_d}/persistence/mmcblk" | awk '{print $1}' | 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 [[ ! -b "$medium_part" ]] ; then
        unset medium_part
    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
    medium_part_fs="$( sudo -H partitions-list --show-only="$medium_part" | awk -v FS="::" '{print $3}' )"

    # by knowing the disk of the live system we can know from where comes our persistence partition
    persistence_partition="$( sudo -H partitions-list --show-all-raw 2>/dev/null | grep -E "^${medium_dev}.*::(persistence)::" | awk -v FS="::" '{print $1}' | tail -1 )"
    if [[ -n "$persistence_partition" ]] ; then
        persistence_mountpoint="$( sudo -H mounts-manager --get-mountpoint "$persistence_partition" 2>/dev/null )"

        if [[ -z "$persistence_mountpoint" ]] ; then
            persistence_partition="$( sudo cat /proc/mounts | grep -E "^/dev/.*${LIVE_MOUNT_MAIN_d}/persistence/${persistence_partition##*/}\s+" | awk '{print $1}' )"
            persistence_mountpoint="$( sudo -H mounts-manager --get-mountpoint "$persistence_partition" 2>/dev/null )"
        fi
    fi

    # exit if already using
    # we are using persistence, this tool is not needed
    if [[ -n "$persistence_partition" ]] && [[ "$( sudo -H ls -1 "$persistence_mountpoint" | wc -l )" -gt 1 ]]  ; then
        exit
    fi


    # check and tell {{{
    if [[ "$medium_part" = "/dev/sr"* ]] ; then
        is_cdrom=1
        is_usb=0
    fi
    if [[ "$medium_part" = "/dev/nvme"* ]] || [[ "$medium_part" = "/dev/mmcblk"* ]] ; then
        is_usb=1
        is_cdrom=0
        # note: this variable cannot be set if we are not /dev/sdX (not /dev/sr0 for example)
        medium_disk="${medium_part%%p[0-9]*}"
    fi
    if [[ "$medium_part" = "/dev/sd"* ]] ; then
        is_usb=1
        is_cdrom=0
        # note: this variable cannot be set if we are not /dev/sdX (not /dev/sr0 for example)
        medium_disk="${medium_part%%[0-9]*}"
    fi
    if [[ "$medium_part_fs" = "iso9660" ]] ; then
        is_image_hybrid=1
        # can be usb (hybrid)
    fi
    # ventoy cases
    if [[ "$medium_part_fs" = "exfat" ]] && [[ -b /dev/mapper/ventoy ]] ; then
        is_image_hybrid=1
        is_cdrom=0
        is_usb=1
    fi
    if [[ "$medium_part_fs" = "vfat" ]] ; then
        is_image_img=1
        is_cdrom=0
    fi
    if sudo -H partitions-list --show-all-raw 2>/dev/null | grep -qsE "^${medium_disk}.*::(persistence)::" ; then
        is_partition_persistence_existing=1
    fi




    # if we have a partition for persistence already set up, maybe we want to remove / clean it up ? (use launched the helper from the desktop, not from auto hooks)
    if ! grep -Fqs "persistence" /proc/cmdline ; then
        if ((is_partition_persistence_existing)) ; then
            is_persistence_wanted=1
            # was_persistence_already_existing=1
            true
        fi
    fi

    # not possible to use persistence
    if ((is_cdrom)) ; then
        $guitool --info --text="$message_2 $message_1" 2>/dev/null || true
        exit
    fi


    # ask if continue
    if ! ((is_persistence_wanted)) ; then

        if ((is_partition_persistence_existing)) ; then
            $guitool --warning --text="$( eval_gettext "You have an unused persistence partition, you can either recreate it or reboot and choose Persistence mode to use it." )" 2>/dev/null
        fi

        #only ask if we don't know that we want it
        if ! $guitool --question --text="Persistence: $message_3 $message_1" 2>/dev/null ; then
            exit
        fi
    fi

    # check
    if [[ -z "$medium_disk" ]] ; then
        result="$( sudo -H partitions-list --show-all --show-disks | grep -F '::(entire disk)::' | awk -v FS="::" '{print $1"\n"$7}' |  $guitool --list --column="" --column="Size" --text="$( eval_gettext "Select your Live USB device to create the Persistence partition." )" || echo cancel )"
        if [[ "$result" = "cancel" ]] ; then
            exit 1
        fi
        if [[ ! -b "$result" ]] ; then
            $guitool --error --text="$( eval_gettext "I can't find your Live USB thumb drive, so you need to manually create a partition for Persistence using Gparted or Gnome-disks, then run a command with the partition you chose." ) sudo persistence-create /dev/sdb3" 2>/dev/null
            exit
        fi
        medium_disk="$result"
    fi

    # check that is a removable device
    if [[ "$( cat "/sys/block/${medium_disk##*/}/removable" )" != 1 ]] && ! sudo -H udevadm info --query=all --name="${medium_disk}" | grep -qs "^E: DEVPATH=.*/usb" ; then
        local message_removabl
        message_removabl="$( printf "$( eval_gettext "Warning: The detected device %s is not showing as a removable device. Please ensure this is the USB thumb drive you used to boot Elive. Do you want to continue?" )" "$medium_disk" )"

        if ! $guitool --question --text="$message_removabl" 2>/dev/null ; then
            exit
        fi
    fi

    # - check and tell }}}

    # set the default Elive wallapper before to save the configuration
    if [[ "$E_START" ]] ; then
        if [[ -e "/usr/share/enlightenment/data/backgrounds/Elive Stars.edj" ]] ; then
            killall enlightenment-wallpapers-switcher 2>/dev/null || true
            enlightenment_remote -desktop-bg-set "/usr/share/enlightenment/data/backgrounds/Elive Stars.edj"
        fi

        sync
        enlightenment_remote -save
    fi

    sudo persistence-create "$medium_disk"

    #if ! ((was_persistence_already_existing)) ; then
        #if sudo -H partitions-list --show-all-raw 2>/dev/null | grep -qsE "^${medium_disk}.*::(persistence|crypto_LUKS)::" ; then
            #el_request_donation
        #fi
    #fi

}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
