#!/usr/bin/env bash
# =====================================================================
#  bin/rx-install — bring up a node from nothing
#
#  Run once per counter PC by the partner, or by the cloud provisioner.
#  Idempotent: running it again on a working store changes nothing.
# =====================================================================
set -uo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

echo "Caresoft counter — install"
echo

# 1. What PHP is missing, in a sentence the partner can act on.
php -r '
$req=["pdo_mysql"=>"the database","json"=>"requests"];
$opt=["zip"=>"Excel export","curl"=>"cloud sync"];
$m=[];foreach($req as $e=>$w) if(!extension_loaded($e)) $m[]="php-$e (needed for $w)";
if($m){fwrite(STDERR,"Missing: ".implode("; ",$m)."\nInstall these, then run this again.\n");exit(1);}
foreach($opt as $e=>$w) if(!extension_loaded($e)) echo "  note: php-$e is missing — $w will not work\n";
' || exit 1
echo "  PHP looks right"

# 2. Config must exist and must not be the shipped sample.
if [ ! -f "$ROOT/config.php" ]; then
  echo "  config.php is missing. Copy config.sample.php to config.php and fill it in."
  exit 1
fi

# 3. Schema, in the declared order.
php "$ROOT/bin/rx-migrate" up || exit 1

# 4. Say what is still needed, rather than pretending it is done.
echo
echo "Installed. Still to do before this counter can bill:"
echo "  · create the first user            (rx-user add)"
echo "  · set the printer and test print   (setup wizard, step 3)"
echo "  · download the medicine list       (setup wizard, step 4)"
echo "  · bring across the old data        (setup wizard, step 5)"
