#!/bin/bash

set -e
set -x

apt-get update --allow-releaseinfo-change > /dev/null 2>&1

apt-get install -y php${PHP_VERSION}-imagick ghostscript ffmpeg gpac libreoffice unoconv imagemagick xvfb build-essential zlib1g-dev libgif-dev python3-venv python3-pip > /dev/null 2>&1

# Enabling Imagick to read and write PDF files
echo "Enabling ImageMagick to read/write pdfs"
if [ -f /etc/ImageMagick-6/policy.xml ]; then
  sed -i -e 's/<policy domain="coder" rights="none" pattern="PDF" \/>/<policy domain="coder" rights="read|write" pattern="PDF" \/>/' /etc/ImageMagick-6/policy.xml
  sed -i -e 's/<policy domain="coder" rights="none" pattern="EPS" \/>/<policy domain="coder" rights="read|write" pattern="EPS" \/>/' /etc/ImageMagick-6/policy.xml
fi

# If unoconv is installed patch the shebang in unoconv to use the UNO-compatible Python interpreter and install a distutils package (setuptools)
if [ -f /usr/bin/unoconv ]; then
    # Download the find_uno script to detect the correct Python interpreter used by LibreOffice
    # It is necessary because unoconv may not work correctly if it does not use the right Python interpreter
    wget -O /tmp/find_uno.py https://gist.githubusercontent.com/regebro/036da022dc7d5241a0ee97efdf1458eb/raw/find_uno.py

    # Detect Python interpreter used by LibreOffice
    UNO_PYTHON=$(python3 /tmp/find_uno.py | grep '^/' | head -n 1)

    # Fallback if detection fails
    if [ -z "$UNO_PYTHON" ]; then
        echo "Failed to detect LibreOffice Python, defaulting to /usr/bin/python3"
        UNO_PYTHON="/usr/bin/python3"
    else
        echo "Detected LibreOffice-compatible Python: $UNO_PYTHON"
    fi

    echo "Patching /usr/bin/unoconv to use: $UNO_PYTHON"
    sed -i "1s|^#!.*|#!$UNO_PYTHON|" /usr/bin/unoconv

    # Create and activate a virtual environment
    $UNO_PYTHON -m venv /tmp/venv
    source /tmp/venv/bin/activate

    # Install setuptools (contains distutils)
    pip3 install setuptools
    deactivate
fi

wget -P /tmp http://www.ijg.org/files/jpegsrc.v8.tar.gz
cd /tmp && tar -zxf jpegsrc.v8.tar.gz > /dev/null 2>&1
cd /tmp/jpeg-8 && ./configure && make && make install

wget -P /tmp http://download.savannah.gnu.org/releases/freetype/freetype-2.10.1.tar.gz
cd /tmp && tar -zxf freetype-2.10.1.tar.gz > /dev/null 2>&1
cd /tmp/freetype-2.10.1
rm -f config.cache
ranlib /usr/local/lib/libjpeg.a
ldconfig /usr/local/lib
LDFLAGS="-L/usr/local/lib" CPPFLAGS="-I/usr/local/include" ./configure
make && make install

cd /tmp && git clone https://gitlab.com/tikiwiki/libraries/forks/swftools.git
cd /tmp/swftools
LDFLAGS="-L/usr/local/lib" CPPFLAGS="-I/usr/local/include" ./configure
make || make && make install

wget -P /tmp http://archive.ubuntu.com/ubuntu/pool/universe/d/dcraw/dcraw_9.28-2_amd64.deb
cd /tmp && apt-get install -y ./dcraw_9.28-2_amd64.deb

echo "Dependency setup complete"

Xvfb :99 & export DISPLAY=:99
libreoffice --headless --invisible --norestore --accept="socket,host=127.0.0.1,port=2002;urp;" &

sleep 10
