#!/bin/sh /etc/rc.common
# Copyright (C) 2006 OpenWrt.org

START=09
clean_mount()
{
    logger -t mmcstorage -p debug "clean_mount"
    if [ -f "/etc/extfilesystem/mountpoint" ]; then
        cat /etc/extfilesystem/mountpoint | while read line 
        do
            logger -t mmcstorage -p debug "clean_mount: $line"
            for word in $line
            do
                res=`cat /etc/config/mmcstorage | grep -w $word`
                if [ -z "$res" ]; then
                    logger -t mmcstorage -p debug "clean_mount: check $word"
                    location=`cat /proc/mounts | grep -w "$word" | awk '{print$2}'`
                    echo "$(grep -v  "$word" /etc/extfilesystem/mount_status)" > /etc/extfilesystem/mount_status
                    umount "$location" >/tmp/mmcerror 2>&1  
                    echo "`date`: Successfully unmounted $word" >> /etc/extfilesystem/mount_status
                    /usr/bin/logger -t mmcstorage -p info  "Successfully unmount $word"
                    [ -d "$location" ] && rmdir  "$location"
                    echo "$(grep -v "$word" /etc/extfilesystem/mountpoint)" > /etc/extfilesystem/mountpoint
                else
                    logger -t mmcstorage -p debug "clean_mount: $word is configured"
                fi
            done
        done
    fi
}

MOUNTED=""
UNMOUNTED=""
syslog_base_path=""

unmount_storage()
{
    cfg="$1"
    local dev=$(uci_get mmcstorage "$cfg" device)
    local enable=$(uci_get mmcstorage "$cfg" enable)
    local mountpoint=$(uci_get mmcstorage "$cfg" mount)
    local options=$(uci_get mmcstorage "$cfg" options)
    oldoptions=$(uci_get mmcstorage "$cfg" oldoptions) 2> /dev/null
    [ -z $oldoptions ] && oldoptions=""

    logger -t mmcstorage -p debug "unmount_storage: $dev $mountpoint"
    if [ -z $dev ]; then
        logger -t mmcstorage -p warning "unmount_storage: no dev:$dev , return"
        return 0
    fi

    proc_rsp=`cat /proc/mounts | grep -w "$dev" | awk '{print$1}'`
    mountedat=`cat /proc/mounts | grep -w "$dev" | awk '{print$2}'`
    if [ "$UNMOUNTED" != "" -a "`echo $UNMOUNTED | grep $dev`" == "$UNMOUNTED" ]; then
        /usr/bin/logger -t mmcstorage -p debug  "unmount_storage: $UNMOUNTED duplicate $dev $mountpoint"
        return 0
    fi
    if [ -n "$HOTPLUGDEVICENAME" ]; then
        rmdevname=`echo $dev | grep  $HOTPLUGDEVICENAME`
    fi

    if [ "$enable" = 0 ]; then
        if [ -n "$proc_rsp" ]; then
            echo "$(grep -v -E "$dev|$mountpoint" /etc/extfilesystem/mount_status)" > /etc/extfilesystem/mount_status
            umount "$mountpoint" >/tmp/mmcerror 2>&1
            if [ "$?" == "0" ]; then
                echo "`date`: Successfully unmounted $dev from $mountedat" >> /etc/extfilesystem/mount_status
                /usr/bin/logger -t mmcstorage -p info  "Successfully unmount $dev" 
                [ -d "$mountpoint" ] && rmdir  "$mountpoint"
            else
                err_rsp=`cat /tmp/mmcerror | awk 'NR==1 {print}'`
                echo "`date`: Failed to unmount $dev (Reason: $err_rsp)" >> /etc/extfilesystem/mount_status
                /usr/bin/logger -t mmcstorage -p info  "Failed to unmount $dev"
            fi
        fi
    else
        if [ -n "$proc_rsp" ]; then
            if [ "$mountedat" != "$mountpoint" -o  "$options" != "$oldoptions" -o -n "$rmdevname" ]; then
                echo "$(grep -v -E "$dev|$mountedat" /etc/extfilesystem/mount_status)" > /etc/extfilesystem/mount_status
                umount "$mountedat" >/tmp/mmcerror 2>&1
                if [ "$?" == "0" ]; then
                    echo "`date`: Successfully unmounted $dev from $mountedat" >> /etc/extfilesystem/mount_status
                    /usr/bin/logger -t mmcstorage -p info  "Successfully unmount $dev"
                    [ -d "$mountedat" ] && rmdir  "$mountedat"
                else
                    err_rsp=`cat /tmp/mmcerror | awk 'NR==1 {print}'`
                    echo "`date`: Failed to unmount $dev (Reason: $err_rsp)" >> /etc/extfilesystem/mount_status
                    /usr/bin/logger -t mmcstorage -p info  "Failed to unmount $dev"
                fi
            else
                UNMOUNTED="$UNMOUNTED,$dev"
                logger -t mmcstorage -p debug "unmount_storage: nothing changed $dev $mountpoint"
            fi
        fi
    fi
    logger -t mmcstorage -p debug "unmount_storage: {$UNMOUNTED}"
}

mount_storage()
{
    cfg="$1"
    dev=$(uci_get mmcstorage "$cfg" device)
    enable=$(uci_get mmcstorage "$cfg" enable)
    mountpoint=$(uci_get mmcstorage "$cfg" mount)
    options=$(uci_get mmcstorage "$cfg" options)
    
    logger -t mmcstorage -p debug "mount_storage: $dev $mountpoint"
    if [ -z $dev ]; then
        logger -t mmcstorage -p warning "mount_storage: no dev:$dev , return"
        #echo "`date`: Failed to mount $dev. No such device." >> /etc/extfilesystem/mount_status
        return 0
    fi
    if [ ! -b "$dev" ]; then
        logger -t mmcstorage -p warning "mount_storage: not a block device:$dev , return"
        echo "`date`: Failed to mount $dev. Invalid device type." >> /etc/extfilesystem/mount_status
        return 0
    fi
    proc_rsp=`cat /proc/mounts | grep -w "$dev" | awk '{print$1}'`
    if [ "$MOUNTED" != "" -a "`echo $MOUNTED | grep $dev`" == "$MOUNTED" ]; then
        /usr/bin/logger -t mmcstorage -p debug  "mount_storage: duplicate $dev $mountpoint"
        echo "`date`: $dev is already configured for use." >> /etc/extfilesystem/mount_status
        return 0
    fi
    if [ "$enable" = 1 ] ; then
        if [ -z "$proc_rsp" ]; then
            proc_rsp=`cat /proc/mounts | grep -w "$mountpoint" | awk '{print$2}'`
            if [ -n "$proc_rsp" ];then 
                if [ ! -d "$mountpoint" -o -n "$(ls -A $mountpoint)" ]; then 
                    echo "$(grep -v -E "$dev" /etc/extfilesystem/mount_status)" > /etc/extfilesystem/mount_status
                    echo "`date`: Failed to mount $dev. Directory $mountpoint is not empty." >> /etc/extfilesystem/mount_status
                    /usr/bin/logger -t mmcstorage -p info "$mountpoint this mount point is already in use, data might be lost."
                fi            
            else
                if [ -n "$(echo $syslog_base_path | grep  $mountpoint)" ]; then                          
                    logger -t mmcstorage -p warning "syslog path $syslog_base_path, mount $mountpoint"
                elif [ -d "$mountpoint" -a -n "$(ls -A $mountpoint)" ]; then
                    echo "$(grep -v -E "$dev" /etc/extfilesystem/mount_status)" > /etc/extfilesystem/mount_status
                    echo "`date`: Failed to mount $dev. Directory $mountpoint is not empty." >> /etc/extfilesystem/mount_status
                    /usr/bin/logger -t mmcstorage -p err "$mountpoint this mount point is already in use, data might be lost."
                    return 0
                fi
                mkdir -p "$mountpoint"
                [ ! -z $options ] && {
                    opt="-o $options"
                }

                echo "$(grep -v -E "$dev|$mountpoint" /etc/extfilesystem/mount_status)" > /etc/extfilesystem/mount_status
                mount $opt "$dev" "$mountpoint" >/tmp/mmcerror 2>&1
                if [ "$?" == "0" ] ; then
                    /usr/bin/logger -t mmcstorage -p info "Successfully mounted $dev"
                    echo "`date`: Successfully mounted $dev at $mountpoint" >> /etc/extfilesystem/mount_status
                    cat /etc/config/mmcstorage | awk '/device/ {print}' | awk '{print$3}' | sed "s/'//g" | tr ' ' '\n' >> /etc/extfilesystem/mountpoint
                    uci set mmcstorage."$cfg".oldoptions=$options
                    MOUNTED="$MOUNTED,$dev"
                else
                    err_rsp=`cat /tmp/mmcerror | awk 'NR==1 {print}'`
                    /usr/bin/logger -t mmcstorage -p info "Failed to mount $dev (Reason:$err_rsp)"
                    echo "`date`: Failed to mount $dev (Reason: $err_rsp)" >> /etc/extfilesystem/mount_status
                    [ -d "$mountpoint" ] && rmdir "$mountpoint"
                fi
            fi
        else
            MOUNTED="$MOUNTED,$dev"
            logger -t mmcstorage -p debug "mount_storage: nothing changed $dev $mountpoint"
        fi
    fi
    logger -t mmcstorage -p debug "mount_storage: {$MOUNTED}"
}

check_ok(){
    . /lib/functions.sh
    . /usr/share/libubox/jshn.sh
    json_init
    json_load_file /etc/hwinfo.json
    json_select hwdata
    json_get_var mmccard mmccard
    [ $mmccard -eq 1 ] || exit
}

boot(){
    local cfg
    mkdir -p /etc/extfilesystem
    touch /etc/extfilesystem/mount_status
    local unmountonly="$1"
    local bootflag=0

    #No parameters during the boot
    if [ $# -eq 0 ]; then
        bootflag=1
    fi

    check_ok

    logger -t mmcstorage -p debug "boot $unmountonly" 

    syslog_base_path=`uci get -q system.@system[0].log_file 2>/dev/null | tr -d '\n'`

    if [ "$bootflag" == 1 -o "$HOTPLUGACTION" == "remove" ]; then
        config_load mmcstorage
        config_foreach unmount_storage storage
    fi
    
    if [ "$bootflag" == 1 -o "$HOTPLUGACTION" == "bind" ]; then
        config_load mmcstorage
        config_foreach  mount_storage storage 
    fi

    #call clean mount function
    clean_mount

    if [ -f "/etc/extfilesystem/mount_status" -o -f "/etc/extfilesystem/mountpoint" ]; then
        sed -i '/\S/!d' /etc/extfilesystem/mount_status /etc/extfilesystem/mount_status
        sed -i '/\S/!d' /etc/extfilesystem/mountpoint /etc/extfilesystem/mountpoint
    fi
    # Flash from SD card
    if [ "$bootflag" == 1 ]; then
	/usr/sbin/fw_flash_from_storage.sh
    fi
}

start(){
    boot 0
}

stop(){
    boot 1
}

reload(){
   HOTPLUGACTION="remove" stop  
   HOTPLUGACTION="bind" start
}
