#!/usr/bin/env bash
#
# provision-carehome.sh — set up a FamilyCarer Pro care home on this server:
# both the production and test sites, their Apache vhosts, certificates,
# databases and application config.
#
# It ships inside the installer zip, so the usual flow is:
#
#     unzip familycarer_pro_install_<name>.zip
#     cd <where it unpacked>
#     sudo ./provision-carehome.sh              # dry run — shows the plan
#     sudo ./provision-carehome.sh --apply      # do it
#
# The hostnames are read from installer.php, which the central site generated
# with this care home's real URLs — so they cannot disagree with the config the
# installer is about to write.
#
# It is idempotent: re-running skips work already done.
#
# It does NOT create DNS records. Both names must already resolve to this
# server, because certbot validates over public DNS. The script checks first.

set -euo pipefail

# ── defaults ──────────────────────────────────────────────────────────────
ZIP=""
SRC="."
DOMAIN=""
TEST_DOMAIN=""
DB_USER="root"
DB_PASS=""
WEB_ROOT="/var/www"
APPLY=0
SKIP_CERT=0
SKIP_DNS=0
CERT_EMAIL=""

usage() {
    cat <<'USAGE'
Usage: provision-carehome.sh [options]

Run from inside an unpacked installer zip (the directory holding
installer.php and familycarer_pro/). With no options it prints what it
would do and changes nothing.

Options:
  --src <dir>           unpacked installer directory (default: current dir)
  --zip <file>          unpack this zip instead of using --src
  --domain <fqdn>       override the production hostname. Normally read from
                        installer.php, which already carries this care home's
                        real URLs.
  --test-domain <fqdn>  test hostname. Default: <first-label>-test.<rest>
  --db-user <user>      MySQL user with CREATE rights (default: root)
  --db-pass <pass>      MySQL password (prompted if omitted)
  --web-root <dir>      where sites live (default: /var/www)
  --cert-email <addr>   email for Let's Encrypt registration
  --skip-dns-check      proceed even if the names look unresolvable here
  --skip-cert           do not run certbot (use if certificates already exist)
  --apply               actually make changes. Without this, dry run only.
  -h, --help            this message

Hostnames must not contain underscores — they are invalid in DNS and browsers
will refuse them.
USAGE
}

while [[ $# -gt 0 ]]; do
    case "$1" in
        --zip)         ZIP="$2"; shift 2 ;;
        --src)         SRC="$2"; shift 2 ;;
        --domain)      DOMAIN="$2"; shift 2 ;;
        --test-domain) TEST_DOMAIN="$2"; shift 2 ;;
        --db-user)     DB_USER="$2"; shift 2 ;;
        --db-pass)     DB_PASS="$2"; shift 2 ;;
        --web-root)    WEB_ROOT="$2"; shift 2 ;;
        --cert-email)  CERT_EMAIL="$2"; shift 2 ;;
        --skip-cert)   SKIP_CERT=1; shift ;;
        --skip-dns-check) SKIP_DNS=1; shift ;;
        --apply)       APPLY=1; shift ;;
        -h|--help)     usage; exit 0 ;;
        *) echo "Unknown option: $1" >&2; usage; exit 1 ;;
    esac
done

# ── output helpers ────────────────────────────────────────────────────────
BOLD=$'\033[1m'; RED=$'\033[31m'; GRN=$'\033[32m'; YEL=$'\033[33m'; OFF=$'\033[0m'
step() { echo "${BOLD}==>${OFF} $*"; }
ok()   { echo "    ${GRN}ok${OFF}   $*"; }
warn() { echo "    ${YEL}note${OFF} $*"; }
die()  { echo "${RED}error:${OFF} $*" >&2; exit 1; }
would() {
    if [[ $APPLY -eq 1 ]]; then return 1; else echo "    would: $*"; return 0; fi
}

# ── validation ────────────────────────────────────────────────────────────
[[ $EUID -eq 0 ]] || die "run as root (sudo)"

# ── work out where the unpacked installation is ───────────────────────────
STAGE=""
if [[ -n "$ZIP" ]]; then
    [[ -f "$ZIP" ]] || die "zip not found: $ZIP"
    command -v unzip >/dev/null 2>&1 || die "'unzip' not found"
    STAGE="$(mktemp -d)"
    unzip -q "$ZIP" -d "$STAGE"
    SRC="$STAGE"
fi

SRC="${SRC%/}"
[[ -f "$SRC/installer.php" ]] || die "no installer.php in '$SRC' — run this from an unpacked installer zip, or pass --zip"
[[ -d "$SRC/familycarer_pro" ]] || die "no familycarer_pro/ in '$SRC'"

# ── read the hostnames the central site baked into installer.php ──────────
# Both are plain PHP string literals, e.g.  $siteUrl = 'https://x.example.net';
read_installer_var() {
    sed -n "s/^\\\$$1 *= *'\\(.*\\)';.*/\\1/p" "$SRC/installer.php" | head -1
}
strip_scheme() {
    local v="$1"
    v="${v//[[:space:]]/}"          # drop any whitespace, incl. "https: //"
    v="${v#http://}"; v="${v#https://}"
    v="${v%%/*}"                     # keep the host, drop any path
    echo "$v"
}

if [[ -z "$DOMAIN" ]]; then
    DOMAIN="$(strip_scheme "$(read_installer_var siteUrl)")"
    [[ -n "$DOMAIN" ]] || die "could not read \$siteUrl from installer.php — pass --domain"
    ok_src="from installer.php"
else
    ok_src="from --domain"
fi
if [[ -z "$TEST_DOMAIN" ]]; then
    TEST_DOMAIN="$(strip_scheme "$(read_installer_var testSiteUrl)")"
fi

# Normalise whatever we ended up with, whoever supplied it: a value passed on
# the command line may well include the scheme, a trailing slash or stray
# whitespace. Without this, DOMAIN of "https://x.example.net" produces
# directories called /var/www/https://x and a database to match.
DOMAIN="$(strip_scheme "$DOMAIN")"
[[ -n "$TEST_DOMAIN" ]] && TEST_DOMAIN="$(strip_scheme "$TEST_DOMAIN")"

[[ "$DOMAIN" == *_* ]] && die "'$DOMAIN' contains an underscore — invalid in a hostname"
[[ "$DOMAIN" == */* ]] && die "'$DOMAIN' still contains a slash — give a hostname, not a URL"

SLUG="${DOMAIN%%.*}"
REST="${DOMAIN#*.}"
if [[ -z "$TEST_DOMAIN" ]]; then
    TEST_DOMAIN="${SLUG}-test.${REST}"
    warn_no_test=1
fi
[[ "$TEST_DOMAIN" == *_* ]] && die "'$TEST_DOMAIN' contains an underscore — invalid in a hostname"

PROD_DIR="${WEB_ROOT}/${SLUG}"
TEST_DIR="${WEB_ROOT}/${SLUG}_test"      # directory name; underscore is fine here
PROD_DB="${SLUG}"
TEST_DB="${SLUG}_test"                   # database name; underscore is fine here
VHOST="/etc/apache2/sites-available/${SLUG}.conf"

echo
echo "${BOLD}FamilyCarer Pro — care home provisioning${OFF}"
echo "  production   $DOMAIN  ->  $PROD_DIR   (db: $PROD_DB)"
echo "  test         $TEST_DOMAIN  ->  $TEST_DIR   (db: $TEST_DB)"
echo "  vhost        $VHOST"
[[ $APPLY -eq 1 ]] && echo "  mode         ${RED}APPLY — changes will be made${OFF}" \
                   || echo "  mode         ${GRN}dry run — nothing will change${OFF}"
echo

# ── preflight ─────────────────────────────────────────────────────────────
step "Checking prerequisites"
for c in apache2ctl unzip mysql curl php; do
    command -v "$c" >/dev/null 2>&1 || die "'$c' not found — install it first"
done
ok "required commands present"

if [[ $SKIP_CERT -eq 0 ]]; then
    command -v certbot >/dev/null 2>&1 || die "certbot not found (or pass --skip-cert)"
    ok "certbot present"
fi

# Resolution is checked several ways: getent goes through NSS, which can fail
# on a host whose local resolver is misconfigured even though the name resolves
# perfectly well otherwise. Any method succeeding is good enough.
resolves() {
    local d="$1"
    getent hosts "$d"            >/dev/null 2>&1 && return 0
    command -v host    >/dev/null 2>&1 && host    "$d" >/dev/null 2>&1 && return 0
    command -v dig     >/dev/null 2>&1 && [[ -n "$(dig +short "$d" @1.1.1.1 2>/dev/null)" ]] && return 0
    command -v nslookup>/dev/null 2>&1 && nslookup "$d" >/dev/null 2>&1 && return 0
    ping -c1 -W2 "$d"            >/dev/null 2>&1 && return 0
    return 1
}

step "Checking DNS"
if [[ $SKIP_DNS -eq 1 ]]; then
    warn "skipping the DNS check as requested"
else
    for d in "$DOMAIN" "$TEST_DOMAIN"; do
        if resolves "$d"; then
            ok "$d resolves"
        else
            echo
            echo "${RED}$d does not appear to resolve from this machine.${OFF}"
            echo "Tried: getent, host, dig, nslookup, ping."
            echo
            echo "certbot validates over public DNS, so the name must resolve."
            echo "If you are sure it does (this machine's resolver may simply be"
            echo "misconfigured), re-run with --skip-dns-check."
            die "DNS check failed for $d"
        fi
    done
fi

step "Checking the installation source"
[[ -f "$SRC/database.sql" ]] || die "no database.sql in '$SRC' — the release source on the central server is missing it"
ok "installer.php and database.sql present"

# These are not optional: without them the care home has no admin console and
# the app cannot sign in. If they are absent the release source on the central
# server is incomplete — fix it there, so every zip carries them.
MISSING=()
[[ -f "$SRC/familycarer_pro/admin/login.php" ]]              || MISSING+=("admin/ (the care home admin console)")
[[ -f "$SRC/familycarer_pro/api/auth/login.php" ]]           || MISSING+=("api/auth/login.php")
[[ -f "$SRC/familycarer_pro/api/auth/change-password.php" ]] || MISSING+=("api/auth/change-password.php")

if [[ ${#MISSING[@]} -gt 0 ]]; then
    echo
    echo "${RED}This installer package is incomplete.${OFF} Missing:"
    for m in "${MISSING[@]}"; do echo "    - $m"; done
    cat <<'FIXIT'

These live in the release source on the CENTRAL server and ship with every zip.
Add them once and regenerate:

    sudo cp -r admin        /home/familyc/familycarer_pro_release/
    sudo cp login.php change-password.php \
                            /home/familyc/familycarer_pro_release/api/auth/

Without them the care home has no admin console and caregivers cannot sign in.
FIXIT
    die "incomplete package — see above"
fi
ok "admin console and auth endpoints present"

if [[ -z "$DB_PASS" ]]; then
    read -rsp "MySQL password for ${DB_USER}: " DB_PASS; echo
fi
mysql -u "$DB_USER" -p"$DB_PASS" -e "SELECT 1" >/dev/null 2>&1 \
    || die "cannot connect to MySQL as '$DB_USER'"
ok "MySQL credentials accepted"

# ── unpack ────────────────────────────────────────────────────────────────
[[ -n "$STAGE" ]] && trap 'rm -rf "$STAGE"' EXIT

deploy_tree() {                     # $1 = target dir
    local target="$1"
    if [[ -d "$target/familycarer_pro" ]]; then
        warn "$target already exists — leaving the application files alone"
        return
    fi
    would "create $target and unpack the application into it" && return
    mkdir -p "$target"
    cp -r "$SRC/familycarer_pro" "$target/"
    cp "$SRC/installer.php" "$SRC/database.sql" "$target/"
    ok "unpacked into $target"
}

set_perms() {                       # $1 = target dir
    local target="$1"
    would "set ownership www-data and modes 750/640 under $target" && return
    chown -R www-data:www-data "$target"
    find "$target" -type d -exec chmod 750 {} \;
    find "$target" -type f -exec chmod 640 {} \;
    ok "permissions set on $target"
}

step "Deploying application files"
deploy_tree "$PROD_DIR"
deploy_tree "$TEST_DIR"

# ── databases ─────────────────────────────────────────────────────────────
db_exists() {
    mysql -u "$DB_USER" -p"$DB_PASS" -N -B \
        -e "SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME='$1'" 2>/dev/null | grep -q "$1"
}

make_db() {                         # $1 = db name
    if db_exists "$1"; then
        warn "database '$1' already exists — not touching it"
        return
    fi
    would "create database '$1' and load database.sql" && return
    mysql -u "$DB_USER" -p"$DB_PASS" \
        -e "CREATE DATABASE \`$1\` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;"
    mysql -u "$DB_USER" -p"$DB_PASS" "$1" < "$SRC/database.sql"
    ok "database '$1' created and loaded"
}

step "Creating databases"
make_db "$PROD_DB"
make_db "$TEST_DB"

# ── apache: port 80 first, so certbot can validate ────────────────────────
write_vhost_80() {
    if [[ -f "$VHOST" ]]; then
        warn "$VHOST already exists — not overwriting it"
        return
    fi
    would "write $VHOST with the :80 vhosts for both hostnames" && return
    cat > "$VHOST" <<EOF
# FamilyCarer Pro — ${SLUG}
# Generated by provision-carehome.sh. Edit if you must, but re-running the
# script will leave your changes alone.

<VirtualHost *:80>
    ServerName ${DOMAIN}
    DocumentRoot ${PROD_DIR}/familycarer_pro

    # Let's Encrypt writes its challenge under .well-known/acme-challenge and
    # fetches it over PLAIN HTTP. It must be served, not redirected: on a first
    # run there is no HTTPS vhost yet, so a redirect lands on the default TLS
    # site and returns 404 — which fails the validation.
    <Directory ${PROD_DIR}/familycarer_pro/.well-known>
        Options -Indexes
        AllowOverride None
        Require all granted
    </Directory>

    RewriteEngine On
    RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    ErrorLog  \${APACHE_LOG_DIR}/${SLUG}_error.log
    CustomLog \${APACHE_LOG_DIR}/${SLUG}_access.log combined
</VirtualHost>

<VirtualHost *:80>
    ServerName ${TEST_DOMAIN}
    DocumentRoot ${TEST_DIR}/familycarer_pro

    <Directory ${TEST_DIR}/familycarer_pro/.well-known>
        Options -Indexes
        AllowOverride None
        Require all granted
    </Directory>

    RewriteEngine On
    RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
    ErrorLog  \${APACHE_LOG_DIR}/${SLUG}_test_error.log
    CustomLog \${APACHE_LOG_DIR}/${SLUG}_test_access.log combined
</VirtualHost>
EOF
    ok "wrote $VHOST"
}

step "Configuring Apache (HTTP)"
write_vhost_80
if would "enable mod_rewrite and mod_ssl, enable the site, and reload Apache"; then
    :
else
    a2enmod rewrite ssl >/dev/null 2>&1 || true
    a2ensite "${SLUG}.conf" >/dev/null 2>&1 || true
    apache2ctl configtest || die "Apache config test failed — nothing reloaded"
    systemctl reload apache2
    ok "Apache reloaded"
fi

# ── certificates ──────────────────────────────────────────────────────────
step "Certificates"
if [[ $SKIP_CERT -eq 1 ]]; then
    warn "skipping certbot as requested"
else
    for d in "$DOMAIN" "$TEST_DOMAIN"; do
        if [[ -d "/etc/letsencrypt/live/$d" ]]; then
            warn "certificate for $d already exists"
        elif would "obtain a certificate for $d"; then
            :
        else
            EMAIL_ARGS=()
            if [[ -n "$CERT_EMAIL" ]]; then EMAIL_ARGS=(-m "$CERT_EMAIL")
            else EMAIL_ARGS=(--register-unsafely-without-email); fi
            wr="$([[ $d == "$DOMAIN" ]] && echo "$PROD_DIR/familycarer_pro" || echo "$TEST_DIR/familycarer_pro")"
            mkdir -p "$wr/.well-known/acme-challenge"
            chown -R www-data:www-data "$wr/.well-known"
            chmod -R 755 "$wr/.well-known"
            certbot certonly --webroot -w "$wr" \
                -d "$d" --agree-tos --non-interactive "${EMAIL_ARGS[@]}" \
                || die "certbot failed for $d"
            ok "certificate obtained for $d"
        fi
    done
fi

# ── apache: port 443 ──────────────────────────────────────────────────────
append_vhost_443() {
    if grep -q "VirtualHost \*:443" "$VHOST" 2>/dev/null; then
        warn "HTTPS vhosts already present in $VHOST"
        return
    fi
    would "append the :443 vhosts to $VHOST" && return
    cat >> "$VHOST" <<EOF

<VirtualHost *:443>
    ServerName ${DOMAIN}
    DocumentRoot ${PROD_DIR}/familycarer_pro
    DirectoryIndex index.php index.html
    <Directory ${PROD_DIR}/familycarer_pro>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    SSLEngine on
    Include /etc/letsencrypt/options-ssl-apache.conf
    SSLCertificateFile    /etc/letsencrypt/live/${DOMAIN}/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/${DOMAIN}/privkey.pem
    ErrorLog  \${APACHE_LOG_DIR}/${SLUG}_ssl_error.log
    CustomLog \${APACHE_LOG_DIR}/${SLUG}_ssl_access.log combined
</VirtualHost>

<VirtualHost *:443>
    ServerName ${TEST_DOMAIN}
    DocumentRoot ${TEST_DIR}/familycarer_pro
    DirectoryIndex index.php index.html
    <Directory ${TEST_DIR}/familycarer_pro>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    SSLEngine on
    Include /etc/letsencrypt/options-ssl-apache.conf
    SSLCertificateFile    /etc/letsencrypt/live/${TEST_DOMAIN}/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/${TEST_DOMAIN}/privkey.pem
    ErrorLog  \${APACHE_LOG_DIR}/${SLUG}_test_ssl_error.log
    CustomLog \${APACHE_LOG_DIR}/${SLUG}_test_ssl_access.log combined
</VirtualHost>
EOF
    ok "appended HTTPS vhosts"
}

step "Configuring Apache (HTTPS)"
append_vhost_443
if would "test the Apache config and reload"; then
    :
else
    apache2ctl configtest || die "Apache config test failed — NOT reloading"
    systemctl reload apache2
    ok "Apache reloaded"
fi

# ── run the installers ────────────────────────────────────────────────────
# Production FIRST: it mints the API key and registers it centrally. The test
# run then fetches that same key, so both deployments agree — which is what the
# app requires, since it is handed one key for whichever URL its build targets.
run_installer() {                   # $1 = dir, $2 = mode ("" or "T"), $3 = db
    local dir="$1" mode="$2" db="$3"
    if [[ ! -f "$dir/installer.php" ]]; then
        warn "no installer.php in $dir — already run and cleaned up?"
        return
    fi
    would "run installer in $dir ${mode:+with mode $mode} against database '$db'" && return
    ( cd "$dir" && php installer.php $mode ) || die "installer failed in $dir"
    rm -f "$dir/installer.php"
    ok "installer completed in $dir (installer.php removed)"
}

step "Running the installers"
warn "the installer prompts for database details — use '$PROD_DB' then '$TEST_DB'"
run_installer "$PROD_DIR" ""  "$PROD_DB"
run_installer "$TEST_DIR"  "T" "$TEST_DB"

step "Setting permissions"
set_perms "$PROD_DIR"
set_perms "$TEST_DIR"

# ── verify ────────────────────────────────────────────────────────────────
step "Verifying"
if [[ $APPLY -eq 0 ]]; then
    echo "    (skipped in dry run)"
else
    for d in "$DOMAIN" "$TEST_DOMAIN"; do
        code=$(curl -s -o /dev/null -w "%{http_code}" "https://$d/" || echo 000)
        [[ "$code" =~ ^(200|301|302|403)$ ]] && ok "https://$d responds ($code)" \
                                             || warn "https://$d returned $code"
    done

    pk=$(grep -oP "define\('API_KEY',\s*'\K[^']+" "$PROD_DIR/familycarer_pro/config.shared.php" 2>/dev/null || true)
    tk=$(grep -oP "define\('API_KEY',\s*'\K[^']+" "$TEST_DIR/familycarer_pro/config.shared.php" 2>/dev/null || true)
    if [[ -n "$pk" && "$pk" == "$tk" ]]; then
        ok "both deployments share one API key"
    else
        warn "API keys DIFFER between production and test — the app will get 401"
        warn "  production: ${pk:-<none>}"
        warn "  test:       ${tk:-<none>}"
    fi

    ic=$(grep -oP "define\('INVITE_CODE',\s*'\K[^']+" "$PROD_DIR/familycarer_pro/config.shared.php" 2>/dev/null || true)
    [[ -n "$ic" ]] && ok "invite code: $ic" || warn "no INVITE_CODE in the config"
fi

echo
if [[ $APPLY -eq 0 ]]; then
    echo "${BOLD}Dry run complete.${OFF} Re-run with --apply to make these changes."
else
    echo "${BOLD}Done.${OFF}"
    echo "  Admin console: https://${DOMAIN}/admin/login.php"
    echo "  Sign in with the administrator email and password from the"
    echo "  credentials email sent when this care home was created."
fi
echo
