#!/usr/bin/env bash

set -euo pipefail

mapfile -t UNMOUNTEDDISKS < <(ls /dev/disk/by-label | grep zooxusb)

printf "\nSelect the usb drive to copy all runs on the vehicle to:\n"
select opt in "${UNMOUNTEDDISKS[@]}"; do
        printf "$opt\n"
        DISKNAME="$(udevadm info /dev/disk/by-label/$opt --query=name)"
        if  df | grep --quiet "$DISKNAME" ; then
                printf "Disk was found to be already mounted, continuing.\n"
        else
                printf "Disk was not found to be mounted, attempting to mount $DISKNAME\n"
                udisksctl mount --block-device /dev/"$DISKNAME"
                printf "Successfully mounted\n"
        fi
        MNT="$(findmnt /dev/$DISKNAME --noheadings --first-only --output TARGET)"
        printf "Starting copy to $opt /dev/$DISKNAME at $MNT\n"

        # This sudo needs to be removed when we properly setup mounting of zooxusb drives with ownership under zoox user
        time sudo rsync -a --remove-source-files --exclude "lost+found" --stats /media/zoox/zooxdata/ "$MNT"

        printf "\nFile transfer completed.\n"
        printf "\nUnmounting drive $opt /dev/$DISKNAME at $MNT\n"
        time udisksctl unmount --block-device /dev/"$DISKNAME"
        printf "Successfully unmounted, you may unplug the usb drive now.\n"
        exit
done
