#!/usr/bin/env bash
#
# Bisect parsing a file at various line cut-off points to see which line causes the parse to differ from emacs.
set -euo pipefail
IFS=$'\n\t'
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

REALPATH=$(command -v uu-realpath || command -v realpath)

############## Setup #########################

function die {
    local status_code="$1"
    shift
    (>&2 echo "${@}")
    exit "$status_code"
}

function log {
    (>&2 echo "${@}")
}

############## Program #########################

function main {
    local target_full_path
    target_full_path=$($REALPATH "$1")
    SOURCE_FOLDER=$(dirname "$target_full_path")
    TARGET_DOCUMENT=$(basename "$target_full_path")


    local good=0
    local bad
    bad=$(wc -l "$SOURCE_FOLDER/$TARGET_DOCUMENT" | awk '{print $1}')

    set +e
    (run_parse "$bad")
    local status=$?
    set -e
    if [ $status -eq 0 ]; then
        log "Entire file passes."
        exit 0
    fi

    while [[ "$((bad - good))" -gt 1 ]]; do
        local next_line=$((((bad - good) / 2) + good))
        log "Testing line $next_line"
        set +e
        run_parse "$next_line" &> /dev/null
        local status=$?
        set -e
        if [ $status -eq 0 ]; then
            good="$next_line"
            log "Line $next_line good"
        else
            bad="$next_line"
            log "Line $next_line bad"
        fi
    done
    echo "Bad line: $bad"
}

function run_parse {
    local lines="$1"

    cd "$SOURCE_FOLDER"
    head -n "$lines" "$SOURCE_FOLDER/$TARGET_DOCUMENT" | PROFILE=release-lto "${DIR}/run_docker_compare.bash"
    local status=$?
    return "$status"
}

main "${@}"