#!/bin/sh

set -eu

OPENJPEG_VERSION=2.5.4
OPENJPEG_COMMIT=6c4a29b00211eb0430fa0e5e890f1ce5c80f409f

if [ "$#" -ne 1 ] || [ -z "$1" ]; then
    echo "usage: $0 INSTALL_PREFIX" >&2
    exit 2
fi

install_prefix=$1
pkg_config_path="$install_prefix/lib/pkgconfig"
library_path="$install_prefix/lib"

persist_actions_environment() {
    if [ -z "${GITHUB_ENV:-}" ]; then
        return
    fi

    case ":${PKG_CONFIG_PATH:-}:" in
        *":$pkg_config_path:"*) resolved_pkg_config_path=${PKG_CONFIG_PATH:-} ;;
        *) resolved_pkg_config_path="$pkg_config_path${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}" ;;
    esac
    case ":${LD_LIBRARY_PATH:-}:" in
        *":$library_path:"*) resolved_library_path=${LD_LIBRARY_PATH:-} ;;
        *) resolved_library_path="$library_path${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" ;;
    esac

    printf 'PKG_CONFIG_PATH=%s\n' "$resolved_pkg_config_path" >>"$GITHUB_ENV"
    printf 'LD_LIBRARY_PATH=%s\n' "$resolved_library_path" >>"$GITHUB_ENV"
}

if [ -f "$pkg_config_path/libopenjp2.pc" ] &&
    PKG_CONFIG_PATH="$pkg_config_path" pkg-config --exact-version "$OPENJPEG_VERSION" libopenjp2
then
    persist_actions_environment
    exit 0
fi

work_dir=$(mktemp -d "${TMPDIR:-/tmp}/metacrate-openjpeg.XXXXXX")
trap 'rm -rf "$work_dir"' EXIT HUP INT TERM

source_dir="$work_dir/source"
build_dir="$work_dir/build"

git clone --branch "v$OPENJPEG_VERSION" --depth 1 \
    https://github.com/uclouvain/openjpeg.git "$source_dir"

actual_commit=$(git -C "$source_dir" rev-parse HEAD)
if [ "$actual_commit" != "$OPENJPEG_COMMIT" ]; then
    echo "OpenJPEG v$OPENJPEG_VERSION resolved to unexpected commit $actual_commit" >&2
    exit 1
fi

cmake -S "$source_dir" -B "$build_dir" \
    -DBUILD_CODEC=OFF \
    -DBUILD_SHARED_LIBS=ON \
    -DBUILD_TESTING=OFF \
    -DCMAKE_BUILD_TYPE=Release \
    -DCMAKE_INSTALL_LIBDIR=lib \
    -DCMAKE_INSTALL_PREFIX="$install_prefix"
cmake --build "$build_dir" --parallel
cmake --install "$build_dir"

PKG_CONFIG_PATH="$pkg_config_path" pkg-config --exact-version "$OPENJPEG_VERSION" libopenjp2
persist_actions_environment
