#!/usr/bin/env bash

RUST_LIB="rust/release/libccx_rust.a"
RUST_PROFILE="--release"
USE_SYSTEM_LIBS=false
while [[ $# -gt 0 ]]; do
  case $1 in
    -debug)
      DEBUG=true
      BLD_FLAGS="$BLD_FLAGS -g -fsanitize=address"
      RUST_PROFILE=""
      RUST_LIB="rust/debug/libccx_rust.a"
      shift
      ;;
    -hardsubx)
      HARDSUBX=true
      # Allow overriding FFmpeg version via environment variable
      if [ -n "$FFMPEG_VERSION" ]; then
        RUST_FEATURES="--features hardsubx_ocr,$FFMPEG_VERSION"
      else
        RUST_FEATURES="--features hardsubx_ocr"
      fi
      BLD_FLAGS="$BLD_FLAGS -DENABLE_HARDSUBX"
      BLD_LINKER="$BLD_LINKER -lswscale -lavutil -pthread -lavformat -lavcodec -lavfilter -lxcb-shm -lxcb -lX11 -llzma -lswresample"
      shift
      ;;
    -system-libs)
      USE_SYSTEM_LIBS=true
      shift
      ;;
    -*)
      echo "Unknown option $1"
      exit 1
      ;;
  esac
done

if [ "$USE_SYSTEM_LIBS" = true ]; then
    command -v pkg-config >/dev/null || {
        echo "Error: pkg-config is required for -system-libs mode"
        exit 1
    }
    
    MISSING=""
    for lib in libpng zlib freetype2 libutf8proc; do
        if ! pkg-config --exists "$lib" 2>/dev/null; then
            MISSING="$MISSING $lib"
        fi
    done
    
    if [ -n "$MISSING" ]; then
        echo "Error: Missing required system libraries:$MISSING"
        echo ""
        echo "On Debian/Ubuntu: sudo apt install libpng-dev zlib1g-dev libfreetype-dev libutf8proc-dev"
        exit 1
    fi
    
    for hdr in leptonica/allheaders.h tesseract/capi.h; do
        if ! echo "#include <$hdr>" | gcc -E - >/dev/null 2>&1; then
            echo "Error: Missing headers for <$hdr>"
            echo "On Debian/Ubuntu: sudo apt install libleptonica-dev libtesseract-dev"
            exit 1
        fi
    done
    
    PKG_CFLAGS="$(pkg-config --cflags libpng zlib freetype2 libutf8proc)"
    PKG_LIBS="$(pkg-config --libs libpng zlib freetype2 libutf8proc)"
fi

BLD_FLAGS="$BLD_FLAGS -std=gnu99 -Wno-write-strings -Wno-pointer-sign -D_FILE_OFFSET_BITS=64 -DVERSION_FILE_PRESENT -DENABLE_OCR -DGPAC_DISABLE_VTT -DGPAC_DISABLE_OD_DUMP -DGPAC_DISABLE_REMOTERY -DNO_GZIP"
if [ "$USE_SYSTEM_LIBS" != true ]; then
    BLD_FLAGS="$BLD_FLAGS -DFT2_BUILD_LIBRARY"
fi
bit_os=$(getconf LONG_BIT)
if [ "$bit_os" == "64" ]
then
    BLD_FLAGS="$BLD_FLAGS -DGPAC_64_BITS"
fi
BLD_INCLUDE="-I../src -I /usr/include/leptonica/ -I /usr/include/tesseract/ -I../src/lib_ccx/ -I /usr/include/gpac/ -I../src/thirdparty/libpng -I../src/thirdparty/zlib -I../src/lib_ccx/zvbi -I../src/thirdparty/lib_hash -I../src/thirdparty -I../src/thirdparty/freetype/include"
SRC_LIBPNG="$(find ../src/thirdparty/libpng/ -name '*.c')"
SRC_ZLIB="$(find ../src/thirdparty/zlib/ -name '*.c')"
SRC_CCX="$(find ../src/lib_ccx/ -name '*.c')"
SRC_GPAC="$(find /usr/include/gpac/ -name '*.c' 2>/dev/null)"
SRC_HASH="$(find ../src/thirdparty/lib_hash/ -name '*.c')"
SRC_UTF8PROC="../src/thirdparty/utf8proc/utf8proc.c"
SRC_FREETYPE="../src/thirdparty/freetype/autofit/autofit.c
        ../src/thirdparty/freetype/base/ftbase.c
        ../src/thirdparty/freetype/base/ftbbox.c
        ../src/thirdparty/freetype/base/ftbdf.c
        ../src/thirdparty/freetype/base/ftbitmap.c
        ../src/thirdparty/freetype/base/ftcid.c
        ../src/thirdparty/freetype/base/ftfntfmt.c
        ../src/thirdparty/freetype/base/ftfstype.c
        ../src/thirdparty/freetype/base/ftgasp.c
        ../src/thirdparty/freetype/base/ftglyph.c
        ../src/thirdparty/freetype/base/ftgxval.c
        ../src/thirdparty/freetype/base/ftinit.c
        ../src/thirdparty/freetype/base/ftlcdfil.c
        ../src/thirdparty/freetype/base/ftmm.c
        ../src/thirdparty/freetype/base/ftotval.c
        ../src/thirdparty/freetype/base/ftpatent.c
        ../src/thirdparty/freetype/base/ftpfr.c
        ../src/thirdparty/freetype/base/ftstroke.c
        ../src/thirdparty/freetype/base/ftsynth.c
        ../src/thirdparty/freetype/base/ftsystem.c
        ../src/thirdparty/freetype/base/fttype1.c
        ../src/thirdparty/freetype/base/ftwinfnt.c
        ../src/thirdparty/freetype/bdf/bdf.c
        ../src/thirdparty/freetype/bzip2/ftbzip2.c
        ../src/thirdparty/freetype/cache/ftcache.c
        ../src/thirdparty/freetype/cff/cff.c
        ../src/thirdparty/freetype/cid/type1cid.c
        ../src/thirdparty/freetype/gzip/ftgzip.c
        ../src/thirdparty/freetype/lzw/ftlzw.c
        ../src/thirdparty/freetype/pcf/pcf.c
        ../src/thirdparty/freetype/pfr/pfr.c
        ../src/thirdparty/freetype/psaux/psaux.c
        ../src/thirdparty/freetype/pshinter/pshinter.c
        ../src/thirdparty/freetype/psnames/psnames.c
        ../src/thirdparty/freetype/raster/raster.c
        ../src/thirdparty/freetype/sfnt/sfnt.c
        ../src/thirdparty/freetype/smooth/smooth.c
        ../src/thirdparty/freetype/truetype/truetype.c
        ../src/thirdparty/freetype/type1/type1.c
        ../src/thirdparty/freetype/type42/type42.c
        ../src/thirdparty/freetype/winfonts/winfnt.c"
BLD_SOURCES="../src/ccextractor.c $SRC_CCX $SRC_GPAC $SRC_ZLIB $SRC_LIBPNG $SRC_HASH $SRC_UTF8PROC $SRC_FREETYPE"
BLD_LINKER="$BLD_LINKER -lm -zmuldefs -l tesseract -l leptonica -lpthread -ldl -lgpac"

if [ "$USE_SYSTEM_LIBS" = true ]; then
    LEPTONICA_CFLAGS="$(pkg-config --cflags --silence-errors lept)"
    TESSERACT_CFLAGS="$(pkg-config --cflags --silence-errors tesseract)"
    GPAC_CFLAGS="$(pkg-config --cflags --silence-errors gpac)"

    BLD_INCLUDE="-I../src -I../src/lib_ccx -I../src/lib_ccx/zvbi -I../src/thirdparty/lib_hash \
    $PKG_CFLAGS $LEPTONICA_CFLAGS $TESSERACT_CFLAGS $GPAC_CFLAGS"

    BLD_SOURCES="../src/ccextractor.c $SRC_CCX $SRC_HASH"
    # Preserve FFmpeg libraries if -hardsubx was specified
    FFMPEG_LIBS=""
    if [ "$HARDSUBX" = true ]; then
        FFMPEG_LIBS="-lswscale -lavutil -pthread -lavformat -lavcodec -lavfilter -lxcb-shm -lxcb -lX11 -llzma -lswresample"
    fi
    BLD_LINKER="$PKG_LIBS -ltesseract -lleptonica -lgpac -lpthread -ldl -lm $FFMPEG_LIBS"
fi


echo "Running pre-build script..."
./pre-build.sh
echo "Trying to compile..."

BLD_LINKER="$BLD_LINKER ./libccx_rust.a"
echo "Checking for cargo..."
if ! [ -x "$(command -v cargo)" ]; then
    echo 'Error: cargo is not installed.' >&2
    exit 1
fi

rustc_version="$(rustc --version)"
semver=( ${rustc_version//./ } )
version="${semver[1]}.${semver[2]}.${semver[3]}"
MSRV="1.87.0"
if [ "$(printf '%s\n' "$MSRV" "$version" | sort -V | head -n1)" = "$MSRV" ]; then
    echo "rustc >= MSRV(${MSRV})"
else
    echo "Minimum supported rust version(MSRV) is ${MSRV}, please upgrade rust"
    exit 1
fi

echo "Building rust files..."
(cd ../src/rust && CARGO_TARGET_DIR=../../linux/rust cargo build $RUST_PROFILE $RUST_FEATURES) || { echo "Failed. " ; exit 1; }

cp $RUST_LIB ./libccx_rust.a

echo "Building ccextractor"
out=$((LC_ALL=C gcc $BLD_FLAGS $BLD_INCLUDE -o ccextractor $BLD_SOURCES $BLD_LINKER)2>&1)
res=$?
if [[ $out == *"gcc: command not found"* ]]
then
    echo "Error: please install gcc";
    exit 1
fi
if [[ $out == *"curl.h: No such file or directory"* ]]
then
    echo "Error: please install curl development library (libcurl4-gnutls-dev for Debian/Ubuntu)";
    exit 2
fi
if [[ $out == *"capi.h: No such file or directory"* ]]
then
    echo "Error: please install tesseract development library (libtesseract-dev for Debian/Ubuntu)";
    exit 3
fi
if [[ $out == *"allheaders.h: No such file or directory"* ]]
then
    echo "Error: please install leptonica development library (libleptonica-dev for Debian/Ubuntu)";
    exit 4
fi
if [[ $res -ne 0 ]]  # Unknown error
then
    echo "Compiled with errors"
    >&2 echo "$out"
    exit 5
fi
if [[ "$out" != "" ]] ; then
    echo "$out"
    echo "Compilation successful, compiler message shown in previous lines"
else
    echo "Compilation successful, no compiler messages."
fi

if [ -d ./utf8proc_compat ]; then
    rm -rf ./utf8proc_compat
fi
