#!/bin/sh

KEY="/home/shinya/.ssh/malnus"
SRC="../chip_test_example"
DST="/home/me/"

deploy_and_build() {
    HOST=$1

    TOTAL_START=$(date +%s)

    echo "[$HOST] Copying..."
    SCP_START=$(date +%s)

    scp -i "$KEY" -r "$SRC" me@$HOST:$DST || return 1

    SCP_END=$(date +%s)
    SCP_TIME=$((SCP_END - SCP_START))

    echo "[$HOST] Copy completed in ${SCP_TIME}s"

    echo "[$HOST] Building..."
    BUILD_START=$(date +%s)

    ssh -i "$KEY" me@$HOST \
        "cd $DST/chip_test_example && make -j4"

    BUILD_STATUS=$?

    BUILD_END=$(date +%s)
    BUILD_TIME=$((BUILD_END - BUILD_START))

    TOTAL_END=$(date +%s)
    TOTAL_TIME=$((TOTAL_END - TOTAL_START))

    echo "[$HOST] Build completed in ${BUILD_TIME}s"
    echo "[$HOST] Total time: ${TOTAL_TIME}s"

    return $BUILD_STATUS
}

deploy_and_build 10.91.51.165 &
PID1=$!

deploy_and_build 10.91.51.166 &
PID2=$!

wait $PID1
STATUS1=$?

wait $PID2
STATUS2=$?

echo "----------------------------------------"
echo "10.91.51.165 status: $STATUS1"
echo "10.91.51.166 status: $STATUS2"

if [ $STATUS1 -ne 0 ] || [ $STATUS2 -ne 0 ]; then
    echo "One or more builds failed"
    exit 1
fi

echo "All builds completed successfully"
