#!/usr/bin/env bash
#
#bamboo remote agent imaging ci sync script

echo "$0 $@"
set -euxo pipefail

[[ $EUID == 0 ]] && echo "Don't run this as sudo/root" && exit 1

#set default value of parameters
bamboo_root="$HOME/bamboo"
git_hash="$bamboo_planRepository_1_revision"
zimbot_name="$bamboo_robot_name"
calibration_branch="$bamboo_calibration_branch"
compute_version="$bamboo_compute_version"
limit_hosts_imaging="$bamboo_limit_hosts_imaging"

checksum_file_remote="s3://imaging/ci/checksums/$git_hash"
checksum_file_local="/tmp/$git_hash"

if ! aws s3 ls "$checksum_file_remote" ; then
    echo "Could not find checksum file for git SHA $git_hash at $checksum_file_remote. Exiting..."
    exit 1
fi

echo "Downloading checksum file..."
aws s3 cp "$checksum_file_remote" "$checksum_file_local"
echo "Checksum file content:"
cat "$checksum_file_local"
echo ""

function read_checksum() {
    jq --raw-output '.imaging_source_checksum' "$1"
}

checksum="$(read_checksum $checksum_file_local)"
echo "Read imaging checksum: $checksum"

ci_status_file_remote="s3://imaging/ci/status/$checksum"
ci_status_file_local="/tmp/$checksum"
status_prefix="Imaging CI status"

#Imaging CI status line template: Imaging CI status: {'pending' | 'succeeded' | 'failed error #'}
function should_skip_imaging_ci() {
    [[ "$1" == "$status_prefix"* ]] && [[ "$1" == *"succeeded"* ]] && return 0
    return 1
}

function read_ci_status() {
    # return empty status when file not exists
    if ! aws s3 ls "$ci_status_file_remote" ; then
        echo "" && return 0
    fi
    aws s3 cp "$ci_status_file_remote" "$ci_status_file_local"
    local lines
    readarray lines < "$ci_status_file_local"
    echo ${lines[1]//[$'\r\n']}
}

function write_ci_status() {
    printf "$git_hash\n$status_prefix: $1\n" | sudo tee $ci_status_file_local
    aws s3 cp "$ci_status_file_local" "$ci_status_file_remote"
}

ci_status="$(read_ci_status)"
should_skip_imaging_ci "$ci_status" && echo "Imaging CI skipped, checksum $checksum already passed" && exit 0

cd "$bamboo_root/driving"
if ! git checkout "$git_hash" ; then
    git fetch --all
    git checkout "$git_hash"
fi

#set ci status to pending before imaging
write_ci_status "pending"
# copy checksum file into place
sudo cp $checksum_file_local $HOME/imaging/assets/imaging_source_checksums.json
$(dirname "$(readlink -f "$0")")/zimage_ci_run.sh "$git_hash" "$zimbot_name" "$calibration_branch" "$limit_hosts_imaging" && write_ci_status "succeeded" && exit 0
ret_code=$?
write_ci_status "failed error $ret_code"
exit $ret_code
