#!/bin/bash
#################################################################
# Inicio de scripts sumapack.org
# Software Libre bajo la AGPLv3+: http://www.fsf.org/licensing/licenses/gpl.html
# Diego Saravia  dsa@unsa.edu.ar Diego.Saravia@gmail.com
################################################################3



TEMP=$(getopt -o hvs --long help,version -- "$@")

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

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

hacesolo=0;

while true ; do
	case "$1" in
		-h|--help) echo "Help" ; shift ; exit ;;
		-v|--version) echo "Version" ; shift ; exit  ;;
                -s) hacesolo=1; break;;
		--) shift ; break ;;
		*) echo "Bad Parameter!>: $1" ; exit 1 ;;
	esac
done
#echo "Remaining arguments:"
#for arg do echo "--> $arg" ; done
# poner en /usr/bin

#    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, dsa@unsa.edu.ar - INENCO
#    bajo la AGPL 3.0 o superior

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU AFFERO 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 Affero General Public License for more details.

#    You should have received a copy of the GNU Affero 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


NOMBRE=detectahttpd 
# no se bien si es necesario, nombre de script $0 no sirve porque no funciona en autoconf o m4

PRIMLINPSHTTPD=$(ps -eo user,args|grep httpd|grep -v root|grep -v grep  |grep -v "$NOMBRE"|tail -n1)
HTTPDUSER=$(echo $PRIMLINPSHTTPD|awk '{print $ 1}')


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

PRIMLINPSAPACHE=$(ps -eo user,args|grep apache|grep -v root|grep -v grep| grep -v "$NOMBRE"|tail -n1)
HTTPDUSER=$(echo $PRIMLINPSAPACHE|awk '{print $ 1}')


if test x"$HTTPDUSER" != x ; then
   HTTPDGRP=$(ps -eo group,args|grep 'apache'|grep -v 'root'|grep -v 'grep'|grep -v "$NOMBRE"|tail -n1|awk '{print $ 1}')

   PRIMLINPSAPACHE2=$(ps -eo args|grep apache|grep -v root|grep -v grep|grep -v "$NOMBRE"|tail -n1)



   HTTPDCONFINI=$(echo $PRIMLINPSAPACHE2|perl -e '$a=<>;$a=~/-f[\t\s\b]*(\S+)/;\
                                                print $1')
   HTTPDSERROOT=$(echo $PRIMLINPSAPACHE2|perl -e '$a=<>;$a=~/-d[\t\s\b]*(\S+)/;\
                                                print $1')
#echo nnnn2  $PRIMLINPSAPACHE -  $HTTPDSERROOT
fi
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 x"$HTTPDCONFINI" != x; 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
    if test ! -s "$HTTPDCONFINI"; then
      HTTPDCONFINI=''
      HTTPDCONFDEF=''
    fi

fi
#echo "# $CAMINO - $DIRCONF - $HTTPDCONFINI"


###################################3
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"
          if test -e $HP; then
              HTTPDCONF=$HP  
              HTTPDPROOT=$(cat  $HTTPDCONF|\
                          awk '/^( |\t)*DocumentRoot / {print $ 2}'|sed 's/"//g')
	      #echo iii $HTTPDCONF - $HTTPDPROOT 
              if test x"$HTTPDPROOT" != x ; then
                 break 3
	      fi
          fi
       done
   done
done

##########################
if test x"$HTTPDCONF" != x -a -e "$HTTPDCONF" ; then
 # sacado \b
  HTTPDPROOT=$(cat  $HTTPDCONF| awk '/^( |\t)*DocumentRoot / {print $ 2}'|\
              sed 's/"//g')
  # echo UUUU $HTTPDPROOT - $HTTPDCONF

  HTTPDROOT=$(echo $HTTPDPROOT|awk '{print $ 1}')
  HTTPDPCGI=$(cat  $HTTPDCONF| awk '/^( |\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



#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


