
####  AVISO: NO EDITAR variables de configuración.
####  WARNING: DO NOT EDIT configuration variables.
OPENGNSYS="/opt/ogboot"		# Directorio de OpenGnsys
OGBOOT="/opt/ogboot"			# Directorio de ogBoot
OGIMG="images"				# Directorio de imágenes del repositorio
OPENGNSYS_CLIENT_USER="opengnsys"	# Usuario Samba
OPENGNSYS_OLDDATABASE="ogBDAdmin"	# Antigua base de datos
MYCNF=/tmp/.my.cnf.$$			# Fichero temporal con credenciales de acceso a la BD.
TFTPDIR=$(readlink $OPENGNSYS/tftpboot 2>/dev/null)	# Directorio de PXE/TFTP

# Sólo ejecutable por usuario root
if [ "$(whoami)" != 'root' ]; then
    echo "ERROR: this program must run under root privileges!!"
    exit 1
fi

# Solicitar confirmación para la desinstalación de OpenGnsys.
read -rp "WARNING: Files under $OPENGNSYS directory will be removed. Continue to uninstall? (y/n): " REPLY
if [ "${REPLY^^}" != "Y" ]; then
    echo "Operation cancelled."
    exit 0
fi

# Parar servicio.
echo "Uninstalling OpenGnsys services."
if [ -x /etc/init.d/opengnsys ]; then
    /etc/init.d/opengnsys stop
    if [ -n "$(which update-rc.d 2>/dev/null)" ]; then
        update-rc.d -f opengnsys remove
    else
	chkconfig --del opengnsys
    fi
fi

#Parar ogserver
if [ -r /lib/systemd/system/ogserver.service ]; then
    systemctl stop ogserver
    systemctl disable ogserver
    rm /lib/systemd/system/ogserver.service
fi

# Quitar configuración específica de Apache.
[ -n "$(which a2dissite 2>/dev/null)" ] && a2dissite ogboot
rm -f /etc/{apache2/{sites-available,sites-enabled},httpd/conf.d}/ogboot*
for serv in apache2 httpd; do
    [ -x /etc/init.d/$serv ] && /etc/init.d/$serv reload
done
# Eliminar ficheros.
echo "Deleting OpenGnsys files."
for dir in $OPENGNSYS/*; do
    if [ "$dir" != "$OPENGNSYS/$OGIMG" ]; then
        rm -fr "$dir"
    fi
done
rm -f /etc/init.d/opengnsys /etc/default/opengnsys /var/log/opengnsys
rm -f /etc/cron.d/{opengnsys,torrentcreator,torrenttracker}
rm -f /etc/logrotate.d/opengnsys*
# Elminar recursos de OpenGnsys en Samba.
rm -f /etc/samba/smb-og.conf
perl -ni -e "print unless /smb-og.conf/" /etc/samba/smb.conf
for serv in smbd smb ; do
    [ -x /etc/init.d/$serv ] && /etc/init.d/$serv reload
done
# Eliminar usuario de OpenGnsys.
smbpasswd -x $OPENGNSYS_CLIENT_USER
userdel $OPENGNSYS_CLIENT_USER
# Tareas manuales a realizar después de desinstalar.
echo "delete temporary files"
rm -rf /tmp/ogboot_installer
rm -rf /opt/ogboot
rm -rf /opt/opengnsys
echo "Manual tasks:"
echo "- You may stop or uninstall manually all other services"
echo "     (DHCP, PXE, TFTP, NFS/Samba, Apache, MySQL)."
echo "- Delete repository directory \"$OPENGNSYS/$OGIMG\""
[ -n "$TFTPDIR" ] && echo "- Delete PXE configuration directory \"$TFTPDIR\""
