#!/bin/bash

# The client name should be absolute or available through $PATH.
CLIENT_EXECUTABLE="efs-client"

# When run by mount based on an /etc/fstab entry, this script is run as:
#   mount-efs-client /mnt/mountpoint -o opt1=val1,opt2,opt3=val3
MOUNTPOINT=$1
OPTION_STRING=$3

# Find out what options are accepted by the client.
declare -A ACCEPTED_OPTIONS
while read -r OPT
do
	ACCEPTED_OPTIONS[$OPT]=1;
done < <($CLIENT_EXECUTABLE --help --hidden-options |& grep -- '--' | sed -re 's/^......--([a-zA-Z0-9-]+).*/\1/')

# Add some default options for mounting via fstab: divert logs to system log,
# and add --delayed-init so that the mount point can be created before the network is available.
CLIENT_OPTIONS=("--log-file=syslog" "--delayed-init=yes" "--fuse-option=allow_other")

# Analyze each option from the string and add to either client or FUSE options
IFS=, read -r -a OPTIONS <<< "$OPTION_STRING"
for OPT in "${OPTIONS[@]}"
do
	if [[ ${ACCEPTED_OPTIONS[${OPT%=*}]} -eq 1 ]]
	then
		CLIENT_OPTIONS+=("--$OPT")
	else
		CLIENT_OPTIONS+=("--fuse-option" "$OPT")
	fi
done

exec $CLIENT_EXECUTABLE "${CLIENT_OPTIONS[@]}" -- "$MOUNTPOINT"
