#!/bin/sh

set -e

start_service() {
  name=$1
  if ! service $name start; then
    set +e
    service $name status
    if [ -x /bin/journalctl ]; then
      journalctl -b -u $name
    elif [ -f /var/log/daemon.log ]; then
      grep $name /var/log/daemon.log
    fi
    exit 1
  fi
}

printf "=== config ===\n"
booth-keygen
cat <<EOF | tee /etc/booth/booth.conf
authfile = /etc/booth/authkey
site = 127.0.0.1
ticket = "ticket-A"
EOF

printf "\n=== cluster ===\n"
start_service corosync
start_service pacemaker
n=0
while ! crm status | grep 'Online:.*node1'; do
  test "$n" -lt 120
  sleep 1
  n=$((n+1))
done

crm configure property stonith-enabled=false
crm configure property no-quorum-policy=ignore
crm configure primitive booth ocf:pacemaker:booth-site 2>&1
crm configure primitive dummy ocf:heartbeat:Dummy 2>&1
crm configure rsc_ticket ticket-A_dummy ticket-A: dummy 2>&1
crm configure show
sleep 10
crm status

printf "\n=== booth ===\n"
booth status
booth list

printf "\n=== grant ===\n"
crm site ticket show ticket-A
crm status | grep dummy.*Stopped
crm --force site ticket grant ticket-A
n=0
while ! crm status | grep 'dummy.*Started'; do
  test "$n" -lt 30
  sleep 1
  n=$((n+1))
done
crm site ticket show ticket-A

printf "\n=== revoke ===\n"
crm site ticket standby ticket-A
n=0
while ! crm status | grep 'dummy.*Stopped'; do
  test "$n" -lt 30
  sleep 1
  n=$((n+1))
done
crm --force site ticket revoke ticket-A
crm site ticket show ticket-A
