cat > /root/fix_bme_logging.sh <<'SH'
#!/usr/bin/env bash
set -euo pipefail

echo "== 1) Confirm apache is running"
systemctl status apache2 --no-pager || true

echo "== 2) Ensure log dir exists"
mkdir -p /var/log/apache2

echo "== 3) Enable access/error logs in the default SSL vhost (safe, reversible)"
# We patch the first enabled SSL vhost we can find; if none, patch the first enabled vhost.
VHOST=""
for f in /etc/apache2/sites-enabled/*ssl*.conf /etc/apache2/sites-enabled/*.conf; do
  [[ -f "$f" ]] || continue
  VHOST="$f"
  break
done

if [[ -z "$VHOST" ]]; then
  echo "No vhost found in /etc/apache2/sites-enabled/"
  exit 1
fi

echo "Using vhost: $VHOST"

TS="$(date +%y%m%d.%H%M%S)"
cp -a "$VHOST" "${VHOST}.bak.${TS}"

# Make sure LogFormat exists (usually in apache2.conf, but we enforce here only if missing)
# We'll only add CustomLog/ErrorLog if missing in this vhost file.
if ! grep -qE '^\s*ErrorLog\s+' "$VHOST"; then
  echo "Adding ErrorLog to vhost"
  printf "\nErrorLog /var/log/apache2/lupton_error.log\n" >> "$VHOST"
fi

if ! grep -qE '^\s*CustomLog\s+' "$VHOST"; then
  echo "Adding CustomLog to vhost"
  printf "CustomLog /var/log/apache2/lupton_access.log combined\n" >> "$VHOST"
fi

echo "== 4) Ensure log files exist"
touch /var/log/apache2/lupton_access.log /var/log/apache2/lupton_error.log
chown root:adm /var/log/apache2/lupton_access.log /var/log/apache2/lupton_error.log
chmod 640 /var/log/apache2/lupton_access.log /var/log/apache2/lupton_error.log

echo "== 5) Validate apache config"
apache2ctl configtest

echo "== 6) Reload apache"
systemctl reload apache2

echo "== 7) Show where logs are now writing"
ls -l /var/log/apache2/lupton_access.log /var/log/apache2/lupton_error.log

echo "== DONE. Tail with:"
echo "  tail -f /var/log/apache2/lupton_access.log | grep --line-buffered 'BME.php'"
echo "  tail -f /var/log/apache2/lupton_error.log"
SH

chmod +x /root/fix_bme_logging.sh
/root/fix_bme_logging.sh
