# GDAL with ECW (read) support, for decoding Environment Agency Vertical Aerial
# Photography in the satellite-highres pipeline (pipeline/download/satellite_highres.py).
#
# EA VAP ships as ECW **v2** rasters, which are readable by the open-source
# libecwj2 3.3 SDK -- the same library the official OSGeo image uses when built
# with WITH_ECW=yes. We therefore avoid the proprietary, login-gated Hexagon
# ERDAS ECW/JP2 SDK (which is only needed for ECW v3) and its licensing
# restrictions entirely.
#
# We build only the ECW driver as a GDAL *plugin* on top of the official runtime
# image (no full GDAL rebuild). The plugin's GDAL sources are pinned to the exact
# commit reported by the base image so libgdal and the plugin stay ABI-compatible.
#
# Build:  docker build -t perfect-postcode/gdal-ecw:latest docker/gdal-ecw
# Verify: docker run --rm perfect-postcode/gdal-ecw:latest gdalinfo --formats | grep -i ECW

FROM ghcr.io/osgeo/gdal:ubuntu-full-latest

ARG LIBECWJ2_URL=https://github.com/rouault/libecwj2-3.3-builds/releases/download/v1/install-libecwj2-3.3-ubuntu-20.04.tar.gz

RUN apt-get update && apt-get install -y --no-install-recommends \
        cmake g++ make git curl ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# Open-source ECW v2 SDK (extracts to /opt/libecwj2-3.3) + make its libs loadable.
RUN curl --retry 3 --retry-all-errors --retry-delay 3 -fsSL -o /tmp/libecwj2.tar.gz "$LIBECWJ2_URL" \
    && tar -C / -xzf /tmp/libecwj2.tar.gz \
    && rm -f /tmp/libecwj2.tar.gz \
    && (cd /opt/libecwj2-3.3/lib && for so in *.so*; do \
            ln -sf "/opt/libecwj2-3.3/lib/$so" "/usr/lib/x86_64-linux-gnu/$so"; \
        done) \
    && ldconfig

# Build the ECW driver plugin against the base image's exact GDAL sources.
RUN set -eux; \
    GDAL_COMMIT="$(gdalinfo --version | sed -nE 's/.*-([0-9a-f]{8,}).*/\1/p')"; \
    test -n "$GDAL_COMMIT"; \
    echo "Building ECW plugin for GDAL commit ${GDAL_COMMIT}"; \
    mkdir -p /tmp/gdal && cd /tmp/gdal && git init -q; \
    git fetch --depth 1 -q https://github.com/OSGeo/gdal.git "$GDAL_COMMIT"; \
    git checkout -q FETCH_HEAD; \
    cmake -S frmts/ecw -B /tmp/ecw-build \
        -DCMAKE_BUILD_TYPE=Release \
        -DCMAKE_PREFIX_PATH=/usr \
        -DECW_ROOT=/opt/libecwj2-3.3; \
    cmake --build /tmp/ecw-build -j"$(nproc)"; \
    PLUGIN_DIR=/usr/lib/x86_64-linux-gnu/gdalplugins; \
    mkdir -p "$PLUGIN_DIR"; \
    find /tmp/ecw-build -name 'gdal_ECW*.so' -exec cp {} "$PLUGIN_DIR/" \; ; \
    rm -rf /tmp/gdal /tmp/ecw-build

# Fail the build if the driver is not actually available.
RUN gdalinfo --formats | grep -iq 'ECW.*rw' && echo "ECW driver OK"
