#!/bin/bash

if [ -f /etc/tos/scripts/scripts ]; then
    . /etc/tos/scripts/scripts
fi
usage=`basename $0`" {device name}"
if [ -z "$1" ]; then
    echo "$usage"
    exit 1
fi

luksmnt(){
    local blk="$1"
    [ ! -b "$blk" ] && return 1
    local number=${blk:0-1}
    local cryptname=`basename $blk`
    cryptsetup luksClose "$cryptname"
    sleep 1
    cryptsetup luksOpen "$blk" "$cryptname"
    local cryptblk=/dev/mapper/$cryptname
    [ ! -b $cryptblk ] && return 1

    df | grep $cryptblk > /dev/null
    if [ $? -eq 0 ]; then
        echo $1 has already mounted
        return 1
    fi
    local mountpath=/mnt/$cryptname
    local fs=`blkid -s TYPE -o value $cryptblk`
    [ -z "$fs" ] && return 1

    mkdir -m 777 -p $mountpath
    if [ "$fs" = "btrfs" ]; then
        mount $MNTYPE -o $MNTOPT_BTRFS $cryptblk $mountpath
        df | grep $mountpath >/dev/null
        [ $? -ne 0 ] && return 1
    else
        mount $MNTYPE -o $MNTOPT_EXT4 $cryptblk $mountpath
        df | grep $mountpath >/dev/null
        [ $? -ne 0 ] && return 1
        /etc/tos/scripts/quota_init
    fi
    echo mount $1 on $mountpath success	
    if [ ! -e /mnt/public ]; then
        /etc/init.d/nas/mkbase $mountpath
    fi
    # update the samba dir
    return 0
}

luksmnt "$1"
