unset swap_devices
if boolean_is_true "$USE_LOCAL_SWAP" ; then
    # Enable local swap partition if found on local disk
    for part in `sfdisk -l 2>/dev/null | awk '/ 82 / { print $1}'`; do
        swap_devices="$swap_devices $part"
    done
fi

# If no local swap was found, default to NBD_SWAP=true for low-RAM clients
if [ -z "$swap_devices" ] && [ -z "$NBD_SWAP" ]; then
    # Set reasonable defaults for NBD_SWAP_THRESHOLD (in MB)
    if [ -z "$NBD_SWAP_THRESHOLD" ]; then
        if boolean_is_true "$LTSP_FATCLIENT"; then
            NBD_SWAP_THRESHOLD=2100
        else
            NBD_SWAP_THRESHOLD=800
        fi
    fi
    memtotal=$(awk '/^MemTotal:/ { print int($2/1024) }' /proc/meminfo)
    if [ "$memtotal" -lt "$NBD_SWAP_THRESHOLD" ]; then
        NBD_SWAP=true
    fi
fi

if boolean_is_true "$NBD_SWAP" ; then
    NBD_SWAP_HOST=${NBD_SWAP_HOST:-"$SERVER"}
    modprobe nbd
    # Detect first unused nbd device, skip nbd0
    for num in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15; do
        ret=0
        nbd-client -c /dev/nbd${num} > /dev/null || ret="$?"
        [ "$ret" -eq 1 ] && break
    done
    # TODO: add -persist here when LP: #938511 is solved, but also verify that
    # we'll get the same file from the server without `mkswap` called again.
    nbd-client $NBD_SWAP_HOST -N swap /dev/nbd${num} -swap && \
        swap_devices="$swap_devices /dev/nbd${num}"
fi

if boolean_is_true "$ENCRYPT_SWAP" ; then
    if [ -x /sbin/cryptsetup ]; then
        modprobe dm_crypt
    else
        echo "ERROR: ENCRYPT_SWAP=Y, but /sbin/cryptsetup not found. disabling swap."
        swap_devices=""
    fi
fi

num=0
for device in $swap_devices ; do
    swap="$device"
    if boolean_is_true "$ENCRYPT_SWAP" ; then
        if [ -x /sbin/cryptsetup ]; then
            cryptsetup -d /dev/urandom create swap$num $swap && swap="/dev/mapper/swap$num"
            num=$(($num+1))
        fi
        mkswap $swap
    fi
    swapon $swap
done
