#!/bin/sh

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

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)
    local source_path=$($JQ -r .${key}.source_path $remote_config)
    if [ "$fs" = "nfs" ]; then
        local destination_path=$($JQ -r .${key}.destination_path $remote_config)
        local transport_protocol=$($JQ -r .${key}.transport_protocol $remote_config)
        local version=$($JQ -r .${key}.version $remote_config)
        local ver=4
        [ "${version}" = "V3" ] && ver=3
        mount -t nfs -o nolock,timeo=8,retry=0,nfsvers=${ver},${transport_protocol} ${source_path} "${destination_path}"
        return $?
    else
        local destination_path=$($JQ -r .${key}.destination_path $remote_config)
        local username=$($JQ -r .${key}.username $remote_config)
        local password=$($JQ -r .${key}.password $remote_config)
        mount.cifs -o file_mode=0777,dir_mode=0777,username=${username},password=${password} ${source_path} "${destination_path}"
        return $?
    fi
}

umount_single_key() {
    local key=$1
    if [ ! -z "$key" ]; then
        local destination_path=$($JQ -r .${key}.destination_path $remote_config)
        [ -z "$destination_path" ] && return 1
        df | egrep "${destination_path}$" >/dev/null
        if [ $? -eq 0 ]; then
            fuser -k "$destination_path"
            sleep 1
            umount "$destination_path"
            echo ok
        fi
        return 0
    fi
    echo "empty key" >&2
    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 $?
    fi
    echo "empty key" >&2
    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 $?
    fi
    echo "empty key" >&2
    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
