#!/bin/sh
# cast cluster baseline — packages, NFS, hosts, nginx/php smoke vhost.
set -eu
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
# shellcheck source=/dev/null
. "$ROOT/scripts/lib/common.sh"
ensure_shared_mounted

HOST="$(host_short)"
STAGE="$(mktemp -d /var/tmp/cast-cluster.XXXXXX)"
trap 'rm -rf "$STAGE"' EXIT

log "baseline start on $HOST"

grep -v "${FE_NFS_EXPORT_PATH}" /etc/fstab > "$STAGE/fstab.new" || true
echo "$FSTAB_NFS_LINE" >> "$STAGE/fstab.new"
mv "$STAGE/fstab.new" /etc/fstab
mkdir -p "$SHARED_MOUNT"
rc-update add nfsmount boot 2>/dev/null || true
mount "$SHARED_MOUNT" 2>/dev/null || mount -a 2>/dev/null || true

grep -v '# cast-cluster' /etc/hosts | grep -v 'cast0[123]\.' | grep -v 'artc0\.' > "$STAGE/hosts.new" || cp /etc/hosts "$STAGE/hosts.new"
cat >> "$STAGE/hosts.new" <<EOF
# cast-cluster ${CLUSTER_NAME}
${CAST01_IP} ${CAST01_HOST} ${CAST01_HOST}.${CAST_DOMAIN}
${CAST02_IP} ${CAST02_HOST} ${CAST02_HOST}.${CAST_DOMAIN}
${CAST03_IP} ${CAST03_HOST} ${CAST03_HOST}.${CAST_DOMAIN}
${ARTC0_IP} ${ARTC0_HOST} ${ARTC0_HOST}.${CAST_DOMAIN} alpine-be
EOF
mv "$STAGE/hosts.new" /etc/hosts

apk update
PKGS="$APK_PACKAGES_BASE"
if is_primary_node; then
  PKGS="$PKGS mariadb"
fi
# shellcheck disable=SC2086
apk add --no-cache $PKGS

rc-update add nginx default 2>/dev/null || true
rc-update add php-fpm83 default 2>/dev/null || true
run_script "$ROOT/scripts/configure-php-fpm.sh"
rc-service php-fpm83 restart 2>/dev/null || rc-service php-fpm83 start 2>/dev/null || true
rc-service nginx start 2>/dev/null || true

if is_primary_node; then
  grep -q '^skip-networking' /etc/my.cnf.d/mariadb-server.cnf 2>/dev/null && \
    sed -i 's/^skip-networking/#skip-networking/' /etc/my.cnf.d/mariadb-server.cnf || true
  grep -q '^bind-address' /etc/my.cnf.d/mariadb-server.cnf 2>/dev/null || \
    printf '\n[mysqld]\nbind-address = 0.0.0.0\n' >> /etc/my.cnf.d/mariadb-server.cnf
  rc-update add mariadb default 2>/dev/null || true
  rc-service mariadb restart 2>/dev/null || rc-service mariadb start 2>/dev/null || true
fi

mkdir -p /var/www/localhost/htdocs
echo "<html><body><h1>${HOST}</h1><p>${CLUSTER_NAME} node</p></body></html>" > /var/www/localhost/htdocs/index.html
chown -R nginx:nginx /var/www/localhost/htdocs 2>/dev/null || true

mkdir -p "$ROOT"
IP="$(ip -4 -o addr show eth0 2>/dev/null | awk '{print $4}' | cut -d/ -f1)"
echo "$HOST $(date -Iseconds) ip=$IP cluster=$CLUSTER_NAME" >> "$ROOT/seen.log"
printf '{"host":"%s","ip":"%s","cluster":"%s","configured_at":"%s"}\n' \
  "$HOST" "$IP" "$CLUSTER_NAME" "$(date -Iseconds)" > "$ROOT/${HOST}.json"

mount | grep -q " on ${SHARED_MOUNT} " || die "NFS not mounted"
curl -sS -o /dev/null -w "nginx_http=%{http_code}\n" http://127.0.0.1/
log "baseline_ok $HOST"
