#!/bin/sh
#
# debian-rime-processor - helper script to build Rime schemas in Debian packaging
#
# SPDX-FileCopyrightText: 2021, 2026 Boyuan Yang <byang@debian.org>
# SPDX-License-Identifier: CC0-1.0 OR BSD-2-Clause

set -e

RIME_DATA_DIR="/usr/share/rime-data"

usage()
{
    printf '%s\n' \
        'Usage: debian-rime-processor default [options]' \
        '  --source-dir DIR       Schema source directory (default: .)' \
        '  --build-dir DIR        Output directory (default: SOURCE/build)' \
        '  --shared-data-dir DIR  Shared source data (default: /usr/share/rime-data)' \
        'Relative paths are resolved from the calling working directory.'
}

if [ "$#" -eq 1 ] && { [ "$1" = --help ] || [ "$1" = -h ]; }; then
    usage
    exit 0
fi
if [ "$#" -eq 0 ] || [ "$1" != default ]; then
    usage >&2
    exit 2
fi
shift

source_dir=.
build_dir=
data_dir=$RIME_DATA_DIR
while [ "$#" -gt 0 ]; do
    case "$1" in
        --source-dir|--build-dir|--shared-data-dir)
            if [ "$#" -lt 2 ] || [ -z "$2" ]; then
                printf '%s\n' "E: $1 requires a nonempty directory argument." >&2
                exit 2
            fi
            case "$1" in
                --source-dir) source_dir=$2 ;;
                --build-dir) build_dir=$2 ;;
                --shared-data-dir) data_dir=$2 ;;
            esac
            shift 2
            ;;
        *)
            usage >&2
            exit 2
            ;;
    esac
done

source_dir=$(realpath -- "$source_dir")
if [ ! -d "$source_dir" ]; then
    printf '%s\n' "E: Source directory does not exist: $source_dir" >&2
    exit 1
fi
build_dir=$(realpath -m -- "${build_dir:-$source_dir/build}")
data_dir=$(realpath -m -- "$data_dir")
case "$source_dir/" in
    "${build_dir%/}/"*)
        printf '%s\n' 'E: The output directory must not contain the source directory.' >&2
        exit 1
        ;;
esac
cd "$source_dir"

set -- ./*.schema.yaml
if [ ! -f "$1" ]; then
    printf '%s\n' 'E: No Rime schemas found in the source directory.' >&2
    exit 1
fi

printf '%s\n' 'I: Running default Debian Rime build...'

# Expose missing source dependencies, but neither installed build products nor
# copies of files owned by this source package. The latter could otherwise make
# librime move an older local schema into its user-data trash directory.
shared_dir=$(mktemp -d "${TMPDIR:-/tmp}/debian-rime-processor.XXXXXX")
trap 'rm -rf -- "$shared_dir"' 0
trap 'exit 1' HUP INT TERM
for dependency in "$data_dir"/*.*; do
    [ -f "$dependency" ] || continue
    name=${dependency##*/}
    if [ ! -e "./$name" ] && [ ! -L "./$name" ]; then
        ln -s "$dependency" "$shared_dir/$name"
    fi
done

for schema do
    rime_deployer --compile "$schema" "$source_dir" "$shared_dir" "$build_dir"
done
printf '%s\n' 'I: Finished.'
