#!/bin/bash

. /etc/tos/scripts/scripts

usage="Usage:$(basename $0) [/dev/vg0/lv0|/dev/mapper/vg0-lv0]"
[ -z "$1" -o ! -b "$1" ] && {
    echo $usage
    exit 1
}
script_get_lock >/dev/null
[ $? -ne 0 ] && exit 1

lv_path=$1
# volumeGroup isn't exists
vg_name=$(lvs -o vg_name $lv_path --noheadings 2>/dev/null | sed s/[[:space:]]//g)
if [ $? -ne 0 ]; then
    echo $usage
    script_put_lock >/dev/null
    exit 2
fi

TOS_UUID=$(GetDeviceUUID $lv_path)
TOS_VOLUME_ROOT=/tmp/volume
[ ! -e $TOS_VOLUME_ROOT ] && mkdir $TOS_VOLUME_ROOT

lv_name=$(lvs -o lv_name $lv_path --noheadings 2>/dev/null | sed s/[[:space:]]//g)
DEVSORT=$(GetVolumeSort $lv_path) #device sort
logFile="$TOS_VOLUME_ROOT/stopFS_${lv_name}_$(date +"%Y%m%d")"
#get mntpoint
MNTPOINT=$(getmntpoint "$lv_path")
mntInfo=$(df-json | grep -E "$lv_path|$MNTPOINT")
mntOPTS=$(GetMountOpts "$lv_path" "$TOS_UUID")

mountBtrfsRootSubvolume(){
    # mount btrfs root subvolume /var/subvols/xxxx
    local btrfsRoot=$(echo -e "$mntInfo" | grep "/var/subvols/")
    local filesystem=$(echo -e "$btrfsRoot" | awk '{print $2}')
    if [ $filesystem == "btrfs" ]; then
        local source=$(echo -e "$btrfsRoot" | awk '{print $1}')
        local target=$(echo -e "$btrfsRoot" | awk '{print $8}')
        mount | grep $target
        if [ $? -ne 0 ]; then
            local btrfsSubvolName=$(iniparse -c -f $TOS_DEFAULT_CONFIG -s filesystem -k btrfs_subvolName)
            if echo -e "$mntOPTS" | grep -q "subvol=$btrfsSubvolName"; then
                local opts=$(echo "$mntOPTS" | sed "s/subvol=$btrfsSubvolName,//")
            else
                local opts=$mntOPTS
            fi
            echo "$(date +"%Y/%m/%d %H:%M:%S") stopFS rollBack: mount -t $filesystem -o $opts $source $target" >> $logFile
            mount -t $filesystem -o $mntOPTS $source $target >> $logFile 2>&1
            if [ $? -eq 0 -a $opts == $mntOPTS ]; then
                # check btrfs mount opts,if there is a root subvolume mount,need to add "subvol=@" for the volume mount. 
                mntOPTS="subvol=${btrfsSubvolName},$mntOPTS"
            fi
        fi
    fi
}

mountVolume(){
    # mount /Volume (if filesystem is btrfs,will mount subvolume(@) to '/Volume1' )
    volumeLine=$(echo -e "$mntInfo" | grep "$MNTPOINT$")
    filesystem=$(echo -e "$volumeLine" | awk '{print $2}')
    source=$(echo -e "$volumeLine" | awk '{print $1}')
    target=$(echo -e "$volumeLine" | awk '{print $8}')
    mount | grep $target
    if [ $? -ne 0 ]; then
        echo "$(date +"%Y/%m/%d %H:%M:%S") stopFS rollBack: mount -t $filesystem -o $mntOPTS $source $target" >> $logFile
        mount -t $filesystem -o $mntOPTS $source $target >> $logFile 2>&1
    fi
}

rollBack() {
    # mount btrfs root subvolume /var/subvols/xxxx
    mountBtrfsRootSubvolume
    # mount /Volume (if filesystem is btrfs,will mount subvolume(@) to '/Volume1' )
    mountVolume
    # mount other 
    echo -e "$mntInfo" | grep -vE "/var/subvols/|$MNTPOINT$" | while read -r line;do
        source=$(echo -e "$line" | awk '{print $1}')
        target=$(echo -e "$line" | awk '{print $8}')
        mount | grep $target
        if [ $? -ne 0 ]; then
            echo "$(date +"%Y/%m/%d %H:%M:%S") stopFS rollBack: mount $source $target" >> $logFile
            mount $source $target >> $logFile 2>&1
        fi
    done
}

checkLvStatus() {
  lvName=$(lvs -o lv_name $lv_path --noheadings 2>/dev/null)
  if [ $? -eq 0 ]; then
      rollBack
      echo "$(date +"%Y/%m/%d %H:%M:%S") stopFS: $lv_path Failed *************************" >> $logFile
      script_put_lock >/dev/null
      exit 2
  fi
}

filterService() {
    sc=/etc/sc.d/StorageManager
    if [ -f "$sc" ]; then
        rm -f "$sc"
    fi
}

echo "$(date +"%Y/%m/%d %H:%M:%S") stopFS: $lv_path start *************************" >> $logFile

# remove the flashcache
DEVFLAC=/dev/mapper/fc${DEVSORT}
[ -b $DEVFLAC ] && /etc/tos/scripts/flashcache remove $lv_path >/dev/null

if [ ! -z "$MNTPOINT" ]; then
    filterService
    check_main_raid "$MNTPOINT"
    if [ $? -eq 0 ]; then
        echo "$(date +"%Y/%m/%d %H:%M:%S") stopFS: [main_service_stop] start" >> $logFile
        main_service_stop
    else
        echo "$(date +"%Y/%m/%d %H:%M:%S") stopFS: [ter_service $MNTPOINT stop] start" >> $logFile
        ter_service $MNTPOINT stop
    fi
    service_stop
fi

umountAll "$MNTPOINT"
umountAll "$lv_path"
df-json | grep "$lv_path" >/dev/null
if [ $? -eq 0 ]; then
    echo "$(date +"%Y/%m/%d %H:%M:%S") stopFS: Failed!" >> $logFile
    checkLvStatus
    script_put_lock >/dev/null
    exit 0
fi

echo "$(date +"%Y/%m/%d %H:%M:%S") stopFS: $lv_path Success *************************" >> $logFile
script_put_lock >/dev/null
exit 0
