#!/usr/bin/env bash
set -euo pipefail

pwd

#defaults
lm=0
num_cameras=2
duration=90
timeout=999
stage="ahmo_production"

usage() {
            echo "Usage:"
            echo "      -m          Activate link margin test"
            echo "      -c=?        Specify number of cameras"
            echo "      -d=?        Specify test duration"
            echo "      -t=?        Specify test error timeout"
            echo "      -s=?        Test stage"
            echo "      -h          display help"
            exit
        }
while getopts "hmc:d:t:" o; do
    case "${o}" in
        m)
            lm=1
            ;;
        c)
            num_cameras=${OPTARG}
            ;;
        d)
            duration=${OPTARG}
            ;;
        t)
            timeout=${OPTARG}
            ;;
        s)
            stage=${OPTARG}
            ;;
        h)
            usage
            ;;
  esac
done

echo "lm:$lm num_cameras: $num_cameras timeout:$timeout"

mkdir -p /media/zoox/zooxdata0

echo "Scan FG:"
part_num=''
serial_num=''
IFS=':' read -ra array
part_num=${array[0]}
serial_num=${array[1]}
echo "Part: $part_num"
echo "Serial: $serial_num"

echo "Scan Operator ID:"
IFS= read -r op_id

echo "Scan Harness ID:"
IFS= read -r ha_id

results_dir=results_`echo $serial_num`_`date +"%s"`
chum_dir="/media/zoox/zooxdata0/vehicle-chum"

rm -rf /media/zoox/zooxdata0/*
mkdir -p $chum_dir
production/cameras/framegrabber_bringup/cammux_jig/cammux_runner --timeout=$timeout --duration=$duration --num_cameras=$num_cameras | tee $chum_dir/cammux_stdout

production/cameras/framegrabber_bringup/link_margin_test | tee $chum_dir/link_margin_stdout

echo $serial_num > $chum_dir/framegrabber_serial
echo $part_num > $chum_dir/framegrabber_part
echo $op_id  > $chum_dir/operator_id
echo $ha_id  > $chum_dir/harness_id

production/cameras/framegrabber_bringup/cammux_jig/local_camera_diagnostics --path=$chum_dir --upload=true --stage=$stage | tee $chum_dir/diagnostics_stdout


vehicle/sensors/cameras/framegrabber/update_factory_data --serial $serial_num --part $part_num
vehicle/sensors/cameras/framegrabber/update_factory_data

echo "Part: $part_num"
echo "Serial: $serial_num"

mkdir -p /media/zoox/zooxdata
cp -R $chum_dir/../* /media/zoox/zooxdata
data/vehicle_data_sync/push_main
