#!/bin/bash
set -euo pipefail

INSTALL_DIR=/opt

cd /src
make clean || true

emmake make \
  OS=linux \
  ARCH=x86 \
  USE_ASM=No \
  ENABLE64BIT=No \
  CC=emcc \
  CXX=em++ \
  AR=emar \
  RANLIB=emranlib \
  DEBUGSYMBOLS=False \
  libopenh264.a -j$(nproc)

mkdir -p $INSTALL_DIR/lib
# FIX 1: Change directory structure back to 'wels' so #include "wels/codec_api.h" works
mkdir -p $INSTALL_DIR/include/wels
mkdir -p $INSTALL_DIR/lib/pkgconfig

cp libopenh264.a $INSTALL_DIR/lib/

# Copy headers to the nested wels directory
cp codec/api/wels/*.h $INSTALL_DIR/include/wels/

# FIX 2: Point includedir to the base include path and append -lstdc++ to Libs
cat << EOF > $INSTALL_DIR/lib/pkgconfig/openh264.pc
prefix=$INSTALL_DIR
exec_prefix=\${prefix}
libdir=\${prefix}/lib
includedir=\${prefix}/include

Name: openh264
Description: OpenH264 - H.264 codec library
Version: 2.4.0
Libs: -L\${libdir} -lopenh264 -lstdc++
Cflags: -I\${includedir}
EOF

# Verify
ls -la $INSTALL_DIR/lib/libopenh264.a
ls -la $INSTALL_DIR/include/wels/
cat $INSTALL_DIR/lib/pkgconfig/openh264.pc