#!/bin/sh

set -eu

if [ "$(puavo-conf puavo.swap.local.enabled)" != 'true' ]; then
  exit 0
fi

list_swap_partition_paths() {
  lsblk --properties-by blkid -n -r -o PATH \
    -Q 'PARTTYPE == "0657fd6d-a4ab-43c4-84e5-0933c84b4f4f"
          || (TYPE == "lvm" && NAME == "puavo-swap")'
}

swap_index=0

# Initialize "/etc/fstab" here.  On bootservers, the setup_nfs_server
# puavo-conf script also appends lines to "/etc/fstab" (so it should be
# run later than this script).
: > /etc/crypttab
: > /etc/fstab

# A single swap device is the norm, but a mirrored bootserver has one per
# disk, so extra devices get a numbered name.
for swap_partition_path in $(list_swap_partition_paths); do
  swap_index=$((swap_index + 1))
  mapper='cryptswap'
  [ "$swap_index" -gt 1 ] && mapper="cryptswap${swap_index}"
  printf "%s %s /dev/urandom swap,cipher=aes-xts-plain64,size=256\n" \
         "$mapper" "$swap_partition_path" >> /etc/crypttab
  printf "/dev/mapper/%s none swap defaults 0 0\n" "$mapper" >> /etc/fstab
done
