#!/bin/bash
# Run the vehicle_data_sync/persist_main target from CRON.  Provides a local
# locking mechanism (via /var/lock) to prevent multiple simultaneous
# instances.
#
# Usage: run_vehicle_data_sync_script [<script_arg> [...]]"

set -euo pipefail
IFS=$'\n\t'

main() {

    emit_heartbeat "vehicle_data_persist"

    set_lockfile_exit_trap "/var/lock/vehicle_data_sync"

    # Fix a weird problem with arguments transferring to ROS's setup.bash in certain cases
    arguments=$*; shift $#

    source_zoox_setup

    timeout 12h ${ZOOX_WORKSPACE_ROOT}/bazel-bin/data/vehicle_data_sync/persist_main ${arguments}
}

# Trap function for the lockfile exit trap
trap_function() {
    rc=$?
    if [[ $rc != 0 ]]; then
        tail -n 50 /var/log/zooxops/sync_driving_data | mailx -r ingest-alerts@zooxlabs.com -s "vehicle_data_persist failed with status ${rc}" ingest-kiosk-alerts@zoox.com
    fi
    local lock_file="$1"; shift
    rm --force ${lock_file}
}

# Sets a lockfile exit trap.
set_lockfile_exit_trap() {
    local lock_file="$1"; shift
    # Attempt to write the lock file by setting 'noclobber' then trying to
    # write the file (or overwrite if it is there).  If this fails, exit.
    # Otherwise
    if ! (set -o noclobber; : > "${lock_file}") ; then
        echo "$(date --utc): ${lock_file} exists; another instance is running."
        exit 0
    fi
    trap "trap_function $lock_file" EXIT
}

# Emit a heartbeat
emit_heartbeat() {
    local canary="$1"; shift
    echo '{"event":"Heartbeat", "time":"'$(date --utc --iso-8601=ns)'", "process":"'"${canary}"'"}'
}

# Sources zooxrc
source_zoox_setup() {
    local this_dir=$(dirname $(readlink --canonicalize --no-newline "${BASH_SOURCE}"))
    # It would be nice if we had the full zoox environment, but during
    # unit testing from bazel, we don't have $HOME, which breaks
    # zooxrc.sh severely.  We actually only need ZOOX_WORKSPACE_ROOT
    if [ -v HOME ] ; then
        source "${this_dir}/../../scripts/shell/zooxrc.sh"
    else
        export ZOOX_WORKSPACE_ROOT="${this_dir}/../.."
    fi
}

main $*
