# This file is part of the 'dragora-installer'.
#
# Purpose: Swap detector, formatter.

# A function to produce the fstab entry for the physical swap partition
add_fstabEntry()
{
    printf '%-43s %-14s %-12s %-16s %-3s %s\n' \
     "$1" "swap" "swap" "defaults" "0" "0" >> "${SUBTMPDIR}/fstab"
}

# Get and print device size
get_size()
{
    lsblk --noheadings --nodeps --output SIZE "$1"
}

# Add device names to the checklist (to be shown)
set_checklist()
{
    while IFS= read -r line
    do
        echo "\"${line}\" \"$(get_size $line)\" ON \\" >> "$2"
    done < "$1"

    # End Of
    echo " 2> \${SUBTMPDIR}/$3" >> "$2"
}

### Detection and addition of inactive/active swap devices

swaplist="$(fdisk -l | awk '/Linux swap/{ print $1 }')"

if test -z "$swaplist"
then
    dialog --colors \
     --backtitle "\\ZbSwap detection" \
     --title "NO SWAP PARTITION DETECTED" \
     --cr-wrap --yesno \
"No swap partition has been detected.

Setting up a swap partition is recommended because
it will enable the system to use available physical
memory (RAM) more efficiently and also provide a
safeguard in situations where RAM is exhausted.

If you want to make use of hibernation (suspend to
disk), a swap partition of sufficient size is
required.

Would you like to proceed without a swap partition?" 17 55 || \
    {
        printf '%s' \
"
Please create a swap partition using fdisk(8) or cfdisk(8).
Then re-run the installer to give it the proper formatting.

You can also use mkswap(8) and swapon(8) to format and
activate the partition in advance.
"
        exit 99;
    }
    unset add_fstabEntry get_size set_checklist swaplist
    return 0
fi

rm -f "${SUBTMPDIR}/MakeSwap_active.list" \
      "${SUBTMPDIR}/MakeSwap_inactive.list"
for device in $swaplist
do
    if swapon --noheadings --show=NAME | grep -q "$device"
    then
        echo "$device" >> "${SUBTMPDIR}/MakeSwap_active.list"
    else
        echo "$device" >> "${SUBTMPDIR}/MakeSwap_inactive.list"
    fi
done
unset -v device swaplist

### ^ End Of 'Detection, addition of active and inactive swap devices'

### Check for active swap devices

if test -s "${SUBTMPDIR}/MakeSwap_active.list"
then
    # Compose output file to be shown

    printf '%s\n' \
     'dialog --colors \'                                           \
     ' --backtitle "\\ZbActive Swap devices" \'                    \
     ' --title "ACTIVE SWAP DEVICES" \'                            \
     ' --nocancel --cr-wrap --checklist \'                         \
'"The following swap devices have already been activated:'         \
''                                                                 \
'By default all partitions are marked to be added to the'          \
'file system representation table (/etc/fstab) in order to'        \
'be loaded at boot time.  You can deselect the partition(s)'       \
'you do not want to add or load at system startup using'           \
'the \\Z3[Space]\\Zn key, then press \\Z3[Enter]\Zn to continue."  \
16 65 3 \' > "${SUBTMPDIR}/MakeSwap_active"

    set_checklist "${SUBTMPDIR}/MakeSwap_active.list" \
     "${SUBTMPDIR}/MakeSwap_active" return-MakeSwap_active
fi

if test -s "${SUBTMPDIR}/MakeSwap_active"
then
    . "${SUBTMPDIR}/MakeSwap_active"

    if test -s "${SUBTMPDIR}/return-MakeSwap_active"
    then
        # Append new line for reading
        echo "" >> "${SUBTMPDIR}/return-MakeSwap_active"

        IFS= read -r REPLY < "${SUBTMPDIR}/return-MakeSwap_active" || exit 2;

        for device in $REPLY
        do
            add_fstabEntry "$device"
        done

        unset -v REPLY device
    fi
fi

### ^ End Of 'Check for active swap devices'

### Check for inactive swap devices

if test -s "${SUBTMPDIR}/MakeSwap_inactive.list"
then
    # Compose output file to be shown

    printf '%s\n' \
     'dialog --colors \'                                           \
     ' --backtitle "\\ZbInactive Swap devices" \'                  \
     ' --title "INACTIVE SWAP DEVICES" \'                          \
     ' --nocancel --cr-wrap --checklist \'                         \
'"The following swap partitions has been detected:'                \
''                                                                 \
'By default all partitions found will be formatted and added'      \
'to the file system representation table (/etc/fstab) in order'    \
'to be loaded at boot time.  You can deselect the partition(s)'    \
'you do not want to format or load at system startup using'        \
'the \\Z3[Space]\\Zn key, then press \\Z3[Enter]\Zn to continue."  \
16 65 3 \' > "${SUBTMPDIR}/MakeSwap_inactive"

    set_checklist "${SUBTMPDIR}/MakeSwap_inactive.list" \
     "${SUBTMPDIR}/MakeSwap_inactive" return-MakeSwap_inactive
fi

if test -s "${SUBTMPDIR}/MakeSwap_inactive"
then
    . "${SUBTMPDIR}/MakeSwap_inactive"

    if test -s "${SUBTMPDIR}/return-MakeSwap_inactive"
    then
        # Append new line for reading
        echo "" >> "${SUBTMPDIR}/return-MakeSwap_inactive"

        IFS= read -r REPLY < "${SUBTMPDIR}/return-MakeSwap_inactive" || exit 2;

        for device in $REPLY
        do
            # Set up temporary random files related to the menu
            tempfile="${SUBTMPDIR}/return_MakeSwap_format${RANDOM-0}$$"

            dialog --colors \
             --backtitle "\\ZbInactive Swap device"  \
             --title "SWAP FORMAT FOR $device"       \
             --ok-label "Format"                     \
             --cancel-label "Ignore & Continue"      \
             --cr-wrap --checklist                   \
"A swap device has been chosen.

We offer the possibility to format it properly,
as well as you can simply ignore this part and
continue if you previously formatted it:

Device name: $device [$(get_size $device)]" 14 51 1 \
"$device"    "Check for bad blocks (slow)" off \
            2> $tempfile || continue;

            dialog --clear

            echo "Making swap device $device ..."
            echo ""

            if test -s "$tempfile"
            then
                mkswap -c "$device"
            else
                mkswap "$device"
            fi

            echo ""
            echo "Activating swap device (${device}) ..."
            echo ""

            swapon -v -f "$device"
            sleep 6
            add_fstabEntry "$device"
        done

        unset -v REPLY device tempfile
    fi
fi

### ^ End Of 'Check for inactive swap devices'

unset -f add_fstabEntry get_size set_checklist

