#!/bin/sh

# E2E test for the hyper-converged setup sequencing of src/install-status.php:
#
# - when the last controller reports puppet-success and all of them are done
#   (initial_cluster_setup flips to 'no'), the hyperconverged compute nodes
#   must get their oci-first-boot restarted (touch + oci-first-boot-wrapper),
#   so that they do their 2nd pass (oci::compute) after the controllers are
#   fully set up.
# - when a hyperconverged compute reports puppet-success and everything else
#   is done (initial_mon_on_ctrl flips to 'no'), only the CONTROLLERS must be
#   restarted: no ssh call at all may target a compute node (that was the
#   dangling /var/lib/oci-first-boot marker bug).
# - a cluster with dedicated cephmon nodes (not hyperconverged) must see no
#   ssh call at all on a controller puppet-success.
#
# The test needs php with mysqli, a scratch MariaDB and a writable
# /etc/openstack-cluster-installer (to install a fixture conf), which is
# why it skips outside of a schroot / root environment. The ssh binary is
# stubbed through PATH with a logger, so no network connection is ever
# attempted.

set -e

REPO_ROOT=$(cd "$(dirname "$0")/../.." && pwd)
SB=$(pwd)/sandbox
LOG_DIR=${SB}/log
SSH_LOG=${LOG_DIR}/ssh-calls.log

skip () {
	echo "SKIP: $1"
	exit 0
}

# --- availability guards (the sbuild environment has php only) -----------
command -v php >/dev/null 2>&1 || skip "php not available"
php -m | grep -qi '^mysqli$' || skip "php mysqli extension not available"
command -v mariadbd >/dev/null 2>&1 || skip "mariadbd not available"
[ "$(id -u)" = "0" ] || skip "must be root to install the fixture conf in /etc"
command -v mariadb >/dev/null 2>&1 || skip "mariadb client not available"

# --- sandbox -------------------------------------------------------------
rm -rf "${SB}"
mkdir -p "${SB}/bin" "${LOG_DIR}" "${SB}/mdata" "${SB}/run"

# Stub ssh: log the command line, connect nowhere, exit 0.
cat > "${SB}/bin/ssh" <<'EOF'
#!/bin/sh
LOG="${OCI_SSH_STUB_LOG:?OCI_SSH_STUB_LOG not set}"
{
	echo -n "ssh"
	for a in "$@" ; do
		echo -n " ${a}"
	done
	echo
} >>"${LOG}"
exit 0
EOF
chmod 755 "${SB}/bin/ssh"

# Fixture conf for readmyconf(): points at the scratch MariaDB, and makes
# send_ssh_cmd() use the ssh binary (stubbed through PATH).
CONF_DIR=/etc/openstack-cluster-installer
CONF_FILE=${CONF_DIR}/openstack-cluster-installer.conf
mkdir -p "${CONF_DIR}"
SAVED_CONF=""
if [ -e "${CONF_FILE}" ] ; then
	SAVED_CONF=$(mktemp)
	cp "${CONF_FILE}" "${SAVED_CONF}"
fi
restore_conf () {
	if [ -n "${SAVED_CONF}" ] ; then
		mv "${SAVED_CONF}" "${CONF_FILE}"
	else
		rm -f "${CONF_FILE}"
	fi
}
trap restore_conf EXIT INT TERM

cat > "${CONF_FILE}" <<EOF
[network]
OPENSTACK_CLUSTER_NETWORK=192.0.2.0/24
PXE_NIC_NAME=eth0
debian_mirror=http://deb.debian.org/debian
debian_security_mirror=http://deb.debian.org/debian
debian_backport_mirror=http://deb.debian.org/debian
debian_incoming_buildd=http://deb.debian.org/debian
TRUSTED_NETWORKS=127.0.0.0/8

[database]
connection=mysql://root@127.0.0.1:3307/ocitest

[ssh]
use_php_ssh2=no
EOF

# --- scratch MariaDB -----------------------------------------------------
if ! [ -d "${SB}/mdata/mysql" ] ; then
	mariadb-install-db --no-defaults --datadir="${SB}/mdata" --auth-root-authentication-method=normal >/dev/null 2>&1
fi
mariadbd --no-defaults --user=root --datadir="${SB}/mdata" --port=3307 \
	--bind-address=127.0.0.1 --socket="${SB}/run/mysqld.sock" --skip-grant-tables \
	--skip-networking=0 >/dev/null 2>&1 &
MARIADB_PID=$!
cleanup_db () {
	kill "${MARIADB_PID}" 2>/dev/null || true
	wait "${MARIADB_PID}" 2>/dev/null || true
}
trap "cleanup_db ; restore_conf" EXIT INT TERM
i=0
while ! mariadb -h 127.0.0.1 -P 3307 -u root -e "SELECT 1" >/dev/null 2>&1 ; do
	i=$((i + 1))
	if [ "${i}" -gt 50 ] ; then
		echo "FAIL: scratch MariaDB did not come up"
		exit 1
	fi
	sleep 0.2
done
mariadb -h 127.0.0.1 -P 3307 -u root -e "DROP DATABASE IF EXISTS ocitest ; CREATE DATABASE ocitest"

# Minimal schema for install-status.php.
mariadb -h 127.0.0.1 -P 3307 -u root ocitest <<'EOF'
CREATE TABLE machines (
  id INT AUTO_INCREMENT PRIMARY KEY,
  serial VARCHAR(64) NOT NULL,
  hostname VARCHAR(255) NOT NULL,
  cluster INT NOT NULL,
  role VARCHAR(32) NOT NULL,
  status VARCHAR(32) NOT NULL DEFAULT '',
  puppet_status VARCHAR(32) NOT NULL DEFAULT '',
  compute_is_cephosd VARCHAR(8) NOT NULL DEFAULT 'no',
  ceph_osd_initial_setup VARCHAR(8) NOT NULL DEFAULT 'no',
  ipaddr VARCHAR(16) NOT NULL DEFAULT '',
  dhcp_ip VARCHAR(16) NOT NULL DEFAULT '',
  lastseen DATETIME NULL
);
CREATE TABLE clusters (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(64) NOT NULL,
  initial_mon_on_ctrl VARCHAR(8) NOT NULL DEFAULT 'no',
  initial_cluster_setup VARCHAR(8) NOT NULL DEFAULT 'yes',
  cephosd_automatic_provisionning VARCHAR(8) NOT NULL DEFAULT 'no',
  first_master_machine_id INT NOT NULL DEFAULT 1
);
EOF

reset_fixtures () {
	mariadb -h 127.0.0.1 -P 3307 -u root ocitest <<'EOF'
DELETE FROM machines ;
DELETE FROM clusters ;
INSERT INTO clusters (id, name, initial_mon_on_ctrl, initial_cluster_setup, cephosd_automatic_provisionning, first_master_machine_id) VALUES
  (1, 'cl3', 'no', 'yes', 'yes', 1);
INSERT INTO machines (serial, hostname, cluster, role, status, puppet_status, compute_is_cephosd, ceph_osd_initial_setup, ipaddr) VALUES
  ('CL3CTRL1', 'cl3-controller-1', 1, 'controller', 'installed', 'success', 'no',  'yes', '192.0.2.11'),
  ('CL3CTRL2', 'cl3-controller-2', 1, 'controller', 'installed', 'success', 'no',  'yes', '192.0.2.12'),
  ('CL3CTRL3', 'cl3-controller-3', 1, 'controller', 'installed', 'running', 'no',  'yes', '192.0.2.13'),
  ('CL3COMP1', 'cl3-compute-1',    1, 'compute',    'installed', 'success', 'yes', 'yes', '192.0.2.21'),
  ('CL3COMP2', 'cl3-compute-2',    1, 'compute',    'installed', 'success', 'yes', 'yes', '192.0.2.22'),
  ('CL3COMP3', 'cl3-compute-3',    1, 'compute',    'installed', 'success', 'yes', 'yes', '192.0.2.23'),
  ('CL3PLAIN', 'cl3-plain',        1, 'compute',    'installed', 'success', 'no',  'no',  '192.0.2.24');
EOF
}

run_driver () {
	local REPORTING_SERIAL=${1}
	: > "${SSH_LOG}"
	( cd "${REPO_ROOT}/src" && \
	  PATH="${SB}/bin:${PATH}" OCI_SSH_STUB_LOG="${SSH_LOG}" \
	  php "${REPO_ROOT}/tests/oci_install_status_hyperconverged/driver.php" "${REPORTING_SERIAL}" \
	) >/dev/null 2>&1
}

assert_eq () {
	local GOT=${1} WANT=${2} MSG=${3}
	if [ "${GOT}" != "${WANT}" ] ; then
		echo "FAIL: ${MSG}: got '${GOT}', want '${WANT}'"
		exit 1
	fi
	echo "PASS: ${MSG}"
}

assert_ssh_calls () {
	local IP=${1} CMD=${2} COUNT WANT MSG
	WANT=${3}
	COUNT=$(grep -cF "root@${IP} ${CMD}" "${SSH_LOG}" || true)
	MSG="ssh '${CMD}' to ${IP}"
	assert_eq "${COUNT}" "${WANT}" "${MSG}"
}

assert_no_ssh_calls () {
	if grep -qF "root@${1} " "${SSH_LOG}" ; then
		echo "FAIL: unexpected ssh call to ${1}"
		grep -F "root@${1} " "${SSH_LOG}"
		exit 1
	fi
	echo "PASS: no ssh call to ${1}"
}

dbval () {
	mariadb -N -h 127.0.0.1 -P 3307 -u root ocitest -e "$1"
}

echo "== Scenario 1: last controller's 2nd pass success (initial_cluster_setup flips) =="
reset_fixtures
run_driver CL3CTRL3
assert_eq "$(dbval "SELECT initial_cluster_setup FROM clusters WHERE id=1")" "no" "S1: initial_cluster_setup flipped to no"
assert_ssh_calls 192.0.2.21 "touch /var/lib/oci-first-boot" 1
assert_ssh_calls 192.0.2.21 "/usr/bin/oci-first-boot-wrapper 2>/dev/null 1>/dev/null" 1
assert_ssh_calls 192.0.2.22 "touch /var/lib/oci-first-boot" 1
assert_ssh_calls 192.0.2.22 "/usr/bin/oci-first-boot-wrapper 2>/dev/null 1>/dev/null" 1
assert_ssh_calls 192.0.2.23 "touch /var/lib/oci-first-boot" 1
assert_ssh_calls 192.0.2.23 "/usr/bin/oci-first-boot-wrapper 2>/dev/null 1>/dev/null" 1
assert_no_ssh_calls 192.0.2.24
assert_no_ssh_calls 192.0.2.11
assert_no_ssh_calls 192.0.2.12
assert_no_ssh_calls 192.0.2.13

echo "== Scenario 2: last hyperconverged compute's 1st pass success (initial_mon_on_ctrl flips) =="
reset_fixtures
mariadb -h 127.0.0.1 -P 3307 -u root ocitest -e "UPDATE clusters SET initial_mon_on_ctrl='yes', initial_cluster_setup='no' WHERE id=1 ; UPDATE machines SET puppet_status='success' WHERE role='controller'"
run_driver CL3COMP3
assert_eq "$(dbval "SELECT initial_mon_on_ctrl FROM clusters WHERE id=1")" "no" "S2: initial_mon_on_ctrl flipped to no"
assert_ssh_calls 192.0.2.11 "touch /var/lib/oci-first-boot" 1
assert_ssh_calls 192.0.2.11 "/usr/bin/oci-first-boot-wrapper 2>/dev/null 1>/dev/null" 1
assert_ssh_calls 192.0.2.12 "touch /var/lib/oci-first-boot" 1
assert_ssh_calls 192.0.2.12 "/usr/bin/oci-first-boot-wrapper 2>/dev/null 1>/dev/null" 1
assert_ssh_calls 192.0.2.13 "touch /var/lib/oci-first-boot" 1
assert_ssh_calls 192.0.2.13 "/usr/bin/oci-first-boot-wrapper 2>/dev/null 1>/dev/null" 1
assert_no_ssh_calls 192.0.2.21
assert_no_ssh_calls 192.0.2.22
assert_no_ssh_calls 192.0.2.23
assert_no_ssh_calls 192.0.2.24

echo "== Scenario 3: cluster with dedicated cephmon nodes (not hyperconverged) =="
reset_fixtures
mariadb -h 127.0.0.1 -P 3307 -u root ocitest -e "INSERT INTO machines (serial, hostname, cluster, role, status, puppet_status, compute_is_cephosd, ceph_osd_initial_setup, ipaddr) VALUES ('CL3MON1', 'cl3-cephmon-1', 1, 'cephmon', 'installed', 'success', 'no', 'no', '192.0.2.31')"
run_driver CL3CTRL3
assert_eq "$(dbval "SELECT initial_cluster_setup FROM clusters WHERE id=1")" "no" "S3: initial_cluster_setup flipped to no"
assert_eq "$(wc -l < "${SSH_LOG}")" "0" "S3: no ssh call at all"

echo "== Scenario 4: non-final controller puppet-success does nothing =="
reset_fixtures
mariadb -h 127.0.0.1 -P 3307 -u root ocitest -e "UPDATE machines SET puppet_status='running' WHERE serial='CL3CTRL2'"
run_driver CL3CTRL3
assert_eq "$(dbval "SELECT initial_cluster_setup FROM clusters WHERE id=1")" "yes" "S4: initial_cluster_setup untouched"
assert_eq "$(wc -l < "${SSH_LOG}")" "0" "S4: no ssh call at all"

echo "All install-status hyperconverged tests passed."
