#!/bin/bash
# Run the vehicle_data_sync/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_sync"

    timeout 10m /opt/zoox/ingest/zoox/data/vehicle_data_sync/vehicle_data_sync_kiosk_properties

    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 $#

    timeout 12h /opt/zoox/ingest/zoox/bin/vehicle_data_sync_push_main
}

# 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 "$(hostname) - vehicle_data_sync failed with status ${rc}" ingest-kiosk-alerts@zoox.com
    fi
    local lock_file="$1"; shift
    rm --force ${lock_file}
}

# Checks for disks that have been inserted/ejected
refresh_disks() {
    timeout 1m /opt/zoox/ingest/zoox/data/vehicle_data_sync/vehicle_data_sync_refresh_disks
}

# 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}") 2>/dev/null) ; then
        echo "$(date +'%Y-%m-%d %H:%M:%S%z'):INFO:vehicle_data_sync:${lock_file} exists; another instance is running."
        refresh_disks
        exit 0
    fi
    trap "trap_function $lock_file" EXIT
}

# Emit a heartbeat
emit_heartbeat() {
    local canary="$1"; shift

    # Leaving this line for when we move to more structured logging
    # echo '{"event":"Heartbeat", "time":"'$(date --utc --iso-8601=ns)'", "process":"'"${canary}"'"}'

    echo $(date +'%Y-%m-%d %H:%M:%S%z'):INFO:${canary}:Heartbeat
}

main $*
