#!/bin/sh

set -eu

ROOT_DIR=$(CDPATH= cd -- "$(dirname "$0")" && pwd)
DATE_STAMP=$(date "+%Y%m%d")
RELEASE_ZIP="$ROOT_DIR/${DATE_STAMP}_892.zip"
BACKEND_JAR_SOURCE="$ROOT_DIR/ruoyi-admin/target/ruoyi-admin.jar"
FRONTEND_DIR="$ROOT_DIR/ruoyi-ui"
FRONTEND_DIST_DIR="$FRONTEND_DIR/dist"
FRONTEND_DIST_ZIP="$FRONTEND_DIR/dist.zip"
NODE_VERSION="14"

log_info() {
    printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$1"
}

log_error() {
    printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$1" >&2
}

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

cleanup() {
    if [ -n "${WORK_DIR:-}" ] && [ -d "$WORK_DIR" ]; then
        rm -rf "$WORK_DIR"
    fi
}

build_backend() {
    log_info "开始构建后端生产 jar"
    (
        cd "$ROOT_DIR"
        mvn -pl ruoyi-admin -am clean package -DskipTests
    )

    if [ ! -f "$BACKEND_JAR_SOURCE" ]; then
        log_error "未生成后端 jar: $BACKEND_JAR_SOURCE"
        exit 1
    fi
}

build_frontend() {
    log_info "开始构建前端生产 dist"
    ROOT_DIR="$ROOT_DIR" NODE_VERSION="$NODE_VERSION" zsh -lic 'nvm use "$NODE_VERSION" >/dev/null && npm --prefix "$ROOT_DIR/ruoyi-ui" run build:prod'

    if [ ! -f "$FRONTEND_DIST_DIR/index.html" ]; then
        log_error "前端生产构建失败，未找到: $FRONTEND_DIST_DIR/index.html"
        exit 1
    fi

    rm -f "$FRONTEND_DIST_ZIP"
    (
        cd "$FRONTEND_DIR"
        zip -qr "$FRONTEND_DIST_ZIP" dist
    )

    if [ ! -f "$FRONTEND_DIST_ZIP" ]; then
        log_error "未生成前端压缩包: $FRONTEND_DIST_ZIP"
        exit 1
    fi
}

package_release() {
    WORK_DIR=$(mktemp -d "${TMPDIR:-/tmp}/loan_pricing_release.XXXXXX")
    trap cleanup EXIT INT TERM

    cp "$BACKEND_JAR_SOURCE" "$WORK_DIR/ruoyi-admin.jar"
    cp "$FRONTEND_DIST_ZIP" "$WORK_DIR/dist.zip"

    rm -f "$RELEASE_ZIP"
    (
        cd "$WORK_DIR"
        zip -qr "$RELEASE_ZIP" ruoyi-admin.jar dist.zip
    )

    log_info "上线压缩包已生成: $RELEASE_ZIP"
}

main() {
    require_command mvn
    require_command zsh
    require_command zip

    build_backend
    build_frontend
    package_release
}

main "$@"
