#!/bin/bash
# Runs from a UDEV rule that checks when a zoox drive is inserted/removed,
# mounts/unmounts the disk and registers the disk as inserted in the data catalog

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

readonly mount_point="/media/"

main() {
    local action; action="$1"; shift;
    local fs_label; fs_label="$1"; shift;
    local devname; devname="$1"; shift;

    case "$action" in
        add)
            source_zoox_setup
            create_mount $fs_label $devname
            refresh_disks
            ;;

        remove)
            delete_mount $fs_label
            ;;
        *)
    esac
}

# Checks for disks that have been inserted/ejected
refresh_disks() {
    timeout 10s ${ZOOX_WORKSPACE_ROOT}/bazel-bin/data/vehicle_data_sync/refresh_disks
}

create_mount() {
    local label; label="$1"; shift;
    local devname; devname="$1"; shift;
    if [[ ! -d "$mount_point/$label" ]]; then
        mkdir --parents "$mount_point/$label"
        chown zoox:zoox "$mount_point/$label"
    fi
    (mount $devname "$mount_point/$label")
}

delete_mount() {
    local label; label="$1"; shift;
    if mountpoint -q "$mount_point/$label"; then
      (umount -f "$mount_point/$label")
    fi
    if [[ -d "$mount_point/$label" ]]; then
        rmdir "$mount_point/$label"
    fi
}

# 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="/home/zoox/driving"
    fi
}

main $*
