#!/bin/sh

JQ=`which jq`
remote_config="/etc/remotefolder/remotefolder.conf"
[ ! -e $remote_config ] && exit 1

TOS_USERNAME=$3

get_id(){
	uid=$(/usr/bin/id -u $TOS_USERNAME)
	gid=$(/usr/bin/id -g $TOS_USERNAME)
}

mount_single_key(){
    local key=$1
    local Auto=$2
    local power_boot=`$JQ -r .${key}.power_boot $remote_config`
    [ $Auto -eq 1 -a "$power_boot" != "1" ] && return 1;
    local fs=`$JQ -r .${key}.fs $remote_config`
    if [ "$fs" = "nfs" ]; then
        local load_path=`$JQ -r .${key}.load_path $remote_config`
        local load_destination=`$JQ -r .${key}.load_destination $remote_config`
        local transport_protocol=`$JQ -r .${key}.transport_protocol $remote_config`
	    local version=`$JQ -r .${key}.version $remote_config`
        if [ "${version}" = "V3" ];then
            local ver=3
        else
            local ver=4
        fi

        mount -t nfs -o nolock,timeo=8,retry=0,nfsvers=${ver},${transport_protocol} ${load_path} ${load_destination}
        sleep 1
        echo ok
    else
        local folder=`$JQ -r .${key}.folder $remote_config`
        local load_destination=`$JQ -r .${key}.load_destination $remote_config`
        local username=`$JQ -r .${key}.username $remote_config`
        local password=`$JQ -r .${key}.password $remote_config`
	get_id
        mount.cifs -o username=${username},password=${password},uid=$uid,gid=$gid ${folder} ${load_destination}
        sleep 1
        echo ok
    fi
}

umount_single_key(){
    local key=$1
    if [ ! -z "$key" ]; then
        local load_destination=`$JQ -r .${key}.load_destination $remote_config`
        [ -z "$load_destination" ] && return 1
        df-json | grep "${load_destination}$" > /dev/null
        if [ $? -eq 0 ]; then
            fuser -k $load_destination
            sleep 1
            umount $load_destination
	    echo ok
        fi
        return 0
    fi
    return 1
}

service_mount_all(){
    $JQ -r 'keys[]' $remote_config | while read line
    do
        [ ! -z "$line" ] && mount_single_key "$line" 1
    done
    return 0
}

service_mount(){
    local key=$1
    if [ ! -z "$key" ]; then
        mount_single_key "$key" $Auto 0
        return 0
    fi
    return 1
}

service_umount_all(){
    $JQ -r 'keys[]' $remote_config | while read line
    do
        [ ! -z "$line" ] && umount_single_key "$line"
    done
    return 0
}

service_umount(){
    local key=$1
    if [ ! -z "$key" ]; then
        umount_single_key "$key"
        return 0
    fi
    return 1
}

result=0
case $1 in
    mountall)
        service_mount_all
        result=$?
        ;;
    mount)
        service_mount $2
        result=$?
        ;;
    umount)
        service_umount $2
        result=$?
        ;;
    umountall)
        service_umount_all
        result=$?
        ;;
    *)
        echo "`basename $0`: {mountall|mount|umountall|umount} {name}"
        exit 1
esac
exit $result

