#!/bin/bash
# vim:noet:ts=4:sw=4:ai:tw=80:

#   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/>.

#   Copyright (C) 2017, CONTROL SUPRIMIR S.L.U.
#   Authors:
#       Guillermo Cordeiro Baqueiro <gcordeiro@librebit.com>

# Este script debe devolver siempre 0 para que la autenticación no se
# vea entorpecida por el montaje.

declare -a shares=()

if [[ $PAM_SERVICE != "gdm-password" ]]; then
	send_to_log "Iniciando sesion con $PAM_SERVICE. No se realiza el montaje."
	return 0
fi

declare SMB_OPTIONS="user=${PAM_USER},password=${PAM_AUTHTOK},workgroup=CONCELLO,actimeo=3,uid=${userID},gid=${userGID}"
declare tmpDir="$(mktemp -d)"

if ! which smbclient &>/dev/null; then
	send_to_log "Falta smbclient. No es posible listar recursos remotos"
	return 0
fi

if ! which mount.cifs &>/dev/null; then
	send_to_log "Falta cifs-utils. No es posible montar recursos samba"
	return 0
fi

for server in scq1f scqd1 scqbackup; do
	readarray -t shares < <(
		smbclient -L "${server}.concello.santiagodecompostela.org" \
			-W CONCELLO -U "${PAM_USER}%${PAM_AUTHTOK}" |
			awk '$2 == "Disk" {print $1}')

	for share in "${shares[@]}"; do

		if [[ ! -d "$home/Compartidos/$share" ]]; then
			mkdir -p "$home/Compartidos/$share"
			chown "$PAM_USER": "$home/Compartidos/$share"
		elif mountpoint -q "$home/Compartidos/$share"; then
			## Si ya está montado se deja
			continue
		fi

		mount "//$server/$share" "$home/Compartidos/$share" -o "$SMB_OPTIONS"

		if [[ $? -ne 0 ]]; then
			if ! mountpoint -q "$home/Compartidos/$share"; then
				mv "$home/Compartidos/$share" "$tmpDir/$share"
			else
				send_to_log "El recurso $share está montado pero salió con error."
			fi
		fi
	done
done

rm -rf "$tmpDir"
