#!/bin/bash

#    detectahttpd, para detectar ubicacion y usuarios del apache, 

#    Pensado para ser usado en instaladores de documentacion 
#    y programas para servidores

#    Es Software Libre, Copyleft.
#    Publicado en forma gratuita y universalmente libre y copyleft
#    en el repositorio del psicro http://www.psicro.org
    
#    Copyright 2004 al 2008 (C)  por Diego Saravia Alía, dsa@unsa.edu.ar
#    bajo la GPL 3.0 o superior

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

#probado con exito al menos en un: ututo, debian, opensuse, slackware
#debian no usa -f, por defecto incluido en camino /etc/apache2/apache2.conf
 
#debiera escribir todo en perl, ya que lo uso, aunque si perl no esta, 
#el resto funciona. PROBAR ESTO
#grep -v grep corrrige error bond, -v $0 uno similar,
# http y apache no solo estan en el comando sino en el camino




TEMP=`getopt -o hv --long help,version -- "$@"`

#if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true ; do
	case "$1" in
		-h|--help) echo "Help" ; shift ; exit ;;
		-v|--version) echo "Version" ; shift ; exit  ;;
		--) shift ; break ;;
		*) echo "Internal error!" ; exit 1 ;;
	esac
done
#echo "Remaining arguments:"
for arg do echo '--> '"\`$arg'" ; done




PRIMLINPSHTTPD=`ps -eo user,args|grep httpd|grep -v root|grep -v grep\
               |grep -v $0|tail -n1`
HTTPDUSER=`echo $PRIMLINPSHTTPD|awk '{print $1}'`

if test $HTTPDUSER; then
   HTTPDGRP=`ps -eo group,args|grep httpd|grep -v root|grep -v grep|grep -v $0\
            |tail -n1|awk '{print $1}'`
   HTTPDCONFINI=`echo $PRIMLINPSHTTPD|perl -e '$a=<>;$a=~/-f[\t\s\b]*(\S+)/;\
                                               print $1'`
   HTTPDSERROOT=`echo $PRIMLINPSHTTPD|perl -e '$a=<>;$a=~/-d[\t\s\b]*(\S+)/;\
                                               print $1'`
  else
   PRIMLINPSAPACHE=`ps -eo user,args|grep apache|grep -v root|grep -v grep|
                                     \grep -v $0|tail -n1`
   HTTPDUSER=`echo $PRIMLINPSAPACHE|awk '{print $1}'`
   HTTPDGRP=`ps -eo group,args|grep 'apache'|grep -v 'root'|grep -v 'grep'|
                               \grep -v $0|tail -n1|awk '{print $1}'`
   HTTPDCONFINI=`echo $PRIMLINPSAPACHE|perl -e '$a=<>;$a=~/-f[\t\s\b]*(\S+)/;\
                                                print $1'`
   HTTPDSERROOT=`echo $PRIMLINPSAPACHE|perl -e '$a=<>;$a=~/-d[\t\s\b]*(\S+)/;\
                                                print $1'`
fi

DIRCONF=`echo $HTTPDCONFINI|perl -e '$s=<>; @a=split(/\//,$s); $n=@a;\
                                     print join("/",@a[0..$n-2])'`

# podria usar opcion -d para encontrar directorio ServerRoot y arreglar: 
# Uses the directives in the file config on startup. If config does not begin
# with a /, then it is taken to be a path rela-
# tive to the ServerRoot. The default is /etc/apache2/apache2.conf.

# solo encontre a gentoo y ututo usando -d, pero tambien usan -f
 
CAMINO="/etc /usr/local /usr /opt"

# revisar esta logica

if test $HTTPDCONFINI; then
   if test $DIRCONF; then
      CAMINO="$DIRCONF $CAMINO"    
      CAMBIACAMINO=SI
   fi
  else
    # ver si el archivo existe antes
    HTTPDCONFINI=/etc/apache2/apache2.conf
    HTTPDCONFDEF=SI
fi
#echo "# $CAMINO - $DIRCONF - $HTTPDCONFINI"
for H1 in $CAMINO; do 
  for H2 in "" /apache2 /apache/conf /httpd/conf /httpd; do
       for H3 in  /default-server.conf /vhosts.d/default_vhost.include \
                  /sites-available/default\
                  /sites-available/default.dpkg-dist\
                  /apache.conf  /httpd.conf; do
          HP="$H1$H2$H3"
          #echo "# $HP"
          if test -e $HP; then
              HTTPDCONF=$HP  
              HTTPDPROOT=`cat  $HTTPDCONF|\
                          awk '/^[\s\t\b]*DocumentRoot / {print $2}'|sed 's/"//g'`
	      #echo $HTTPDCONF - $HTTPDPROOT 
              if test $HTTPDPROOT; then
                 break 5
	      fi
          fi
       done
   done
done

if test $HTTPDCONF; then
  HTTPDPROOT=`cat  $HTTPDCONF| awk '/^[\s\t\b]*DocumentRoot / {print $2}'|\
              sed 's/"//g'`
  HTTPDROOT=`echo $HTTPDPROOT|awk '{print $1}'`
  HTTPDPCGI=`cat  $HTTPDCONF| awk '/^[\s\t]*ScriptAlias / {print $3}'|\
             sed 's/"//g'|sed 's/\/$//'`
  HTTPDCGI=`echo $HTTPDPCGI|awk '{print $1}'`
fi


#if ! test $HTTPDUSER; then
#   echo "#EL APACHE NO TIENE USUARIO, estara apagado o no existira?" 
#fi



############################ Solo para pruebas, 
# DIST2 Tomado de infosis.sh (C) Diego Saravia, tambien en http://www.psicro.org

DIST2=`cat /proc/version | awk '\
       /SUSE/     {if (SI!=1) print "SuSE";        SI=1;}\
       /musix/    {if (SI!=1) print "Musix";        SI=1;}\
       /RePortE/  {if (SI!=1) print "UtutoR";      SI=1;}\
       /ututo-xs/ {if (SI!=1) print "UtutoEXS";    SI=1;}\
       /sarge/    {if (SI!=1) print "DebianSarge"; SI=1;}\
       /ututo/    {if (SI!=1) print "Ututo";       SI=1;}\
       /ubuntu/   {if (SI!=1) print "Ubuntu";      SI=1;}\
       /ututo/    {if (SI!=1) print "Ututo";       SI=1;}\
       /Debian/   {if (SI!=1) print "Debian";      SI=1;}\
       /Gentoo/   {if (SI!=1) print "Gentoo";      SI=1;}\
       /linux/    {if (SI!=1) print "GNULinux";    SI=1;}\
       '`

#########################################################
#    DIST Tomado de sysinfo.sh
#    Copyright (C) 2006  Makarand Hazarika
#    You can contact the author at <makarand.hazarika@gmail.com>
#    http://www.novell.com/coolsolutions/tools/17005.html



DIST=`for i in /etc/*[rv]e[lr][es][ai][so][en]
	do 
		if [ -L "$i" ]
		then 
			echo > /dev/null
		else  
			cat "$i"
		fi
	done 2> /dev/null | sed '/LSB/d' | head -n 1`

LINUXDIST=`echo  $DIST |sed  "s/ /\_\_/g"|sed  "s/[()]//g" `

SISTEMAT=`uname -a`
SISTEMA=`uname -s`
LINUXSISTEMA=$SISTEMA
#LINUXSISTEMAUNAME=$SISTEMAT
LINUXDIST2="$DIST2"



echo "# Exporta caracteristicas de la instalación del Apache"

echo HTTPDCONFDEF=$HTTPDCONFDEF
echo CAMBIACAMINO=$CAMBIACAMINO
echo HTTPDSERROOT=$HTTPDSERROOT
echo HTTPDCONFINI=$HTTPDCONFINI
echo HTTPDLEYOCONF=$HTTPDCONF 
echo HTTPDUSR=$HTTPDUSER 
echo HTTPDGRP=$HTTPDGRP
echo HTTPDROOT=$HTTPDROOT
echo HTTPDCGI=$HTTPDCGI
echo LINUXSISTEMA=$LINUXSISTEMA
#echo LINUXSISTEMAUNAME=$LINUXSISTEMAUNAME
echo LINUXDIST2=$LINUXDIST2
echo LINUXDIST=$LINUXDIST

