#!/bin/bash
#
# flashcache	Init Script to manage cachedev loads
. /etc/tos/scripts/scripts

BACKEND_DISK=$2 #/dev/md0,/dev/vg0/lv0
Usage="Usage: $0 {start|stop|status|forcestop} {/dev/md0|/dev/vg0/lv0}\n"
if [ -z "$2" ]; then
    echo -e $Usage
    exit 1
fi

DMSETUP=`which dmsetup`
RETVAL=0

procflash(){
    local name=$1
    local FLAGS=$2
    echo $name | grep "-" >/dev/null
    [ $? -eq 0 ] && name=${name##*-}
    
    local FLASHCACHE_PATH=`ls -1d /proc/flashcache/* 2>/dev/null|egrep "sd[a-z]+[0-9]\+.*${name}"`
    FLASHCACHE_NAME=`basename "$FLASHCACHE_PATH"`
    [ -z "$FLASHCACHE_NAME" ] && return 1
    [ ! -z "$FLAGS" ] && sysctl -w dev.flashcache.${FLASHCACHE_NAME}.fast_remove=$FLAGS >/dev/null 2>&1
    echo $FLASHCACHE_NAME
    return 0
}

load_drive(){
    #Load the module
    local has_mod="`lsmod | grep flashcache`"
    if [ -z "${has_mod}" ]; then
        insmod /lib/modules/$TOS_KERNEL/kernel/flashcache.ko
        RETVAL=$?
        if [ $RETVAL -ne 0 ]; then
            mount_device "$BACKEND_DISK"
            echo "Module Load Error: flashcache. Exited with status - $RETVAL"
            exit $RETVAL
        fi
    fi
}

is_lvm(){
    local blk=$1
    local FS=`blkid -o export $blk | awk -F= '/TYPE/ {print $2}'`
    [ "$FS" = "LVM2_member" ] && return 1
    return 0
}

init_action_process(){
    local blk=$1
    echo "$blk" |egrep -q -E "^/dev/md[0-9]+"
    if [ $? -eq 0 ]; then
        is_lvm $blk
        if [ $? -eq 1 ]; then
            blk=`pvs -o lv_path $blk --noheadings 2>/dev/null|sed s/[[:space:]]//g`
            echo $blk
        fi
    fi
    echo $blk
}

service_all_stop(){
    sync
    # disabled service
    service all stop ssh_service nginx > /dev/null 2>&1
    df-json | awk '/\/mnt\/md[0-9]+$/ {print $8}' | while read line
    do
        local pids=$(fuser -m $line)
        [ ! -z "$pids" ] && kill -9 $pids > /dev/null 2>&1
    done
}

mount_device(){
    local device=$1
    local fs=`blkid -o export $device | awk -F= '/TYPE/ {print $2}'`
    if [ "$fs" = "LVM2_member" ]; then
        pvs -o lv_path $device --noheadings|sed s/[[:space:]]//g | while read line
        do
            mount_item_device $line
        done
    else
        mount_item_device $device
    fi
}

device_sortbyname(){
    local name=$1
    echo $name | grep "-" >/dev/null
    if [ $? -eq 0 ]; then
        echo ${name##*-lv}
    else
        echo ${name:2}
    fi
}

mount_item_device(){
    local device=$1
    [ ! -b "$device" ] && exit 1
    local fs=`blkid -o export $device | awk -F= '/TYPE/ {print $2}'`
    [ -z "$fs" ] && exit 1
    local MNTYPE="-t $fs"
    local blkname=`basename $device`
    local DEVSORT=`device_sortbyname $blkname`
    local MNTPATH=/mnt/md${DEVSORT}
    [ ! -d $MNTPATH ] && mkdir $MNTPATH
    
    if [ "$fs" = "btrfs" ]; then
        mount $MNTYPE -o $MNTOPT_BTRFS $device $MNTPATH
        df-json | grep "${MNTPATH}$" >/dev/null
        if [ $? -eq 0 ]; then
            btrfs filesystem resize max $MNTPATH >/dev/null 2>&1
        fi
    else
        mount $MNTYPE -o $MNTOPT_EXT4 $device $MNTPATH
    fi
    RETVAL=$?
    if [ $RETVAL -ne 0 ]; then
        echo "Mount Failed: $device to $MNTPATH"        
        return $RETVAL
    fi
    return 0
}

flashcache_remake(){
    local config=$1
    local device=$2
    local devsort=`device_sortbyname $(basename $device)`
    local CACHE_NAME=fc${devsort}
    local PTUUID=`awk -F= '/SSD_UUID/ {print $2}' $config`
    local PART_NAME=`awk -F= '/PART_NAME/ {print $2}' $config`
    local CACHESIZE=`awk -F= '/CACHESIZE/ {print $2}' $config`
    if [ -z "$PTUUID" -o -z "$PART_NAME" ]; then
        rm -f $config
        mount_device "$device"
    else
        local ssd=`get_device_name $PTUUID`
        local partition=${ssd}${PART_NAME}
        if [ -z "$ssd" -o ! -b $partition ]; then
            rm -f $config
            mount_device "$device"
        else
            echo -e "y\n" | flashcache_create -p around -b 4k -s $CACHESIZE  $CACHE_NAME  $partition  $device
            sleep 1
            if [ -b /dev/mapper/$CACHE_NAME ]; then
                mount_device "/dev/mapper/$CACHE_NAME"
            else
                mount_device "$device"
            fi
        fi
    fi
}

service_start() {
    #lvm reloading...
    vgscan
    vgchange -ay >/dev/null 2>&1    
    
    echo "Starting Flashcache..."
    load_drive
    #flashcache_load the cachedev for back mode
    flashcache_scan
    
    local devices=`init_action_process $1`
    local FLAG=1
    echo -e $devices | while read device
    do
        local blkname=`basename $device`
        local uuid=`blkid -o value -s UUID $device`
        local devsort=`device_sortbyname $blkname`
        local cachename=fc${devsort}
        if [ -b /dev/mapper/$cachename ]; then
            local SUBSYS_LOCK=/var/lock/subsys/$cachename
            local FLASHCACHE_NAME=`procflash $blkname $FLAG`
            mount_device "/dev/mapper/$cachename"
            touch $SUBSYS_LOCK
        elif [ -e $TOS_FLASHCACHE/$uuid ]; then
            flashcache_remake "$TOS_FLASHCACHE/$uuid" "$device"
        else
            mount_device "$device"
        fi
    done
}

service_stop() {
    local devices=`init_action_process $1`
    local FLAG=0
    #[ "$2" = '--force' ] && FLAG=1
    [ -z "$devices" ] && return 1
    service_all_stop
    
    echo -e $devices | while read device
    do
        local blkname=`basename $device`        
        local devsort=`device_sortbyname $blkname`
        local mntpath=/mnt/md${devsort}
        local cachename=fc${devsort}
        if [ -b /dev/mapper/$cachename ]; then
            local SUBSYS_LOCK=/var/lock/subsys/$cachename            
            umountAll $mntpath
            local FLASHCACHE_NAME=`procflash $blkname $FLAG`
            if [ ! -z "${FLASHCACHE_NAME}" ]; then
                echo "Flushing flashcache: Flushes to $BACKEND_DISK"
                $DMSETUP remove $cachename
                local cache_dev=${FLASHCACHE_NAME%+*}
                [ -b "/dev/$cache_dev" ] && flashcache_destroy -f /dev/$cache_dev
            fi
            if [ ! -b /dev/mapper/$cachename ]; then
                local uuid=`blkid -o value -s UUID $device`
                [ -e $TOS_FLASHCACHE/$uuid ] && rm -f $TOS_FLASHCACHE/$uuid
            fi
            #mounting ...
            mount_device "$device"
            #unlock subsys
            [ -e $SUBSYS_LOCK ] && rm -f $SUBSYS_LOCK
        fi
    done
    
    df-json | egrep /mnt/md[0-9]+$ > /dev/null
    [ $? -eq 0 ] && other_service_restore
}

service_remove() {
    local devices=`init_action_process $1`
    local FLAG=1
    [ -z "$devices" ] && return 1
    service_all_stop
    
    echo -e $devices | while read device
    do
        local blkname=`basename $device`
        local devsort=`device_sortbyname $blkname`
        local mntpath=/mnt/md${devsort}
        local cachename=fc${devsort}        
        if [ -b /dev/mapper/$cachename ]; then
            local SUBSYS_LOCK=/var/lock/subsys/$cachename
            umountAll $mntpath
            local FLASHCACHE_NAME=`procflash $blkname $FLAG`            
            if [ ! -z "${FLASHCACHE_NAME}" ]; then
                echo "$DMSETUP remove $cachename"
                $DMSETUP remove $cachename
                local cache_dev=${FLASHCACHE_NAME%+*}
                [ -b "/dev/$cache_dev" ] && flashcache_destroy -f /dev/$cache_dev
            fi
            if [ ! -b /dev/mapper/$cachename ]; then
                local uuid=`blkid -o value -s UUID $device`
                [ -e $TOS_FLASHCACHE/$uuid ] && rm -f $TOS_FLASHCACHE/$uuid
            fi
            #unlock subsys
            [ -e $SUBSYS_LOCK ] && rm -f $SUBSYS_LOCK
        fi
    done
}

service_status() {
    local devices=`init_action_process $1`
    echo -e $devices | while read device
    do
        local blkname=`basename $device`
        local devsort=`device_sortbyname $blkname`
        local cachename=fc${devsort}
        local SUBSYS_LOCK=/var/lock/subsys/$cachename
        [ -f $SUBSYS_LOCK ] && echo "Flashcache status: loaded" || echo "Flashcache status: NOT loaded"
        if [ -b /dev/mapper/$cachename ]; then            
            $DMSETUP status $cachename
        fi
    done
}

other_service_restore(){
    local names=(samba ftp nfs)
    for name in ${names[@]}; do
        if [ -f /etc/sc.d/$name ]; then
            [ -x /etc/init.d/$name ] && /etc/init.d/$name start
        fi
    done
}

case $1 in
    start)
        service_start $2
        ;;
    stop)
        service_stop $2
        ;;
    remove)
        service_remove $2
        ;;
    status)
        service_status $2
        ;;
    forcestop)
        service_stop $2 --force
        ;;
    *)
        echo -e $Usage
        exit 1
        ;;
esac
exit 0
