#!/bin/sh

set -eu

WEBAPP_ROOT="/home/webapp"
ENV_ROOT="$WEBAPP_ROOT/env"
APP_ROOT="$WEBAPP_ROOT/loan-pricing"
JAVA_HOME="$ENV_ROOT/java"
NGINX_HOME="$ENV_ROOT/nginx"
NGINX_CONF="$NGINX_HOME/conf/nginx.conf"
BACKEND_DIR="$APP_ROOT/backend"
FRONTEND_DIR="$APP_ROOT/frontend"
BACKUP_DIR="$APP_ROOT/backup"
LOG_DIR="$APP_ROOT/logs"
RUN_DIR="$APP_ROOT/run"
TMP_DIR="$APP_ROOT/tmp"
BACKEND_PORT=63310
FRONTEND_PORT=63311

timestamp() {
    date "+%Y-%m-%d %H:%M:%S"
}

log_info() {
    printf '[%s] %s\n' "$(timestamp)" "$1"
}

log_error() {
    printf '[%s] %s\n' "$(timestamp)" "$1" >&2
}

require_root() {
    if [ "$(id -u)" -ne 0 ]; then
        log_error "请使用 root 用户执行安装脚本"
        exit 1
    fi
}

require_command() {
    if ! command -v "$1" >/dev/null 2>&1; then
        log_error "缺少命令: $1"
        exit 1
    fi
}

ensure_base_dirs() {
    mkdir -p "$ENV_ROOT" "$BACKEND_DIR" "$FRONTEND_DIR" "$BACKUP_DIR" "$LOG_DIR" "$RUN_DIR" "$TMP_DIR"
}

find_archive() {
    search_kind="$1"
    found=""

    case "$search_kind" in
        java)
            set -- "$WEBAPP_ROOT/openjdk" "$WEBAPP_ROOT"
            patterns='openjdk*.tar.gz openjdk*.tgz jdk*.tar.gz jdk*.tgz'
            ;;
        nginx)
            set -- "$WEBAPP_ROOT/nginx" "$ENV_ROOT" "$WEBAPP_ROOT"
            patterns='nginx-*.tar.gz nginx-*.tgz'
            ;;
        *)
            log_error "未知的安装包类型: $search_kind"
            exit 1
            ;;
    esac

    for dir in "$@"; do
        if [ ! -d "$dir" ]; then
            continue
        fi

        for pattern in $patterns; do
            candidate=$(find "$dir" -maxdepth 1 -type f -name "$pattern" | sort | head -n 1)
            if [ -n "${candidate:-}" ]; then
                found="$candidate"
                break
            fi
        done

        if [ -n "${found:-}" ]; then
            break
        fi
    done

    if [ -z "${found:-}" ]; then
        log_error "未找到 $search_kind 安装包"
        exit 1
    fi

    printf '%s\n' "$found"
}

install_yum_dependencies() {
    require_command yum

    log_info "安装系统依赖"
    yum install -y \
        gcc \
        make \
        pcre \
        pcre-devel \
        zlib \
        zlib-devel \
        openssl \
        openssl-devel \
        tar \
        gzip \
        unzip \
        which \
        findutils \
        procps-ng \
        iproute
}

install_java() {
    java_archive="$1"

    log_info "安装 Java: $java_archive"
    rm -rf "$JAVA_HOME"
    mkdir -p "$JAVA_HOME"
    tar -xzf "$java_archive" -C "$JAVA_HOME" --strip-components=1

    if [ ! -x "$JAVA_HOME/bin/java" ]; then
        log_error "Java 安装失败，未找到 $JAVA_HOME/bin/java"
        exit 1
    fi

    "$JAVA_HOME/bin/java" -version >/dev/null 2>&1
}

install_nginx() {
    nginx_archive="$1"
    build_dir=$(mktemp -d "$ENV_ROOT/nginx-build.XXXXXX")

    log_info "编译安装 Nginx: $nginx_archive"
    rm -rf "$NGINX_HOME"
    mkdir -p "$NGINX_HOME"

    tar -xzf "$nginx_archive" -C "$build_dir"
    source_dir=$(find "$build_dir" -mindepth 1 -maxdepth 1 -type d | head -n 1)
    if [ -z "${source_dir:-}" ]; then
        rm -rf "$build_dir"
        log_error "Nginx 源码目录解析失败"
        exit 1
    fi

    jobs=$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1)
    (
        cd "$source_dir"
        ./configure --prefix="$NGINX_HOME" --with-http_ssl_module
        make -j"$jobs"
        make install
    )

    rm -rf "$build_dir"

    if [ ! -x "$NGINX_HOME/sbin/nginx" ]; then
        log_error "Nginx 安装失败，未找到 $NGINX_HOME/sbin/nginx"
        exit 1
    fi
}

write_nginx_conf() {
    log_info "写入 Nginx 配置: $NGINX_CONF"

    mkdir -p "$NGINX_HOME/conf" "$NGINX_HOME/logs" "$FRONTEND_DIR/dist"

    cat > "$NGINX_CONF" <<EOF
user  nobody;
worker_processes  1;

error_log  $LOG_DIR/nginx-error.log warn;
pid        $RUN_DIR/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       $NGINX_HOME/conf/mime.types;
    default_type  application/octet-stream;

    log_format main '\$remote_addr - \$remote_user [\$time_local] "\$request" '
                    '\$status \$body_bytes_sent "\$http_referer" '
                    '"\$http_user_agent" "\$http_x_forwarded_for"';

    access_log  $LOG_DIR/nginx-access.log  main;

    sendfile        on;
    keepalive_timeout  65;
    client_max_body_size 100m;

    server {
        listen       $FRONTEND_PORT;
        server_name  _;

        root   $FRONTEND_DIR/dist;
        index  index.html;

        location /prod-api/ {
            proxy_pass         http://127.0.0.1:$BACKEND_PORT/;
            proxy_http_version 1.1;
            proxy_set_header   Host \$host;
            proxy_set_header   X-Real-IP \$remote_addr;
            proxy_set_header   X-Forwarded-For \$proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Proto \$scheme;
        }

        location / {
            try_files \$uri \$uri/ /index.html;
        }
    }
}
EOF

    "$NGINX_HOME/sbin/nginx" -t -c "$NGINX_CONF"
}

main() {
    require_root
    require_command tar
    require_command find
    ensure_base_dirs
    install_yum_dependencies

    java_archive=$(find_archive java)
    nginx_archive=$(find_archive nginx)

    log_info "检测到 Java 安装包: $java_archive"
    log_info "检测到 Nginx 安装包: $nginx_archive"

    install_java "$java_archive"
    install_nginx "$nginx_archive"
    write_nginx_conf

    log_info "环境安装完成"
    log_info "JAVA_HOME=$JAVA_HOME"
    log_info "NGINX_HOME=$NGINX_HOME"
    log_info "前端端口=$FRONTEND_PORT，后端端口=$BACKEND_PORT"
}

main "$@"
