#!/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/syslog ]; then
      grep $name /var/log/syslog
    fi
    exit 1
  fi
}

crm_status_wait() {
  match=$1
  log=$AUTOPKGTEST_TMP/crm.status
  n=0
  printf "Waiting for '$match':"
  while ! crm status | tee $log | grep -q "$match"; do
    if [ "$n" -eq 120 ]; then
      printf " failed.\n"
      cat $log
      return 1
    fi
    sleep 1
    n=$((n+1))
    printf " $n"
  done
  printf " done.\n"
}

printf "=== keygen ===\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
crm_status_wait  "\\* Online: "

printf "\n=== configure ===\n"
crm configure property stonith-enabled=false
crm configure property no-quorum-policy=ignore
crm configure primitive booth ocf:pacemaker:booth-site \
                        op start timeout=100s 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
crm_status_wait 'booth.*Started'
crm status

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

printf "\n=== grant ===\n"
crm --force site ticket grant ticket-A
crm_status_wait 'dummy.*Started'
crm site ticket show ticket-A

printf "\n=== revoke ===\n"
crm site ticket standby ticket-A
crm_status_wait 'dummy.*Stopped'
crm --force site ticket revoke ticket-A
crm site ticket show ticket-A
