#!/bin/sh
. /usr/share/libubox/jshn.sh
# ACTION="add" SUBSYSTEM="block" DEVTYPE="partition" DEVICENAME="sda1" DEVNAME="sda1"
# logger -t "hotplug" -p local3.notice "$ACTION" "$SUBSYSTEM" "$DEVTYPE" "$DEVICENAME" "$DEVNAME"
[ "$SUBSYSTEM" = block ] || exit 0


[ "$DEVTYPE" = partition -a "$ACTION" = add ] && {
    echo "$DEVICENAME" | grep 'sd[a-z][1-9]' || exit 0
    test -d /mnt/$DEVICENAME || mkdir /mnt/$DEVICENAME
    mount -o iocharset=utf8,rw /dev/$DEVICENAME /mnt/$DEVICENAME || logger -t "hotplug" -p local3.notice "$DEVICENAME"
    mosquitto_pub -t 'ipc/system/notification/hostplug' -m '{"title":"information","message":"Found U disk inserted!"}'
    ROOTDIR="/mnt/$DEVICENAME"

    test -n "$(ls $ROOTDIR/bin/)" || test -n "$(ls $ROOTDIR/bin/script/)" || test -n "$(ls $ROOTDIR/bin/translations/)" || test -n "$(ls $ROOTDIR/bin/config/)" || test -n "$(ls $ROOTDIR/firmware/)" || exit 0
    if [ -n "$(ls $ROOTDIR/firmware/)" ]
    then
        json_init
        json_add_string "title" "information"
        json_add_string "message" "Found firmware for device!"
        json_add_array  "param"
        for file in `ls $ROOTDIR/firmware/*`
        do
        json_add_string "" "$file"
        done
        json_close_array
        json_str=`json_dump`
        mosquitto_pub -t 'ipc/system/notification/firmware' -m "${json_str}"
    else
        mosquitto_pub -t 'ipc/system/requestion/update_config' -m "{\"title\":\"$ROOTDIR\",\"message\":\"Detected if the configuration file is updated now?\"}"
    fi
}

[ "$DEVTYPE" = partition -a "$ACTION" = remove ] && {
    echo "$DEVICENAME" | grep 'sd[a-z][1-9]' || exit 0
    umount /mnt/$DEVICENAME && rmdir /mnt/$DEVICENAME
    mosquitto_pub -t 'ipc/system/notification/hostplug' -m '{"title":"information","message":"U disk is unplugged!"}'
}


