#!/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, Rafael Rodríguez Gayoso 
#			<rrodriguezg@santiagodecompostela.gal>

DB=/home/$USER/mount.db
TMPDIR="$(mktemp -d)"

while true
do
	
	res=$(zenity --list  --radiolist --hide-header --title="Selecciona" --column="" --column="" \
	FALSE "Seleccionar directorios" FALSE "Crear BD a partir de directorio" FALSE "Saír" 2>/dev/null)
	
	case $res in
		"Seleccionar directorios")
			filas=$(wc -l < ${DB})
			altura=$((200+($filas*20)))
	
			res=$(zenity --list --checklist --height $altura --width 600 --column "Estado" \
			--column "Nome directorio" $(cat ${DB} | sort) \
			--text "Selecciona os directorios que se montarán ao inicio de sesión" \
			--title "Configuración" --separator=":" 2>/dev/null) 
			
			[ $? -eq 1 ] && continue

			echo $res | tr : "\n" | sort > "${TMPDIR}"/mountres.db
	
			sed -i 's/TRUE //' ${DB} 
			sed -i 's/FALSE //' ${DB}
	
			sort ${DB} > ${TMPDIR}/mountord.db
	
			comm -21 "$TMPDIR"/mountres.db "$TMPDIR"/mountord.db | sed 's/^/TRUE /' > "$TMPDIR"/mount.temp
			comm -13 "$TMPDIR"/mountres.db "$TMPDIR"/mountord.db | sed 's/^/FALSE /' >> "$TMPDIR"/mount.temp
	
			mv "$TMPDIR"/mount.temp ${DB}
			rm "$TMPDIR"/mountres.db "$TMPDIR"/mountord.db 
			;;
		"Crear BD a partir de directorio")	
			dir=$(zenity  --file-selection --title="Choose a directory"  --directory 2>/dev/null)
			files=($dir/*)
	
			for item in ${files[*]}
			do
				printf "FALSE %s\n" $item
			done > ${DB}
			;;
		*)
			rm -rf "$TMPDIR"
			exit 0
			;;
	esac
done
