#!/bin/bash

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

# (c) Antonio Sánchez León <introlinux[fix@]gmail[fix.]com>
# (c) Miguel Anxo Bouzada <mbouzada[fix@]gmail[fix.]com>
# (c) GALPon MinNo Team <minino[fix@]galpon[fix.]org>
# july 2012

## -

##########################################################################################
##											##
## Un pequeño "script" para ajustar la fecha y la hora  bajo GNU/Linux con hwclock...	##
##											##
## Dependencias: hwclock								##
##		 awk (gawk, nawk)							##
##		 dialog									##
## Debe ejecutarse con permisos de root (su, sudo, gksu, gksudo)			##
##											##
##########################################################################################

export TEXTDOMAIN="minino-datetime"
export TEXTDOMAINDIR="/usr/local/share/locale" 

# Ahorrando trabajo de escritura en el código
TITLE="$(gettext "Set date and time")"
MSG1="$(gettext "«hwclock» not found
Execute as administrator (root or sudo):
apt-get install hwclock")"

# Ruta a iconos / Patht to icons
ICONS=/usr/share/icons/dialog

# Comprobamos la ejecución como administrador
if [ $(whoami) != "root" ];  then
	dialog --title "$(gettext "WARNING")" \
		--ok-label "$(gettext "OK")" \
		--icon $ICONS/importante.xpm \
		--msgbox "$(gettext "MiniNo_Date-Time requires root priviledges! Be careful!")" 0 0 0	
	exit 1
fi

# Reasignamos ruta si fuese necesario y comprobamos la existencia de hwclock. 
HWCLOCK=/sbin/hwclock
if [ -f "/usr/sbin/hwclock" ];then
  HWCLOCK=/usr/sbin/hwclock
fi 

if ! [ -f $HWCLOCK ] ; then
   dialog --title "$TITLE" --icon $ICONS/danger.xpm --msgbox "$MSG1 $HWCLOCK" 0 0
   exit 0
fi

# Buscar en "adjtime" a fin de saber si el RTC (reloj de tiempo real) fue fijado en la UTC (hora universal coordinada).
# Si no se encuentra "adjtime" a continuación, busca en el fichero /etc/sysconfig/clock
# y en última instancia, si no puede deducirse automáticamente, se le solicita al usuario ...
if [ -f /etc/adjtime ] ; then
	UTC=`grep UTC /etc/adjtime`
	if [ "$UTC" == "UTC" ] ; then
		UTC="--utc"
	fi
else
	if [ -f /etc/sysconfig/clock ] ; then
		. /etc/sysconfig/clock
		if [ "$UTC" == "no" ] || [ "$UTC" == "false" ] ; then
			UTC=""
		else
			UTC="--utc"
		fi
	else
		dialog --title "$TITLE" --yesno "$(gettext "Is the RTC set in UTC ?")" 0 0
		case $? in
	 		0)
			    UTC="--utc" ;;
			1)
			    UTC="" ;;
			255)
			    exit ;;
		esac
	fi
fi

# Obtenemos la fecha, devuelta en el formato DD/MM/YYYY por dialog.
ENTEREDDATE=`dialog --stdout --title "$TITLE" --icon $ICONS/duda.xpm --ok-label "$(gettext "OK")" --calendar "$(gettext "Select date...")" 0 0 0 0 0`
if [ ! $? -eq 0 ]; then
   exit
fi

# Convertimos la fecha al formato MM/DD/YYYY usado por hwclock.
NEWDATE=`echo "$ENTEREDDATE" | awk --source 'BEGIN { FS="/" }' --source '{ print $2 "/" $1 "/" $3 }'`

# Obtenemos la hora en el formato HH:MM:SS.
NEWTIME=`dialog --stdout --title "$TITLE" --icon $ICONS/duda.xpm --ok-label "$(gettext "OK")" --timebox "$(gettext "Select time...")" 0 0`
if [ ! $? -eq 0 ]; then
   dialog --title "$TITLE" --icon $ICONS/importante.xpm --msgbox "$(gettext "Cancel.")" 0 0
   exit
fi

# Preparamos el fichero de registro de errores.
echo "$(gettext "Error while trying to set the system clock !")" >/tmp/set-time.err.$$
echo "$(export TEXTDOMAIN="minino_hora-feha"
export TEXTDOMAINDIR="/usr/local/share/locale" gettext "Reason: ")" >>/tmp/set-time.err.$$
echo "" >>/tmp/set-time.err.$$

# Ajustamos el reloj de hardware (RTC) y despues el reloj del sistema.
# añadiendo cualquier mensaje de error.
if [ ! $? -eq 0 ] ; then
	sudo hwclock --hctosys $UTC 2>>/tmp/set-time.err.$$
fi

# La siguiente cadena da un error APARENTE de codificación, causado por la palabra "for".
# Para trabajar en el código, podemos PROVISIONALMENTE escaparla "\for".
# Acordarse de volver a quitarle el escape "\".
# dialog --title "$(gettext "Information")" --icon $ICONS/minino-splash.xpm --fill --ok-label "$(gettext "OK")" --msgbox "$(gettext "Your screen could get dark for some seconds. Wait please ...")" 0 0 0

# Creamos las variables para el mensaje final de éxito
D=`echo $NEWDATE|sed "s/^...//" | sed "s/\/.*$//"`
M=`echo $NEWDATE|sed "s/\/.*$//"`
Y=`echo $NEWDATE|sed "s/^........//" | sed "s/ .*$//"`
H=`echo $NEWTIME|sed "s/^.* //" | sed "s/://g" | sed "s/..$//"`
DT=`echo $M$D$H$Y`
sudo date $DT

sudo hwclock --set --date="$NEWDATE $NEWTIME" -s 2>>/tmp/set-time.err.$$

# Devolver el resultado (éxito o fracaso+razón).
if [ ! $? -eq 0 ] ; then
	THEDATE=`date`
	dialog --title "$(gettext "About...")" --icon $ICONS/reloj.xpm --ok-label "$(gettext "OK")" \
		--msgbox "$(gettext "Done. Date and time were setted to: ")\n $THEDATE" 0 0 
else
	dialog --title "$TITLE" --ok-label "$(gettext "OK")" --textbox /tmp/set-time.err.$$ 20 60
fi

rm -f /tmp/set-time.err.$$
