#!/bin/bash

. /etc/profile >/dev/null
# . /etc/tos/scripts/scripts

STORAGE_DEVICE_TOOL_SOCK="/var/api/storage_device_tool.sock"
i=0
while [ ! -e "$STORAGE_DEVICE_TOOL_SOCK" ]; do
    sleep 3
    i=$(("$i"+1))
    if [ $i -eq 9 ]; then
        echo "ter_storage_device_tool have not started"
        exit 10
    fi
done
action=$1
blk=/dev/$2
if [ "$action" = "remove" ]; then
    mkdir "/run/diskCache" >/dev/null 2>&1
    cp /run/cache/diskinfo/$2 /run/diskCache/$2 >/dev/null
fi
if [ "$action" = "insert" ]; then
    boot=$(blkid | grep UTOSBOOT | cut -d: -f1)
    if [ -n "$boot" ]; then
        out=$(echo "$boot" | grep $2)
        if [ ! -z "$out" ]; then
            echo 0 >/sys/block/$2/device/delete
            rm /dev/disk/by-label/UTOSBOOT
            echo "USB device ($out) with label UTOSBOOT done remove." | tee -a /tmp/umount_BOOTUSB.log
            exit 0
        fi
    fi
    ter_curl -v -X PUT --unix-socket $STORAGE_DEVICE_TOOL_SOCK http://storage_device_tool.sock/v1/$2
    systemctl start disk-event-logger-insert@$blk.service &
elif [ "$action" = "remove" -o "$action" = "saferemove" -o "$action" = "delete" ]; then
    ter_curl -v -X DELETE --unix-socket $STORAGE_DEVICE_TOOL_SOCK http://storage_device_tool.sock/v1/$2/1
    systemctl start disk-event-logger-remove@$blk.service &
fi

# while [ 1 ]; do
#     script_get_lock >/dev/null
#     [ $? -eq 0 ] && break
# done
#
# action=$1
# if [ "$action" = "insert" ]; then
#     usb_init_position $2
# elif [ "$action" = "remove" -o "$action" = "saferemove" -o "$action" = "delete" ]; then
#     usb_disk_remove $2
# fi
# (/etc/udev/scripts/usb_disk_auto $@ >/dev/null &)
#
# sleep 2
# script_put_lock
# exit 0
