#!/bin/sh

runtime_name="${0##*/}"
archive="${VOIP8_RUNTIME_ARCHIVE:-/usr/share/voip8-proxy/runtime/${runtime_name}.gz}"
archive_id_file="${VOIP8_RUNTIME_ARCHIVE_ID:-/usr/share/voip8-proxy/runtime/${runtime_name}.id}"
runtime="${VOIP8_RUNTIME_PATH:-/tmp/voip8-proxy/runtime/${runtime_name}}"
stamp="${runtime}.id"
lock="${runtime}.lock"

fail() {
    echo "${runtime_name} runtime: $*" >&2
    exit 1
}

[ -r "$archive" ] || fail "archive not found: $archive"
[ -r "$archive_id_file" ] || fail "archive id not found: $archive_id_file"

expected_id="$(cat "$archive_id_file" 2>/dev/null)"
[ -n "$expected_id" ] || fail "archive id is empty"

runtime_ready() {
    [ -x "$runtime" ] && [ "$(cat "$stamp" 2>/dev/null)" = "$expected_id" ]
}

if ! runtime_ready; then
    runtime_dir="${runtime%/*}"
    [ "$runtime_dir" != "$runtime" ] || runtime_dir="."
    mkdir -p "$runtime_dir" || fail "cannot create runtime directory: $runtime_dir"

    lock_acquired=0
    attempts=0
    while [ "$attempts" -lt 30 ]; do
        if mkdir "$lock" 2>/dev/null; then
            lock_acquired=1
            break
        fi
        runtime_ready && break
        attempts=$((attempts + 1))
        sleep 1
    done

    # Recover an empty lock left by an interrupted extraction.
    if [ "$lock_acquired" -eq 0 ] && ! runtime_ready; then
        rmdir "$lock" 2>/dev/null
        if mkdir "$lock" 2>/dev/null; then
            lock_acquired=1
        fi
    fi

    if [ "$lock_acquired" -eq 1 ]; then
        tmp="${runtime}.tmp.$$"
        stamp_tmp="${stamp}.tmp.$$"
        trap 'rm -f "$tmp" "$stamp_tmp"; rmdir "$lock" 2>/dev/null' EXIT INT TERM
        if ! runtime_ready; then
            gzip -dc "$archive" > "$tmp" || fail "cannot extract archive"
            chmod 0755 "$tmp" || fail "cannot make runtime executable"
            mv -f "$tmp" "$runtime" || fail "cannot install runtime"
            printf '%s\n' "$expected_id" > "$stamp_tmp" || fail "cannot write runtime id"
            mv -f "$stamp_tmp" "$stamp" || fail "cannot install runtime id"
        fi
        rmdir "$lock" 2>/dev/null
        trap - EXIT INT TERM
    fi

    runtime_ready || fail "runtime preparation timed out"
fi

exec "$runtime" "$@"
