#!/bin/sh

set -e

DISK=$AUTOPKGTEST_TMP/disk
EXPORT=$AUTOPKGTEST_TMP/export

cleanup () {
  test "$LOOP" && losetup -d "$LOOP"
  test -f "$DISK" && rm -f "$DISK"
  test -f "$EXPORT" && rm -f "$EXPORT"
}

trap "cleanup" 0 2 3 15

printf "\n=== losetup ===\n"
dd if=/dev/zero of=$DISK bs=1M count=10 2>&1
LOOP=$(losetup --find --show $DISK)

printf "\n=== create ===\n"
sbd -d $LOOP create

printf "\n=== allocate ===\n"
sbd -d $LOOP allocate $(hostname)

printf "\n=== list ===\n"
sbd -d $LOOP list

printf "\n=== watch ===\n"
mkdir -p /var/lib/pacemaker/cores
sbd -d $LOOP -W -W watch
pgrep -a sbd

printf "\n=== dump ===\n"
sbd -d $LOOP dump

printf "\n=== exporter ===\n"
echo SBD_DEVICE=$LOOP >> /etc/default/sbd
service ha_cluster_exporter restart
service ha_cluster_exporter status

printf "\n=== export ===\n"
curl --silent http://localhost:9002/metrics > $EXPORT
if ! grep $LOOP $EXPORT; then
  cat $EXPORT
  service ha_cluster_exporter status
  exit 1
fi
