#!/bin/sh

# Script for automount specified GIO locations 
# (c) 2016 Andrey Cherepanov <cas@altlinux.org>

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
VERSION="1.2"

. shell-quote

system_config="/etc/gvfs.shares"
user_config="$HOME/.gvfs.shares"
mount_command="gvfs-mount"
umount_command="gvfs-mount -u"

if [ -w "$system_config" -o -w /etc ]; then
	config="$system_config"
else
	config="$user_config"
fi

if [ -x '/usr/bin/gio' ]; then
	mount_command="gio mount"
	umount_command="gio mount -u"
fi


# List a`ll configured shares (both system and user)
list_shares()
{
	# System
	[ -e "$system_config" ] && grep '^[^#]' "$system_config"

	# User
	[ -e "$user_config" ] && grep '^[^#]' "$user_config"

}

# Mount all locations
mount_all()
{
	list_shares | while read loc
	do
		echo "Mounting $loc"
		$mount_command $loc
	done
}

# Unmount all locations
umount_all()
{
	list_shares | while read loc
	do
		echo "Unmounting $loc"
		$umount_command $loc
	done
}

usage()
{
	cat <<END.
Script for automount specified GIO locations

Usage: gvfs-shares [<command>] [<option>]

Commands:
list    Show configured mount locations
add     Add location to automount
rm      Remove location from automount
        gvfs-shares rm all removes all locations
mount   Mount all locations
umount  Unmount all locations
-h      Show usage information
-v      Show version info
END.
	exit
}


case "$1" in
	add)
		shift
		[ -z "$1" ] && usage
		echo "$@" >> "$config"
		;;
	rm)
		[ -z "$2" ] && usage
		[ "$2" = "all" ] && echo -n "" > "$config"
		touch "$config"
		sed -i "/^$(quote_sed_regexp "$2")$/d" "$config"
		;;
	mount)
		mount_all
		;;
	umount)
		umount_all
		;;
	-h|--help)
		usage
		;;
	-v|--version)
		echo "$VERSION"
		exit 0
		;;
	list|"")
		list_shares
		;;
	*)
		echo "Unknown command $1" >&2
		usage
esac
