#!/bin/bash
# Under the terms of the 'COPYRIGHT.TXT' file.

# Men primario:
dialog \
 --title "SWAP PARTITION" \
 --cancel-label "Continue" \
 --menu \
"You have two options to make the swap partition.\n\n\
One is formatting the swap partition, and the other \n\
is creating a swap file in the root partition (after\n\
the installer will ask).\n\n\
What do you want?:" 0 0 0 \
 "Partition" "Make swap partition" \
 "File" "Create a swap file (expert)" \
  2> ${TMP}/return-menu-swap
CODE=$?; (( $CODE != 0 )) && exit $CODE;
# Verifica la opcin de archivo swap:
if grep -q File ${TMP}/return-menu-swap ; then
  touch ${TMP}/set-swapfile
  exit;
fi

# Comprueba la existencia de una particin swap:
if ! probe -l 2> /dev/null | grep -q -m 1 swap ; then
  dialog \
   --title "SWAP PARTITION NOT DETECTED" \
   --defaultno \
   --yesno \
"\nWould you like to proceed without a swap partition?" 7 55
  if (( $? != 0 )); then
    dialog \
     --title "SWAP PARTITION" \
     --infobox \
"\nTry to create the swap partition using 'fdisk' or 'cfdisk'.\n\n" 5 63
    exit 99;
  else
    exit 0;
  fi
fi

# Asigna valores como el dispositivo y el tamao:
SWAP="$(probe -l 2> /dev/null | grep -m 1 swap)"
DEVICE=${SWAP%% *}
SIZE=$(echo "$SWAP" | awk '{ print $4 }' | tr -d '+, ')

# Men secundario:
dialog \
 --backtitle "Setting the swap partition" \
 --title "SWAP PARTITION" \
 --ok-label "Format" \
 --cancel-label "Continue" \
 --checklist \
"Swap partition detected:\n\n\
${DEVICE} - ${SIZE} K" 10 47 1 \
 "$DEVICE"  "Check for bad blocks" off \
  2> ${TMP}/return-mk_swap
if (( $? == 0 )); then
  if [[ -s ${TMP}/return-mk_swap ]]; then
    dialog \
     --title "SWAP PARTITION (${DEVICE})" \
     --sleep 2 --infobox \
"Formatting without checking bad blocks..." 3 45
mkswap -v1 $DEVICE 1> $OUTPUT_TTY 2>&1
  else
    dialog \
     --title "SWAP PARTITION (${DEVICE})" \
     --sleep 2 --infobox \
"Formatting and checking bad blocks..." 3 42
mkswap -v1 -c $DEVICE 1> $OUTPUT_TTY 2>&1
  fi
  dialog \
   --title "${DEVICE}" \
   --sleep 1 --infobox \
"Activating swap partition..." 3 32
  swapon -f $DEVICE
  swapon -s 1> $OUTPUT_TTY 2>&1
  printf "%-15s %-15s %-11s %-16s %-5s %s\n" \
   "$DEVICE" "swap" "swap" "defaults" "0" "0" > ${TMP}/fstab
fi

