#!/bin/bash

BUILD_LOG=build.log

ARGUMENTS="clean verify -B -T 1.5C -U"
if [ $# -ge 1 ]; then
    ARGUMENTS=$@
fi

function print_reactor_summary() {
    local start_end=$(grep -anE "\[INFO\] \\-{70,}" "$BUILD_LOG" | tail -n4 | cut -f1 -d: | sed -e 1b -e '$!d' | xargs)
    local start=$(awk '{print $1}' <<< $start_end)
    local end=$(awk '{print $2}' <<< $start_end)
    cat "$BUILD_LOG" | sed -n "${start},${end}p" | sed 's/\[INFO\] //'
}

function mvnp() {
    set -o pipefail # exit build with error when pipes fail
    local reactor_size=$(find -name "pom.xml" | grep -vE '/src/|/target/' | wc -l)
    local padding=$(bc -l <<< "scale=0;2*(l($reactor_size)/l(10)+1)")
    local command=(mvn $@)
    exec "${command[@]}" 2>&1 | # execute, redirect stderr to stdout
        tee "$BUILD_LOG" | # write output to log
        stdbuf -oL grep -aE '^\[INFO\] Building .+ \[.+\]$' | # filter progress
        stdbuf -o0 sed -uE 's/^\[INFO\] Building (.*[^ ])[ ]+\[([0-9]+\/[0-9]+)\]$/\2| \1/' | # prefix project name with progress
        stdbuf -o0 sed -e :a -e "s/^.\{1,${padding}\}|/ &/;ta" # right align progress with padding
}

function build_all() {
    echo
    echo "Building all projects"
    echo
    echo "+ mvn $ARGUMENTS"
    echo

    mvnp $ARGUMENTS

    status=$?
    echo

    if [ $status -eq 0 ]; then
        print_reactor_summary
    else
        tail -n 2000 "$BUILD_LOG"
    fi

    exit $status
}

function changed_files() {
    sed 's#,#\n#g' <<< $CHANGED_FILES
}

function addon_unrelated_changed_files() {
    local addon="$1"
    changed_files | \
        grep -Ev "^(bundles/|itests/)$addon([/.].*)?$" | \
        grep -Ev "^(CODEOWNERS|bom/openhab-addons/pom.xml|bundles/pom.xml|itests/pom.xml)$"
}

function changed_addons() {
    changed_files | grep -E '(bundles/|itests/)org\.openhab\.' | sed -E 's#.+/(org\.openhab\.[a-z0-9]+\.[a-z0-9]+).*#\1#g' | sort -u
}

function addon_projects() {
    local addon="$1"

    # include add-on projects
    local projects=":$(find . -mindepth 2 -maxdepth 2 -type d -regextype egrep -regex "./(bundles|itests)/$addon(\..*)?$" | sort | sed -E 's#./(bundles|itests)/##g' | xargs | sed 's# #,:#g')"

    # include BOMs
    projects="$projects,:org.openhab.addons.bom.openhab-core-index,:org.openhab.addons.bom.runtime-index,:org.openhab.addons.bom.test-index"

    # exclude features
    projects="$projects,-:org.openhab.addons.reactor.features.karaf,-:org.openhab.addons.features.karaf.openhab-addons,-:org.openhab.addons.features.karaf.openhab-addons-external"

    echo $projects
}

function build_addon() {
    local addon="$1"
    local mvn_command="mvn $ARGUMENTS -am -amd -pl $(addon_projects $addon)"

    echo
    echo "Building add-on: $addon"
    echo
    echo "+ $mvn_command"
    echo

    set -o pipefail # exit build with error when pipes fail
    $mvn_command 2>&1 | tee "$BUILD_LOG"
    exit $?
}

function build_based_on_changes() {
    local changed_addon=$(changed_addons | xargs)
    if [ $(echo $changed_addon | wc -w) -eq 1 ] && \
        [ $(addon_unrelated_changed_files $changed_addon | wc -l) -eq 0 ] && \
        [ -d "./bundles/$changed_addon" ]
    then
        build_addon $changed_addon
    else
        build_all
    fi
}

mvn -v
build_based_on_changes