#!/bin/bash

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

exec_cute=/usr/bin/ecryptfs-tools

getfolderid() {
    local dir_src=$1
    local ecrypt_name=$(basename "$dir_src")
    local folder=$(tersql -sql "select folder_id from share where foldername='$ecrypt_name' and ecryptfs=1" -only)
    local folder_id=$(echo $folder | jq -r .folder_id)
    echo $folder_id
}

get_ecryptfs_sig() {
    local id=$1
    local folder=$(tersql -sql "select ecryptfs_sig from share_crypt where folder_id='$id'" -only)
    local ecryptfs_sig=$(echo $folder | jq -r .ecryptfs_sig)
    echo $ecryptfs_sig
}

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-json | grep "${mntpath}" >/dev/null
    [ $? -eq 0 ] && fuser -k "${mntpath}"
    $exec_cute -action=umount -path="$mntpath"
    # umount...
    df-json | 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=$(get_ecryptfs_sig $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
    df-json | egrep "/Volume[0-9]+/$foldername" >/dev/null
    if [ $? -ne 0 ]; then
        deletefolder "$mntpath"
    fi
    ;;
esac
exit 0
