#!/bin/bash
source /usr/lib/elive-tools/functions

main(){
    # pre {{{
    local var
    target="/mnt/target-$$"

    if [[ -d "$target" ]] ; then
        el_error "target $target already exist"
        exit 1
    fi

    mkdir -p "$target"

    # }}}

    # show partitions
    partitions="$( partitions-list --show-all --show-raw --show-disks )"

    elive_root="$( echo "$partitions" | grep -i "::elive_os::" | sed -e 's|::.*$||g' )"
    if [[ -z "$elive_root" ]] ; then
        # First, check if there is a LUKS partition already identified as Elive_OS
        # (e.g. if it was already opened or has a specific label)
        luks_elive="$( echo "$partitions" | grep -i "::crypto_LUKS::" | grep -i "elive_os" | sed -e 's|::.*$||g' | head -n 1 )"
        if [[ -b "$luks_elive" ]] ; then
             el_info "Found encrypted Elive OS partition: $luks_elive"
             el_info "Insert your admin / root password to unlock your disk:"
             crypt_name="${luks_elive##*/}_crypt"
             if cryptsetup luksOpen "$luks_elive" "$crypt_name" ; then
                 sync ; sleep 2
                 if [[ -b "/dev/mapper/elive_vg-root_lv" ]] ; then
                     elive_root="/dev/mapper/elive_vg-root_lv"
                 elif [[ -b "/dev/mapper/$crypt_name" ]] ; then
                     $0
                     exit
                 fi
             fi
        fi
    fi

    if [[ -z "$elive_root" ]] ; then
        # Search for LUKS partitions that might be Elive root
        while read -r luks_part ; do
            [[ -z "$luks_part" ]] && continue

            # Determine the disk of this partition to look for Elive_boot
            # Handles /dev/sda3 -> /dev/sda and /dev/nvme0n1p3 -> /dev/nvme0n1
            if [[ "$luks_part" =~ p[0-9]+$ ]] ; then
                disk_path="${luks_part%p*}"
            else
                disk_path="${luks_part%[0-9]*}"
            fi

            # Check if there's an Elive_boot partition on the same disk
            if echo "$partitions" | grep "$disk_path" | grep -qi "::Elive_boot::" ; then
                el_info "Found potential encrypted Elive system on $luks_part"
                el_info "Insert your admin / root password to unlock your disk:"

                crypt_name="${luks_part##*/}_crypt"
                if cryptsetup luksOpen "$luks_part" "$crypt_name" ; then
                    sync ; sleep 2
                    if [[ -b "/dev/mapper/elive_vg-root_lv" ]] ; then
                        elive_root="/dev/mapper/elive_vg-root_lv"
                        break
                    elif [[ -b "/dev/mapper/$crypt_name" ]] ; then
                        # Re-scan partitions to see if the opened mapper is Elive_OS
                        new_partitions="$( partitions-list --show-all --show-raw --show-disks )"
                        elive_root="$( echo "$new_partitions" | grep "/dev/mapper/$crypt_name" | grep -i "::elive_os::" | sed -e 's|::.*$||g' )"

                        if [[ -n "$elive_root" ]] ; then
                            break
                        else
                            # If it's not Elive_OS, maybe we need a full re-run or it's just not it
                            $0
                            exit
                        fi
                    fi
                fi
            fi
        done <<< "$( echo "$partitions" | grep -i "::crypto_LUKS::" | sed -e 's|::.*$||g' )"
    fi
    # check
    if [[ "$( echo "$elive_root" | wc -l )" -gt 1 ]] || [[ ! -b "$elive_root" ]] ; then
        el_warning "Elive OS root not found, please enter the device path manually:"
        echo -e "$partitions"
        el_info "Insert root partition device path:"
        read -e elive_root

        if ! [[ -b "$elive_root" ]] ; then
            exit 1
        fi
    fi

    # mount
    mount -o dev "$elive_root" "$target"

    # other mounts
    while read -ru 3 line
    do
        dev="$( echo "$line" | awk '{print $1}' )"
        point="$( echo "$line" | awk '{print $2}' )"
        if [[ "$dev" = "UUID="* ]] ; then
            dev="/dev/disk/by-uuid/${dev#UUID=}"
        fi
        # skips
        if [[ "$dev" != "/dev"* ]] ; then
            continue
        fi
        if ! echo "$point" | grep -qsE "^(/boot)" ; then
            continue
        fi

        echo "found '$dev' to '$point'"
        mkdir -p "$target/$point"
        mount -o dev "$dev" "$target/$point"

    done 3<<< "$( cat "$target/etc/fstab" | psort -- -p "/boot\s" -p "/boot/efi" )"

    # layers
    mounts-manager --chroot-layers-mount "$target" bind bind
    el_info "Chroot inside:"

    chroot "$target"

    el_info "Exiting chroot..."
    mounts-manager --chroot-layers-umount "$target" bind bind

    umount "$target/boot/efi" 2>/dev/null || true
    umount "$target/boot" 2>/dev/null || true
    umount "$target" 2>/dev/null || true

    rmdir "$target"

}

#
#  MAIN
#
main "$@"

# vim: set foldmethod=marker :
