#!/bin/sh
set -eu
(set -o pipefail) 2>/dev/null && set -o pipefail

HIPERISO_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
GUI="$HIPERISO_ROOT/src/gui"
PLUGSON="$HIPERISO_ROOT/src/plugson"
PAYLOAD="$HIPERISO_ROOT/build/payload"

CFLAGS="-O2 -std=gnu99 -D_FILE_OFFSET_BITS=64 -DSTATIC=static -DINIT= -DLINUX -Wno-unused-function"
INCLUDES_GUI="-I$GUI/Core -I$GUI/Web -I$GUI/GTK -I$GUI/Include -I$GUI \
    -I$GUI/Lib/libhttp/include -I$GUI/Lib/fat_io_lib/include \
    -I$GUI/Lib/xz-embedded/linux/include -I$GUI/Lib/xz-embedded/linux/include/linux \
    -I$GUI/Lib/xz-embedded/userspace -I$GUI/Lib/exfat/src/libexfat \
    -I$GUI/Lib/exfat/src/mkfs -I$GUI/Lib/fat_io_lib"

INCLUDES_PS="-I$PLUGSON/src -I$PLUGSON/src/Core -I$PLUGSON/src/Web -I$PLUGSON/src/Include \
    -I$PLUGSON/src/Lib/libhttp/include -I$PLUGSON/src/Lib/fat_io_lib/include \
    -I$PLUGSON/src/Lib/xz-embedded/linux/include -I$PLUGSON/src/Lib/xz-embedded/linux/include/linux \
    -I$PLUGSON/src/Lib/xz-embedded/userspace -I$PLUGSON/src/Lib/exfat/src/libexfat \
    -I$PLUGSON/src/Lib/exfat/src/mkfs -I$PLUGSON/src/Lib/fat_io_lib"

build_civetweb() {
    echo ">>> Compiling civetweb ($1)"
    gcc -std=gnu99 -D_FILE_OFFSET_BITS=64 -O2 -Wall -Wno-unused-function \
        -DLINUX -DNDEBUG -DNO_CGI -DNO_CACHING -DNO_SSL \
        -DSQLITE_DISABLE_LFS -DSSL_ALREADY_INITIALIZED \
        -DUSE_STACK_SIZE=102400 -fPIC \
        -I"$1/Lib/libhttp/include" \
        -c "$1/Lib/libhttp/include/civetweb.c" -o "$2/civetweb.o"
}

safe_install_bin() {
    src="$1"
    dst="$2"
    tmp="${dst}.new"
    cp "$src" "$tmp"
    chmod +x "$tmp" 2>/dev/null || true
    mv -f "$tmp" "$dst"
}

mkdir -p "$PAYLOAD/tool/x86_64" "$PAYLOAD/WebUI" "$PAYLOAD/plugson.www"
cp "$HIPERISO_ROOT/assets/languages.json" "$PAYLOAD/tool/languages.json"
cp "$HIPERISO_ROOT/assets/HiperisoGTK.glade" "$PAYLOAD/tool/HiperisoGTK.glade"

# ── Qt5 GUI ──
echo ">>> Building Hiperiso2Disk.qt5"
mkdir -p "$GUI/QT/build_output"
cd "$GUI/QT"
qmake Hiperiso2Disk.pro -o build_output/Makefile "CONFIG+=release"
make -j"$(nproc)" -C build_output 2>&1 | tail -5
strip build_output/Hiperiso2Disk
safe_install_bin build_output/Hiperiso2Disk "$PAYLOAD/tool/x86_64/Hiperiso2Disk.qt5"

# ── GTK3 GUI ──
echo ">>> Building Hiperiso2Disk.gtk3"
BUILDDIR=$(mktemp -d)
cd "$BUILDDIR"
build_civetweb "$GUI" .
gcc $CFLAGS $(pkg-config --cflags gtk+-3.0) $INCLUDES_GUI \
    "$GUI/main_gtk.c" "$GUI/Core/"*.c "$GUI/Web/"*.c "$GUI/GTK/"*.c \
    "$GUI/Lib/xz-embedded/linux/lib/decompress_unxz.c" \
    "$GUI/Lib/exfat/src/libexfat/"*.c "$GUI/Lib/exfat/src/mkfs/"*.c \
    "$GUI/Lib/fat_io_lib/"*.c civetweb.o \
    $(pkg-config --libs gtk+-3.0) -lpthread \
    -o Hiperiso2Disk.gtk3
strip Hiperiso2Disk.gtk3
safe_install_bin Hiperiso2Disk.gtk3 "$PAYLOAD/tool/x86_64/Hiperiso2Disk.gtk3"

# ── GUI launcher wrapper ──
echo ">>> Building HiperisoGUI"
gcc -O2 -D_FILE_OFFSET_BITS=64 \
    "$GUI/hiperiso_gui.c" "$GUI/Core/hiperiso_json.c" \
    -I"$GUI/Core" -DHISO_GUI_ARCH="\"x86_64\"" \
    -o HiperisoGUI.x86_64
strip HiperisoGUI.x86_64
safe_install_bin HiperisoGUI.x86_64 "$PAYLOAD/HiperisoGUI.x86_64"

# ── WebUI ──
echo ">>> Building HiperisoWeb"
build_civetweb "$GUI" .
gcc $CFLAGS $INCLUDES_GUI \
    "$GUI/main_webui.c" \
    "$GUI/Core/hiperiso_json.c" "$GUI/Core/hiperiso_util.c" \
    "$GUI/Core/hiperiso_disk.c" "$GUI/Core/hiperiso_log.c" \
    "$GUI/Core/hiperiso_md5.c" "$GUI/Core/hiperiso_crc32.c" \
    "$GUI/Web/"*.c \
    "$GUI/Lib/xz-embedded/linux/lib/decompress_unxz.c" \
    "$GUI/Lib/exfat/src/libexfat/"*.c "$GUI/Lib/exfat/src/mkfs/"*.c \
    "$GUI/Lib/fat_io_lib/"*.c civetweb.o \
    -lpthread -o HiperisoWeb
strip HiperisoWeb
safe_install_bin HiperisoWeb "$PAYLOAD/tool/x86_64/HiperisoWeb"
cp -a "$HIPERISO_ROOT/assets/webui/"* "$PAYLOAD/WebUI/"
OLD_SHORT="$(printf '\166\164\157\171')"
OLD_SHORT_CAP="$(printf '\126\164\157\171')"
OLD_BRAND="$(printf '\126\145\156\164\157\171')"

sed -i "s#/${OLD_SHORT}/json#/hiso/json#g" "$PAYLOAD/WebUI/static/js/"*.js 2>/dev/null || true
mv "$PAYLOAD/WebUI/static/js/${OLD_SHORT}.js" "$PAYLOAD/WebUI/static/js/hiso.js" 2>/dev/null || true
mv "$PAYLOAD/WebUI/static/js/jquery.${OLD_SHORT}.alert.js" "$PAYLOAD/WebUI/static/js/jquery.hiso.alert.js" 2>/dev/null || true
mv "$PAYLOAD/WebUI/static/css/${OLD_SHORT}.css" "$PAYLOAD/WebUI/static/css/hiso.css" 2>/dev/null || true
sed -i "s#static/js/jquery\\.${OLD_SHORT}\\.alert\\.js#static/js/jquery.hiso.alert.js#g; s#static/js/${OLD_SHORT}\\.js#static/js/hiso.js#g; s#static/css/${OLD_SHORT}\\.css#static/css/hiso.css#g" "$PAYLOAD/WebUI/index.html" 2>/dev/null || true
mv "$PAYLOAD/WebUI/static/img/${OLD_BRAND}Logo.png" "$PAYLOAD/WebUI/static/img/HiperisoLogo.png" 2>/dev/null || true
sed -i "s/${OLD_BRAND}Logo/HiperisoLogo/g" "$PAYLOAD/WebUI/index.html" 2>/dev/null || true

sed -i 's/callVtoyASyncTimeout/callHisoAsyncTimeout/g' "$PAYLOAD/WebUI/static/js/hiso.js" "$PAYLOAD/WebUI/index.html" 2>/dev/null || true
sed -i "s/${OLD_SHORT}/hiso/g; s/${OLD_SHORT_CAP}/Hiso/g" "$PAYLOAD/WebUI/index.html" "$PAYLOAD/WebUI/static/js/hiso.js" "$PAYLOAD/WebUI/static/js/jquery.hiso.alert.js" "$PAYLOAD/WebUI/static/css/hiso.css" 2>/dev/null || true

# ── Generate languages.js from languages.json ──
python3 - "$PAYLOAD/tool/languages.json" "$PAYLOAD/WebUI/static/js/languages.js" <<'PY'
import json, sys
with open(sys.argv[1], 'r', encoding='utf-8') as f:
    langs = json.load(f)
with open(sys.argv[2], 'w', encoding='utf-8') as f:
    f.write('// Auto-generated from languages.json - do not edit manually\n')
    f.write('var hiso_language_data = ')
    json.dump(langs, f, ensure_ascii=False, separators=(',', ':'))
    f.write(';\n')
PY

# ── Add logo to header ──
sed -i 's#<section class="content" id="hiso-content">#<section class="content" id="hiso-content">\n<div style="text-align:center; margin-bottom:5px;"><img src="static/img/HiperisoLogo.png" alt="Hiperiso" style="height:30px;"></div>#' "$PAYLOAD/WebUI/index.html" 2>/dev/null || true

# ── Replace Chinese defaults with English (overwritten by language JS at runtime) ──
sed -i \
    -e 's/在磁盘最后保留一段空间/Reserve space at the end of disk/g' \
    -e 's/分区按照 4KB 对齐/Align partitions to 4KB boundaries/g' \
    -e 's/>确定</>OK</g' \
    -e 's/>取消</>Cancel</g' \
    -e 's/>配置选项 />Option /g' \
    -e 's/>安全启动支持</>Secure Boot Support</g' \
    -e 's/>分区类型</>Partition Style</g' \
    -e 's/>分区设置</>Partition Configuration</g' \
    -e 's/>清除 Hiperiso</>Clear Hiperiso</g' \
    -e 's/>显示所有设备</>Show All Devices</g' \
    -e 's/>设备</>Device</g' \
    -e 's/>安装包内 Hiperiso 版本</>Hiperiso in Package</g' \
    -e 's/>设备内部 Hiperiso 版本</>Hiperiso in Device</g' \
    -e 's/>状态 - 准备就绪</>Status - Ready</g' \
    -e 's/>安装</>Install</g' \
    -e 's/>升级</>Update</g' \
    "$PAYLOAD/WebUI/index.html" 2>/dev/null || true

# ── Remove overflow:hidden from body ──
sed -i 's/<body style="overflow:hidden;">/<body>/g' "$PAYLOAD/WebUI/index.html" 2>/dev/null || true

# ── Apply brand color (#2d8e57) to WebUI ──
sed -i 's/#2F7095/#2d8e57/g' "$PAYLOAD/WebUI/static/css/hiso.css" 2>/dev/null || true
sed -i 's/color:#ea991f/color:#2d8e57/g' "$PAYLOAD/WebUI/index.html" 2>/dev/null || true
cat >> "$PAYLOAD/WebUI/static/css/hiso.css" << 'BRANDCSS'

#HisoBtnInstall, #HisoBtnUpdate {
    background-color: #2d8e57 !important;
    border-color: #256e44 !important;
    color: #ffffff !important;
}
#HisoBtnInstall:hover, #HisoBtnUpdate:hover {
    background-color: #329f66 !important;
    border-color: #256e44 !important;
}
#HisoBtnInstall:disabled, #HisoBtnUpdate:disabled {
    background-color: #a9cdb8 !important;
    border-color: #94bda3 !important;
}
BRANDCSS

# ── Plugson ──
echo ">>> Building Plugson"
build_civetweb "$PLUGSON/src" .
gcc $CFLAGS $INCLUDES_PS \
    "$PLUGSON/src/main_linux.c" \
    "$PLUGSON/src/Core/hiperiso_crc32.c" "$PLUGSON/src/Core/hiperiso_disk.c" \
    "$PLUGSON/src/Core/hiperiso_disk_linux.c" "$PLUGSON/src/Core/hiperiso_json.c" \
    "$PLUGSON/src/Core/hiperiso_log.c" "$PLUGSON/src/Core/hiperiso_md5.c" \
    "$PLUGSON/src/Core/hiperiso_utf.c" "$PLUGSON/src/Core/hiperiso_util.c" \
    "$PLUGSON/src/Core/hiperiso_util_linux.c" \
    "$PLUGSON/src/Web/"*.c \
    "$PLUGSON/src/Lib/xz-embedded/linux/lib/decompress_unxz.c" \
    "$PLUGSON/src/Lib/fat_io_lib/"*.c civetweb.o \
    -lpthread -o Plugson
strip Plugson
safe_install_bin Plugson "$PAYLOAD/tool/x86_64/Plugson"
cp -a "$PLUGSON/www" "$PAYLOAD/plugson.www"

# ── Utility binaries ──
echo ">>> Building utility binaries"
gcc -O2 -D_FILE_OFFSET_BITS=64 -fno-pie -no-pie \
    "$HIPERISO_ROOT/src/hisocli/hisocli.c" \
    "$HIPERISO_ROOT/src/hisocli/hisofat.c" \
    "$HIPERISO_ROOT/src/hisocli/hisogpt.c" \
    "$HIPERISO_ROOT/src/hisocli/crc32.c" \
    "$HIPERISO_ROOT/src/hisocli/partresize.c" \
    -I"$HIPERISO_ROOT/src/hisocli/fat_io_lib/include" \
    "$HIPERISO_ROOT/src/hisocli/fat_io_lib/lib/libfat_io_64.a" \
    -o hisocli
strip hisocli
safe_install_bin hisocli "$PAYLOAD/tool/x86_64/hisocli"

gcc -O2 -D_FILE_OFFSET_BITS=64 -fno-pie -no-pie \
    "$HIPERISO_ROOT/src/hisolnk/crc32.c" \
    "$HIPERISO_ROOT/src/hisolnk/main_linux.c" \
    "$HIPERISO_ROOT/src/hisolnk/hlnk.c" \
    -I"$HIPERISO_ROOT/src/hisolnk" \
    -o hisolnk
strip hisolnk
safe_install_bin hisolnk "$PAYLOAD/tool/x86_64/hisolnk"
chmod +x "$PAYLOAD/tool/x86_64/"*

# ── Launcher scripts ──
cp "$HIPERISO_ROOT/src/installer/Hiperiso.sh" "$PAYLOAD/" 2>/dev/null || true
cp "$HIPERISO_ROOT/src/installer/HiperisoQt.sh" "$PAYLOAD/" 2>/dev/null || true
cp "$HIPERISO_ROOT/src/installer/HiperisoGtk.sh" "$PAYLOAD/" 2>/dev/null || true
cp "$HIPERISO_ROOT/src/installer/HiperisoWeb.sh" "$PAYLOAD/" 2>/dev/null || true
cp "$HIPERISO_ROOT/src/installer/HiperisoPlugson.sh" "$PAYLOAD/" 2>/dev/null || true
cp "$HIPERISO_ROOT/src/installer/hisocli" "$PAYLOAD/" 2>/dev/null || true
cp "$HIPERISO_ROOT/src/installer/hisolnk" "$PAYLOAD/" 2>/dev/null || true

cd "$HIPERISO_ROOT"
rm -rf "${BUILDDIR:-}"

echo ""
echo "=== All GUI/web tools built ==="
ls -lh "$PAYLOAD/tool/x86_64/"
