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

# Set NBD_SWAP=true by default for clients with RAM < NBD_SWAP_THRESHOLD
if [ -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=800
        else
            NBD_SWAP_THRESHOLD=300
        fi
    fi
    memtotal=$(sed -n 's/MemTotal: *\([0-9]*\) .*/\1/p' /proc/meminfo)
    if [ "$memtotal" -lt $((1024*$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
        nbd-client -c /dev/nbd${num} > /dev/null
        [ $? -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
