#!/bin/sh

##########################################################################################
##											##
## Dependencias: Xdialog								##
##		 zenity									##
##		 samba									##
##		 gawk									##
##											##
## Debe executarse con permisos de administrador (su, sudo, gksu, gksudo)		##
##											##
## Este script foi realizado polo equipo de desenvolvedores de GALPon MiniNo		##
##	<minino@galpon.org>							 	##
##											##
## Este script publicase SEN NINGUNHA GARANTIA e baixo a Licenza Pública Xeral GNU/GPL	##
## versión 2 ou superior, publicada pola Free Software Fundation.			##
##											##
##########################################################################################
##########################################################################################
##											##
## Dependences:  Xdialog								##
##		 zenity									##
##		 samba									##
##		 gawk									##
##											##
## You have to execute it with administrator permissions (su, sudo, gksu, gksudo)	##
##											##
## Script developed by GALPon MiniNo Team <minino@galpon.org>				##
##										 	##
## This program is distributed, but WITHOUT ANY WARRANTY and following the		##
## GNU/GPL General Public License version 2 or any later version published by the	##
## Free Software Fundation.								##
##											##
##########################################################################################

export TEXTDOMAIN="groupAdmins"
export TEXTDOMAINDIR="/usr/local/share/locale"

# Comprobamos la ejecución como administrador
if [ $(whoami) != "root" ]; then
  zenity --error \
          --text="$(gettext "This action requires administrator priviledges!

Be careful!")"
	exit 0
fi

#=======================================

samba_users () {
  # Ruta a iconos / Patht to icons
  ICONS=./Xdialog #/usr/share/icons/Xdialog

  # Comprobamos la existencia de "awk" (gaw, mawk o awk-original).
  if ! [ -d /usr/lib/awk ]; then
    Xdialog --title "$(gettext "WARNING")" --icon $ICONS/danger.xpm \
    --msgbox "$(gettext "«awk» not found.
Execute as administrator (root or sudo):")
apt-get install gawk $(gettext "(recommended)
or")
apt-get install mawk" 0 0
    exit 0
  fi

  # Comprobamos la existencia de smbpasswd. 
  if ! [ -f /usr/bin/smbpasswd ]; then
    Xdialog --title "$(gettext "WARNING")" --icon $ICONS/danger.xpm \
    --msgbox "$(gettext "«smbpasswd» not found.
Execute as administrator (root or sudo):")
apt-get install samba" 0 0
    exit 0
 fi

  # Pedimos los datos
  LOGIN1=`Xdialog --stdout --separator "|" \
    --icon $ICONS/usuarios.xpm --password --password\
    --title "$(gettext "SaMBa")" --backtitle "$(gettext "Creation or modification of
SaMBa Users")"\
    --3inputsbox "$(gettext "NOTE:
Use Tab to move into box dialog.")" 0 0 \
      "$(gettext "User Name:")" "$USUARIO"\
      "$(gettext "New SMB Password:")" "" \
      "$(gettext "Retype new SMB Password:")" "" \
    --no-close --no-cancel --title "$(gettext "SaMBa")"\
    --icon $ICONS/save-as.xpm --yesno "$(gettext "Aply?")" 0 0`
  ret=$?

  # Obtenemos las variables
  case $ret in
    0)
      NAME=`echo $LOGIN1 | awk --source 'BEGIN { FS="|" }' --source '{ print $1 }'`
      PASSWD=`echo $LOGIN1 | awk --source 'BEGIN { FS="|" }' --source '{ print $2 }'`
      REPASSWD=`echo $LOGIN1 | awk --source 'BEGIN { FS="|" }' --source '{ print $3 }'`

      # Comprobamos si existe el usuario en el sistema
      if ! [ `find /etc/group -type f | xargs grep -o $NAME:x:` ] ; then
        `Xdialog --title "$(gettext "WARNING")" \
        --icon $ICONS/importante.xpm \
        --msgbox "$(gettext "No such user in the system.

You must add it before (as root) with the command:")
adduser $NAME" 0 0`
        exit 0
      fi

      # Comprobamos la coherencia de las contraseñas
      if [ "$PASSWD" != "$REPASSWD" ]; then
        `Xdialog --title "$(gettext "WARNING")"\
        --icon $ICONS/importante.xpm\
        --ok-label "$(gettext "Repeat")"\
        --yesno "$(gettext "Mismatch Passwords.

Repeat the process.")" 0 0`

        # Procesamos la orden
        case $? in
          0)
            samba_users ;;
          1) exit ;;
          255) exit ;;
        esac
      else
         `Xdialog --title "$(gettext "SaMBa")" --backtitle "$(gettext "SaMBa Users")"\
        --icon $ICONS/usuarios.xpm --no-button\
        --infobox "$(gettext "Starting the process.

Whait please...")" 0 0 1500`

        (echo $PASSWD; echo $PASSWD)| sudo smbpasswd -s -a $NAME

        `Xdialog --title "$(gettext "SaMBa")" --backtitle "$(gettext "SaMBa Users")"\
        --icon $ICONS/usuarios.xpm --no-button\
        --infobox "$(gettext "Done!
Created or Modified SaMBa User")" 0 0 3000`
      fi
      ;;
    1) exit ;;
    255) exit ;;
  esac
  sudo /etc/init.d/samba restart
}


#=======================================

get_user () {
  USUARIO=$(zenity --entry \
    --title="$(gettext "User")" \
    --text="$(gettext "Escriba el nombre de usuario:")")
}

#=======================================

ACCION=$(zenity --list --title="$(gettext "Grupos especiales")" \
--text="$(gettext "<b>P</b>uede añadir a un usuario a grupos con
permisos especiales para:
    <b>A</b>dministrar impresoras:
        Añadir, modificar y configurar.
    <b>C</b>ompartir archivos con otros ordenadores
    usando <b>S</b>a<b>MB</b>a.
    <b>C</b>ompartir archivos por procedimientos
    que usen «fuse» (p.ej. sshfs, fusesmb...)

Elija el permiso que desea conceder:")" \
--radiolist \
--width="320" --height="388" \
--hide-column=2 \
--column="" \
--column="" \
--column="$(gettext "Conceder permisos para:")" \
FALSE "I" "$(gettext "Administrar impresoras")" \
FALSE "S" "$(gettext "Compartir archivos con SaMBa")" \
FALSE "F" "$(gettext "Compartir archivos con FUSE")" \
FALSE "T" "$(gettext "TODOS los permisos especiales")")

case $? in
  0)
    if [ "$ACCION" = "I" ]; then
      get_user
        echo adduser $USUARIO lpadmin
#        sudo adduser $USUARIO lpadmin
    elif [ $ACCION = "S" ]; then
      samba_users
    elif [ $ACCION = "F" ]; then
      get_user
        echo adduser $USUARIO fuse
#        sudo adduser minino fuse
    elif [ $ACCION = "T" ]; then
      get_user
        if [ $? = 1 ]; then exit 0
        fi
        echo usermod -G lpadmin,fuse $USUARIO
#       sudo usermod -G lpadmin,fuse $USUARIO
        samba_users
    else
      exit 0
    fi
    ;;
  1) exit ;;
  255) exit ;;
esac
