#!/usr/bin/env node

// Checks the health of Etherpad by visiting http://localhost:9001/health. Returns 0 on success, 1
// on error as required by the Dockerfile HEALTHCHECK instruction.

'use strict';

// As of v14, Node.js does not exit when there is an unhandled Promise rejection. Convert an
// unhandled rejection into an uncaught exception, which does cause Node.js to exit.
process.on('unhandledRejection', (err) => { throw err; });

const assert = require('assert').strict;
const superagent = require('superagent');

(async () => {
  const res = await superagent.get('http://localhost:9001/health')
      .accept('application/health+json')
      .buffer(true)
      .parse(superagent.parse['application/json']);
  assert(res.ok, `Unexpected HTTP status: ${res.status}`);
  assert.equal(res.type, 'application/health+json');
  const {body: {status} = {}} = res;
  assert(status != null);
  assert.equal(typeof status, 'string');
  assert(['pass', 'ok', 'up'].includes(status.toLowerCase()), `Unexpected status: ${status}`);
})();
