#!/bin/bash
set -e

FPC_VER=3.3.1
LAZ_OPT="-v0e -g-"
FPC_OPT="-v0e"
SRCDIR="$PWD/src"
OUTDIR="$PWD/release"

mkdir -p "$OUTDIR"
mkdir -p "$SRCDIR/lazarus" "$SRCDIR/fpc"

docker build --pull \
  -t lazarus-buildenv:stable \
  --build-arg FPC_OLDSTABLE_VER=3.2.0 \
  --build-arg FPC_STABLE_VER=3.2.2 \
  --build-arg FPC_FIXES_VER=3.2.3 \
  --build-arg FPC_MAIN_VER=3.3.1 \
  -f buildenv.Dockerfile \
  https://gitlab.com/freepascal.org/lazarus/lazarus.git#main

docker run --rm -it \
  -v "$OUTDIR":/output \
  -v "$SRCDIR/lazarus":/opt/lazarus \
  -v "$SRCDIR/fpc":/opt/fpcsrc \
  --name lazarus-trunk-win64 \
  lazarus-buildenv:stable bash -c "
    set -e

    echo '📦 Installing rsync and zip...'
    apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y rsync zip

    echo '📥 Cloning Lazarus trunk...'
    if [ -d /opt/lazarus/.git ]; then
      cd /opt/lazarus
      git reset --hard
      git clean -xdff
      git checkout main
      git pull
    else
      git clone -c core.autocrlf=true --branch main --depth=1 https://gitlab.com/freepascal.org/lazarus/lazarus.git /opt/lazarus
    fi

    cd /opt/lazarus

    echo '🔨 Building lazbuild...'
    make lazbuild FPC=/usr/lib/fpc/3.2.2/ppcx64 OPT=\"$LAZ_OPT\"

    echo '🧩 Regenerating makefiles under components/...'
    find /opt/lazarus/components -name Makefile.fpc -print0 \
      | xargs -0 -n1 dirname \
      | sort -u \
      | while IFS= read -r dir; do
          echo \"   -> \$dir\"
          ( cd \"\$dir\" && rm -f Makefile && fpcmake -T x86_64-win64 ) || exit 1
        done
 
    echo '🔨 Building bigide for Win64...'
    make bigide FPC=/usr/lib/fpc/$FPC_VER/ppcrossx64 OS_TARGET=win64 CPU_TARGET=x86_64 LCL_PLATFORM=win32 OPT=\"$LAZ_OPT\"

    echo '🔨 Building LCL, LazUtils, IdeIntf, SynEdit for Win32...'
    /opt/lazarus/lazbuild \
      lcl lazutils ideintf synedit \
      --cpu=i386 --os=win32 \
      --compiler=/usr/lib/fpc/$FPC_VER/ppcross386 \
      --lazarusdir=/opt/lazarus \
      --opt=\"$LAZ_OPT\"

    echo '📥 Cloning FPC trunk source...'
    if [ -d /opt/fpcsrc/.git ]; then
      cd /opt/fpcsrc
      git reset --hard
      git clean -xdff
      git checkout main
      git pull
    else
      git clone -c core.autocrlf=true --branch main --depth=1 https://gitlab.com/freepascal.org/fpc/source.git /opt/fpcsrc
    fi

    echo '🧼 Cleaning any previous FPC builds...'
    cd /opt/fpcsrc
    make distclean || true

    echo '🔨 Building full FPC compiler toolchain for Win64...'
    make distclean all zipinstall \
      PREFIX=\"P:\\Lazarus\\FPC\\\$FPC_VER\" \
      FPC=/usr/lib/fpc/$FPC_VER/ppcx64 \
      OS_TARGET=win64 CPU_TARGET=x86_64 \
      OPT=\"$FPC_OPT\" \
      BINDIR=/dev/null MANDIR=/dev/null SHAREDIR=/dev/null DOCDIR=/dev/null

    echo '📦 Preparing portable ZIP directory...'
    INSTALLDIR=/tmp/lazarus-win64
    mkdir -p \$INSTALLDIR
    rsync -a --exclude=.git* --exclude=*.bak /opt/lazarus/ \$INSTALLDIR/

    echo '📁 Assembling FPC runtime layout...'
    FPCBASE=\$INSTALLDIR/fpc/$FPC_VER
    mkdir -p \$FPCBASE/
    mkdir -p \$FPCBASE/source

    echo '📄 Copying Windows-native FPC binaries...'
    HOST_PLATFORM=\$(fpc -iTP)-\$(fpc -iTO)
    tar -xzf /opt/fpcsrc/fpc-${FPC_VER}.x86_64-win64.built.on.\${HOST_PLATFORM}.tar.gz --directory=\"\$FPCBASE\"

    echo '🧹 Removing all example directories from FPC docs...'
    find \$FPCBASE/share/doc -type d -name examples -exec rm -rfv {} +
    find \$FPCBASE/share/doc -type d -empty -delete
    mkdir -p \$FPCBASE/doc
    mv -t \$FPCBASE/doc \$FPCBASE/share/doc/fpc-$FPC_VER/*
    rm -rfv \$FPCBASE/share

    echo '🔨 Building FPC tools for Win64...'
    for tooldir in \
      utils/fpcres \
      utils/fpdoc \
      utils/fppkg \
      utils/fpcmkcfg \
      utils/fpcm \
      utils/h2pas \
      utils/instantfpc \
      utils/pas2fpm \
      utils
    do
      echo \"🔧 Building tool: \$tooldir\"
      cd /opt/fpcsrc/\$tooldir
      make clean all zipinstall \
        PREFIX=\"P:\\Lazarus\\FPC\\\$FPC_VER\" \
        FPC=/usr/lib/fpc/$FPC_VER/ppcrossx64 \
        OS_TARGET=win64 CPU_TARGET=x86_64 \
        BINDIR=/dev/null MANDIR=/dev/null SHAREDIR=/dev/null DOCDIR=/dev/null \
        OPT=\"$FPC_OPT\" || {
          echo \"❌ Failed building \$tooldir\"
          exit 1
        }
      tar -xzf *.x86_64-win64.tar.gz --directory=\"\$FPCBASE\"
    done

    echo '🧹 Removing build artifacts from FPC tree...'
    cd /opt/fpcsrc
    make distclean || true

    echo '📁 Copying FPC source (rtl + packages)...'
    cp -r /opt/fpcsrc/rtl \"\$FPCBASE/source/\"
    cp -r /opt/fpcsrc/packages \"\$FPCBASE/source/\"

    echo '🧩 Generating fpc.cfg using fpcmkcfg...'
    /usr/bin/fpcmkcfg -d basepath=\"P:\\\\Lazarus\\\\fpc\\\\\\\$fpcversion\" -o \$FPCBASE/bin/x86_64-win64/fpc.cfg

    echo '🔨 Building full FPC compiler toolchain for Win32...'
    make distclean crosszipinstall \
      PREFIX=\"P:\\Lazarus\\FPC\\\$FPC_VER\" \
      FPC=/usr/lib/fpc/$FPC_VER/ppcx64 \
      OS_TARGET=win32 CPU_TARGET=i386 \
      OPT=\"$FPC_OPT\" \
      BINDIR=/dev/null MANDIR=/dev/null SHAREDIR=/dev/null DOCDIR=/dev/null

    echo '📄 Copying Windows-native FPC cross-compiler Win32...'
    tar -xzf /opt/fpcsrc/fpc-${FPC_VER}.i386-win32.built.on.\${HOST_PLATFORM}.tar.gz --directory=\"\$FPCBASE\"

    echo '🧹 Cleaning up...'
    find \$FPCBASE/bin -maxdepth 1 -type f -exec mv {} \$FPCBASE/bin/x86_64-win64/ \\;
    rsync -a --remove-source-files \$FPCBASE/lib/fpc/$FPC_VER/ \$FPCBASE/
    rm -rf \$FPCBASE/lib

    echo '🔨 Building documentation...'
    cd /opt/lazarus/docs/html
    unzip -j /doc-chm.zip -d \$INSTALLDIR/docs/chm
    /opt/lazarus/lazbuild \
      --lazarusdir=/opt/lazarus \
      --compiler=/usr/lib/fpc/3.2.2/ppcx64 \
      build_lcl_docs.lpi
    ./build_lcl_docs --fpdoc=/usr/bin/fpdoc --fpcdocs=\$INSTALLDIR/docs/chm --outfmt=chm --footer locallclfooter.xml --warnings

    echo '🧹 Removing build artifacts from Lazarus tree...'
    find \$INSTALLDIR -type d -name \"\$HOST_PLATFORM\" -exec rm -rfv {} +

    echo '🧼 Removing all ELF binaries from Lazarus ZIP tree...'
    find \$INSTALLDIR -type f -exec file {} + | grep ELF | cut -d: -f1 | xargs rm -fv || true

    echo '📦 Creating zip archive...'
    ZIPFILE=lazarus-${LAZ_VER}-fpc-${FPC_VER}-win64.zip
    rm -f /output/\$ZIPFILE || true
    zip -9 -r /output/\$ZIPFILE \$INSTALLDIR

    echo \"✅ ZIP created: \$ZIPFILE\"
    ls -lh /output/\$ZIPFILE
  "

echo "🎉 Done. Check your '$OUTDIR' directory for the ZIP."

