#!/bin/bash

usage="Usage: $0 [act] [mntpath] [passphrase]"
if [ -z "$1" ]; then
    echo $usage
    exit 1
fi

exec_cute=/usr/bin/ecryptfs-tools
sysdb=/etc/base/nasdb

getfolderid(){
    local dir_src=$1
    local ecrypt_name=$(basename "$dir_src")
    local folder_id=`sqlite3 $sysdb "select folder_id from share where foldername='$ecrypt_name' and ecryptfs=1"`
    echo $folder_id
}

deletefolder(){
    local mntpath=$1
    local basedir=$(basename "$mntpath")
    local lnkpath="/mnt/${basedir}"
    btrfs subvolume show "$mntpath" > /dev/null
    if [ $? -eq 0 ]; then
        btrfs subvolume delete -c "$mntpath" >/dev/null 2>&1
    else
        rm -fr "$mntpath"
    fi
    [ -L "$lnkpath" ] && rm -f "$lnkpath"
}

case $1 in
    umount)
        shift
        mntpath="$1"
        if [ -z "$mntpath" ]; then
            echo $usage
            exit 1
        fi
        df | grep "${mntpath}" > /dev/null
        [ $? -eq 0 ] && fuser -k "${mntpath}"
        $exec_cute -action=umount -path="$mntpath"
        # umount...
        df | grep "$mntpath" > /dev/null
        [ $? -ne 0 ] && deletefolder "$mntpath"
        ;;
    mount)
        shift
        mntpath="$1"
        passphrase="$2"
        if [ -z "$mntpath" -o -z "$passphrase" ]; then
            echo $usage
            exit 1
        fi
        path_father=$(dirname "$mntpath")
        foldername=$(basename "$mntpath")
        ecryptfs_path="${path_father}/@${foldername}@"
        if [ ! -d "$ecryptfs_path" ]; then
            echo "[ $ecryptfs_path ] isn't exists!"
            exit 1
        fi
        folderid=`getfolderid "$mntpath"`
        if [ -z "$folderid" ]; then
            echo "[ $foldername ] isn't ecryptfs dir!"
            exit 1
        fi
        if [ ! -e "${mntpath}" ]; then
            btrfs subvolume show "$path_father" > /dev/null
            [ $? -eq 0 ] && {
                btrfs subvolume create "${mntpath}">/dev/null 2>&1
            } || {
                mkdir -m 777 "${mntpath}"
            }
        fi
        passphrase_key=`sqlite3 $sysdb "select ecryptfs_sig from share_crypt where folder_id='$folderid'"`
        if [ -f "$passphrase" ]; then	
            [ "$passphrase_key" = "" ] && {
                echo $usage
                exit 1
            }
            $exec_cute -action=mount -path="$mntpath" -passphrase-file="$passphrase" -passphrase-key="$passphrase_key"
        elif [ "$passphrase_key" = "" ]; then
            $exec_cute -action=mount -path="$mntpath" -passphrase="$passphrase"
        else
            $exec_cute -action=mount -path="$mntpath" -passphrase="$passphrase" -passphrase-key="$passphrase_key"
        fi
        lnkpath="/mnt/${foldername}"
        df | grep "$mntpath" > /dev/null
        if [ $? -eq 0 ]; then
            ln -fsn "$mntpath" "$lnkpath"
        else
            deletefolder "$mntpath"
        fi
        ;;
esac
exit 0
