#!/bin/bash

set -e

mkdir -p /workspace/wwwlogs \
    /workspace/zhct/zhctproject/store \
    /workspace/zhct/zhctproject/ai_api \
    /workspace/zhct/zhctproject/ai_store \
    /workspace/zhct/zhctproject/ai_app \
    /workspace/zhct/zhctlogs/log/zhct/cron \
    /workspace/zhct/zhctlogs/log/aizhct/cron \
    /var/run

# Host-mounted workspaces may contain files that the container user cannot chown
# on macOS bind mounts, so only try to chown runtime log directories.
chown -R www:www /workspace/wwwlogs 2>/dev/null || true
chown -R www:www /workspace/zhct/zhctlogs 2>/dev/null || true

# Normalize known local absolute log paths to container paths.
# This prevents open_basedir failures after mounting host project directories.
if [ -f /workspace/zhct/zhctproject/store/application/config/local/config.php ]; then
    sed -i \
        -e 's|/workspace/wwwroot/log/zhct/|/workspace/zhct/zhctlogs/log/zhct/|g' \
        /workspace/zhct/zhctproject/store/application/config/local/config.php
fi

if [ -f /workspace/zhct/zhctproject/ai_api/.env.local ]; then
    sed -i \
        -e 's|/workspace/wwwroot/log/aizhct/|/workspace/zhct/zhctlogs/log/aizhct/|g' \
        -e 's|/var/www/html/runtime/log/|/workspace/zhct/zhctlogs/log/aizhct/|g' \
        /workspace/zhct/zhctproject/ai_api/.env.local

    if [ "${USE_LOCAL_REDIS:-0}" = "1" ]; then
        # Optional local Docker Redis runs on the zhct_default network.
        sed -i '/^\[REDIS\]/,/^\[/{s/^HOSTNAME *=.*/HOSTNAME = redis/;s/^HOSTPORT *=.*/HOSTPORT = 6379/;s/^PASSWORD *=.*/PASSWORD =/;s/^SELECT *=.*/SELECT = 0/;}' \
            /workspace/zhct/zhctproject/ai_api/.env.local
    fi
fi

rm -f /tmp/php-cgi.sock /tmp/php-cgi7.4.sock

/usr/local/php7.3/sbin/php-fpm -D --fpm-config /usr/local/php7.3/etc/php-fpm.conf
/usr/local/php7.4/sbin/php-fpm -D --fpm-config /usr/local/php7.4/etc/php-fpm.conf

exec /usr/sbin/nginx -c /usr/local/nginx/conf/nginx.conf -g "daemon off;"
