#!/bin/bash
set -euo pipefail

RED='\033[0;31m'
NC='\033[0m' # No Color
UNMOUNT_SUCCESS=" ---------------------------------------------\n
It is now safe to unplug the removable drive\n
--------------------------------------------"

unmount_drive_on_host() {
        host=$1
        label_command="label=\$(ssh $host 'ls /dev/disk/by-label/' | grep -E -m 1 -o -e zooxusb-[[:digit:]]+)"
        # If we can't find a drive, then exit
        if ! eval $label_command; then
                return 0
        fi
        echo "Attempting to unmount $label"
        unmount_command="sudo eject /dev/disk/by-label/$label"
        clear_mount_command="sudo rmdir /media/zoox/$label"
        if ssh $host $unmount_command; then
                ssh $host $clear_mount_command
                echo -e "Successfully unmounted $label on $host"
        else
                echo -e " ---------------------------------------------
                        \n${RED} Failed to unmount $label on $host. Do not pull drive ${NC}
                        \nPlease make sure logger has completely shut down, then wait 30s and try again
                        \n---------------------------------------------"
                exit 1
        fi
}

# initctl stop will have a nonzero return code if it's already stopped
# We don't want to bail out in this case.
# If it's actually still running, unmounting the drive will fail and alert the user
set +e
remote_command sudo initctl stop zlog
set -e

if ssh main-ai true; then
        unmount_drive_on_host main-ai
fi

if ssh vision1 true; then
        unmount_drive_on_host vision1
fi

echo -e $UNMOUNT_SUCCESS
