#!/bin/sh /etc/rc.common
#
# Mount usb storage for tiny system ....
# ./target/linux/rtd1295/base-files/etc/
START=30
#logger -t TGM-DEBUG "MOUNT USB................./etc/init.d/mountusb"
source /etc/tos/scripts/scripts
TOS_BOOT_DEV=""
TOS_BOOT_USB=/mnt/bootdev
TOS_BOOT_DIR="/tmp/TOS_BOOT_DEV"
[ ! -d $TOS_BOOT_DIR ] && mkdir $TOS_BOOT_DIR

get_boot_dev(){
    for blk in /dev/sd[a-z]; do
        if [ -b $blk'1' ]; then
            local label=`e2label $blk'1'`
            if [ "$label" = "$TOS_BOOT_SIGN" ]; then
                TOS_BOOT_DEV=$blk
                return 0
            fi
        fi
    done
    return 1
}

get_usb_slot(){
	local blk=$1
	local name=$(basename "$blk")
	local link=$(readlink -f /sys/block/$name)
	[ -z "$link" ] && return 1
	local keyslot=`echo $link | cut -d '/' -f10`
    local bootusb="$TOS_BOOT_DIR/$keyslot"
    [ ! -f "$bootusb" ] && touch "$bootusb"
	return 0
}

unpkg(){
    local pkg=$1
    if [ -f $pkg ]; then
        tar -xf $pkg -C /
        /etc/init.d/dbus start
        /etc/init.d/avahi-daemon start
        /usr/sbin/syscontrol > /dev/null &
        /etc/init.d/nginx start
        /etc/init.d/php7-fpm start
        tosconf
    fi
}

start() {
    echo "mount usb storage..."
    local isContinue=0
    get_boot_dev
    if [ ! -z "$TOS_BOOT_DEV" ]; then
        get_usb_slot ${TOS_BOOT_DEV}
        [ ! -d $TOS_BOOT_USB ] && mkdir $TOS_BOOT_USB
        df | grep ${TOS_BOOT_DEV} >/dev/null
        if [ $? -ne 0 ]; then
            isContinue=1
            mount -t ext4 ${TOS_BOOT_DEV}1 $TOS_BOOT_USB
        fi
    fi
    # main rootfs ?
    label=`df-json | awk '/\/$/ {print $1}'`
    # not in minos or not the first call
    if [ "$label" != "rootfs" -o $isContinue -eq 0 ]; then
        exit 1
    fi
    if [ -f "$TOS_BOOT_USB/php7-all.tar" ]; then
	    unpkg $TOS_BOOT_USB/php7-all.tar
    else
	    /etc/tos/scripts/wget_from_online >/dev/null &
    fi
    exit 0
}

stop(){
    umount $TOS_BOOT_USB
    get_boot_dev
    if [ ! -z "$TOS_BOOT_DEV" ]; then
        echo "umount usb storage..."
        get_usb_slot ${TOS_BOOT_DEV}
        echo 0 > /sys/block/`basename ${TOS_BOOT_DEV}`/device/delete
		exit 0
	fi
    echo "tos boot usb storage not found..."
	exit 1
}




