#!/bin/sh
set -eu

retry() {
    attempt=1
    while ! "$@"; do
        if [ "$attempt" -ge "$SOURCE_FETCH_RETRY_ATTEMPTS" ]; then
            return 1
        fi
        sleep "$SOURCE_FETCH_RETRY_DELAY_SECONDS"
        attempt=$((attempt + 1))
    done
}

mkdir -p "$(dirname "$VOICE_SOURCE_DIR")"
if [ ! -d "$VOICE_SOURCE_DIR/.git" ]; then
    rm -rf "$VOICE_SOURCE_DIR"
    mkdir -p "$VOICE_SOURCE_DIR"
    git -C "$VOICE_SOURCE_DIR" init
    git -C "$VOICE_SOURCE_DIR" remote add origin "$SOURCE_REPOSITORY"
fi

test "$(git -C "$VOICE_SOURCE_DIR" remote get-url origin)" = "$SOURCE_REPOSITORY"
if ! git -C "$VOICE_SOURCE_DIR" cat-file -e "$SOURCE_REF^{commit}" 2>/dev/null; then
    retry git -C "$VOICE_SOURCE_DIR" fetch --depth 1 origin "$SOURCE_REF"
fi
git -C "$VOICE_SOURCE_DIR" checkout --detach "$SOURCE_REF"
test "$(git -C "$VOICE_SOURCE_DIR" rev-parse HEAD)" = "$SOURCE_REF"

if [ "$SOURCE_SUBMODULES" = recursive ]; then
    if ! git -C "$VOICE_SOURCE_DIR" submodule status --recursive >/dev/null 2>&1 \
        || git -C "$VOICE_SOURCE_DIR" submodule status --recursive | grep -q '^[+-U]'; then
        retry git -C "$VOICE_SOURCE_DIR" submodule update --init --recursive --depth 1
    fi
    ! git -C "$VOICE_SOURCE_DIR" submodule status --recursive | grep -q '^[+-U]'
fi

printf '%s  %s\n' "$REFERENCE_WAV_SHA256" "$VOICE_SOURCE_DIR/$REFERENCE_WAV_PATH" | sha256sum -c -
