#!/bin/bash
set -euo pipefail

SRC_DIR="$(cd "$(dirname "$0")/.." && pwd)"
NGINX_CONF_DIR="/usr/local/nginx/conf"
BACKUP_DIR="/root/binzhou-nginx-backup-$(date +%Y%m%d%H%M%S)"

mkdir -p "$BACKUP_DIR"
mkdir -p "$NGINX_CONF_DIR/rewrite" "$NGINX_CONF_DIR/vhost" "$NGINX_CONF_DIR/vhost-available" /workspace/wwwlogs

for target in \
    "$NGINX_CONF_DIR/nginx.conf" \
    "$NGINX_CONF_DIR/enable-php.conf" \
    "$NGINX_CONF_DIR/enable-php7.4.conf" \
    "$NGINX_CONF_DIR/rewrite/thinkphp.conf" \
    "$NGINX_CONF_DIR/vhost/bzjkzhct.yyangpt.cn.conf" \
    "$NGINX_CONF_DIR/vhost/aibzjkzhct.yyangpt.cn.conf" \
    "$NGINX_CONF_DIR/vhost-available/zysct.bziht.edu.cn-ssl.conf"
do
    if [ -e "$target" ]; then
        cp -a "$target" "$BACKUP_DIR/"
    fi
done

cp -f "$SRC_DIR/files/usr/local/nginx/conf/nginx.conf" "$NGINX_CONF_DIR/nginx.conf"
cp -f "$SRC_DIR/files/usr/local/nginx/conf/enable-php.conf" "$NGINX_CONF_DIR/enable-php.conf"
cp -f "$SRC_DIR/files/usr/local/nginx/conf/enable-php7.4.conf" "$NGINX_CONF_DIR/enable-php7.4.conf"
cp -f "$SRC_DIR/files/usr/local/nginx/conf/rewrite/thinkphp.conf" "$NGINX_CONF_DIR/rewrite/thinkphp.conf"
cp -f "$SRC_DIR/files/usr/local/nginx/conf/vhost/"*.conf "$NGINX_CONF_DIR/vhost/"
cp -f "$SRC_DIR/files/usr/local/nginx/conf/vhost-available/"*.conf "$NGINX_CONF_DIR/vhost-available/"

/usr/local/nginx/sbin/nginx -t

echo "Nginx config applied. Backup: $BACKUP_DIR"
echo "If nginx is already running under systemd, reload with:"
echo "systemctl reload nginx || /usr/local/nginx/sbin/nginx -s reload"
