#!/bin/sh
set -e


LUPDATE=${LUPDATE:-lupdate}
LCONVERT=${LCONVERT:-lconvert}

die() {
    echo "ERROR: $*" >&2
    exit 1
}

usage() {
    cat <<EOF
Usage: $(basename $0) [src_files]... -o [pot_file]

Creates a .pot file for code translated using Qt translation system.
EOF
    exit 1
}

src_files=""
pot_file=""
while [ $# -gt 0 ] ; do
    case "$1" in
    -h|--help)
        usage
        ;;
    -o|--output)
        pot_file="$2"
        shift 2
        ;;
    -*)
        die "Unknown option $1"
        ;;
    *)
        src_files="$src_files $1"
        shift
        ;;
    esac
done

if [ -z "$src_files" ] ; then
    die "No source files provided"
fi
if [ -z "$pot_file" ] ; then
    die "No pot file provided, please provide one with the -o option"
fi

# lupdate fails if the file passed as "-ts" argument already exists, so create a
# temp dir where it can safely create a tmp.ts file.
ts_dir=$(mktemp --directory --tmpdir ts-XXXXXX)
trap "rm -rf $ts_dir" 0
trap "exit 2" 1 2 3 13 15
tmp_ts=$ts_dir/tmp.ts

$LUPDATE -silent $src_files -ts $tmp_ts
$LCONVERT $tmp_ts --sort-contexts --output-format pot -o $pot_file
