#!/bin/sh
###
### Capture a sipXpbx configuration for reporting purposes
###

# Add /sbin to the end of PATH, because often if the user is not
# running as root or if he su'ed to root, /sbin will not be in the
# PATH, and ifconfig can't be found.  But put /sbin at the end of PATH
# in case the user prefers a different ifconfig that is already in the
# PATH.
PATH=$PATH:/sbin

Action=SNAPSHOT
DoWebFiles=YES
SaveCredentials=NO
SaveLogs=YES
DeleteLogs=NO
Tar=YES
ToFile=

DefaultTarFile="sipx-configuration-`hostname -f`.tar.gz"

while [ $# -ne 0 ]
do
    case ${1} in

        -v|--version)
            echo 3.6.0
            exit;
            ;;

        -w|--www)
            DoWebFiles=YES
            ;;

        -nw|--no-www)
            DoWebFiles=NO
            ;;

        -l|--logs)
            SaveLogs=YES
            ;;

        -nl|--no-logs)
            SaveLogs=NO
            ;;

        -c|--credentials)
            SaveCredentials=YES
            ;;

        -i|--info-only)
            Action=INFO
            Tar=NO
            ;;

        -d|--delete-logs)
            SaveLogs=YES
            DeleteLogs=YES
            ;;

        -n|--notar)
            Tar=NO
            ;;

        ##
        ## handle the 'end of options' marker
        ##
        --)
            ;;

        ##
        ## handle an unknown switch
        ##
        -*)
            Action=USAGE
            break
            ;;

        *)
            if [ -z "${ToFile}" ]
            then
                ToFile=${1}
            else
                echo "Too many arguments supplied: $@" 1>&2
                Action=USAGE
                break
            fi
            ;;
    esac

    shift # always consume 1 argument
done

# Set the working file tree.
# Since the destination location may not be able to hold the uncompressed
# data, place it in a recognized temporary location.
Work=${TMPDIR:-/tmp}/sipxcfg.$$
if [ ${Tar} = YES ]
then
  # Set default ToFile if necessary.
  ToFile=${ToFile:-${DefaultTarFile}}
else
  # If Tar = NO, we copy the files directly to their destination.
  Work=${ToFile:-${Work}}
fi

if [ ${Action} = USAGE ]
then
  cat <<USAGE

Usage:

    sipx-snapshot [ -c | --credentials ]
                  [ -nw | --no-www ]
                  [ -nl | --no-logs ]
                  [ -d | --delete-logs ]
                                       [ <tar-file-name> ]

    sipx-snapshot [ -i | --info-only ]

    sipx-snapshot [ -n | --notar ]
                  [ -c | --credentials ]
                  [ -nw | --no-www ]
                  [ -nl | --no-logs ]
                  [ -d | --delete-logs ]
                                       [ <to-directory-name> ]

    Collects important sipXpbx configuration information
    and saves it in a file.  This is used to record configuration
    information to accompany a problem report.

    In the default mode (the first form shown), the output file is a
    gzipped tar file named <tar-file-name>.  The default name is
    '${DefaultTarFile}'.  The tar file contains a text file named
    SystemConfig that describes various system configuration information,
    and the sipXpbx configuration files.

    The second form, with the --info-only switch, only the system
    configuration information is collected; none of the sipXpbx configuration
    files are included, and the output is to standard out.

    The third form, with the --notar switch, prevents the saved files from
    being tar'ed -- they remain in a file tree that mirrors the originals;
    in this case the final argument is the name of the directory where the
    information should be saved.

    By default, all password information is removed from the recorded
    credentials file.  If diagnosing a particular problem requires that the
    real credential information be included, the --credentials switch
    causes it to be left in.

    The --no-www switch disables saving the apache configuration files.

    The --no-logs switch causes the sipX and Apache logs to be omitted
    from the snapshot; the default is to include them.

    The --delete-logs switch deletes the log files after they are included 
    in the snapshot, which is often handy when doing multiple runs to illustrate 
    a problem.  --delete-logs should only be used if sipX is not running.


USAGE
    exit
fi

# Establish the work directory, which will mirror the parts of the
# file system that we are interested in, with $Work correspondign to /.
rm -rf $Work
mkdir  $Work

# File into which to record random system configuration information.
SystemConfig=${Work}/SystemConfig

# Assemble the list of files to record.

# These files are always recorded.
cat > $Work.copy-files <<EOF
/usr/local/etc/sipxpbx/ProcessDefinitions.xml
/usr/local/etc/sipxpbx/WatchDog.xml
/usr/local/etc/sipxpbx/authexception.xml
/usr/local/etc/sipxpbx/authproxy-config
/usr/local/etc/sipxpbx/authproxy-config.in
/usr/local/etc/sipxpbx/authrules.xml
/usr/local/etc/sipxpbx/authrules.xml.in
/usr/local/etc/sipxpbx/callresolver-config
/usr/local/etc/sipxpbx/callresolver-config.in
/usr/local/etc/sipxpbx/config.defs
/usr/local/etc/sipxpbx/destinations.xml
/usr/local/etc/sipxpbx/fallbackrules.xml
/usr/local/etc/sipxpbx/fallbackrules.xml.in
/usr/local/etc/sipxpbx/forwardingrules.xml
/usr/local/etc/sipxpbx/forwardingrules.xml.in
/usr/local/etc/sipxpbx/httpd.conf
/usr/local/etc/sipxpbx/httpd-sipxchange-common-ssl.conf
/usr/local/etc/sipxpbx/httpd-sipxchange-common-ssl.conf.in
/usr/local/etc/sipxpbx/httpd-sipxchange-common.conf
/usr/local/etc/sipxpbx/httpd-sipxchange-common.conf.in
/usr/local/etc/sipxpbx/httpd-sipxchange-configserver.conf
/usr/local/etc/sipxpbx/httpd-sipxchange-configserver.conf.in
/usr/local/etc/sipxpbx/httpd-sipxchange-mediaserver-ssl.conf
/usr/local/etc/sipxpbx/httpd-sipxchange-mediaserver-ssl.conf.in
/usr/local/etc/sipxpbx/httpd-sipxchange-mediaserver.conf
/usr/local/etc/sipxpbx/httpd-sipxchange-mediaserver.conf.in
/usr/local/etc/sipxpbx/mappingrules.xml
/usr/local/etc/sipxpbx/mappingrules.xml.in
/usr/local/etc/sipxpbx/mediaserver-config
/usr/local/etc/sipxpbx/mediaserver-config.in
/usr/local/etc/sipxpbx/orbits.xml
/usr/local/etc/sipxpbx/proxy-config
/usr/local/etc/sipxpbx/proxy-config.in
/usr/local/etc/sipxpbx/registrar-config
/usr/local/etc/sipxpbx/registrar-config.in
/usr/local/etc/sipxpbx/resourcemap.xml
/usr/local/etc/sipxpbx/resourcemap.xml
/usr/local/etc/sipxpbx/security.policy
/usr/local/etc/sipxpbx/sipxconfig.properties.in
/usr/local/etc/sipxpbx/sipxpark-config
/usr/local/etc/sipxpbx/sipxpark-config.in
/usr/local/etc/sipxpbx/sipxpresence-config
/usr/local/etc/sipxpbx/sipxpresence-config.in
/usr/local/etc/sipxpbx/ssl/authorities/*.crt
/usr/local/etc/sipxpbx/ssl/ssl.crt
/usr/local/etc/sipxpbx/ssl/stunnel/stunnel-config
/usr/local/etc/sipxpbx/status-config
/usr/local/etc/sipxpbx/status-config.in
/usr/local/etc/sipxpbx/status-plugin.xml
/usr/local/etc/sipxpbx/status-plugin.xml.in
/usr/local/etc/sipxpbx/statusserver-config-defs.xml
/usr/local/etc/sipxpbx/topology.xml
/usr/local/etc/sipxpbx/voicemail.xml
/usr/local/etc/sipxpbx/voicemail.xml.in
/usr/local/etc/sipxpbx/process.d/keepalive.process.xml
/usr/local/etc/sipxpbx/process.d/sipauthproxy.process.xml
/usr/local/etc/sipxpbx/process.d/sipproxy.process.xml
/usr/local/etc/sipxpbx/process.d/sipregistrar.process.xml
/usr/local/etc/sipxpbx/process.d/sipstatus.process.xml
/usr/local/etc/sipxpbx/process.d/sipxacd.process.xml
/usr/local/etc/sipxpbx/process.d/sipxconfig.process.xml
/usr/local/etc/sipxpbx/process.d/sipxpark.process.xml
/usr/local/etc/sipxpbx/process.d/sipxpresence.process.xml
/usr/local/etc/sipxpbx/process.d/sipXvxml.process.xml
/var/sipxdata/sipdb/alias.xml
/var/sipxdata/sipdb/credential.xml
/var/sipxdata/sipdb/ext_alias.xml
/var/sipxdata/sipdb/caller-alias.xml
/var/sipxdata/sipdb/extension.xml
/var/sipxdata/sipdb/huntgroup.xml
/var/sipxdata/sipdb/permission.xml
/var/sipxdata/sipdb/registration.xml
/var/sipxdata/sipdb/subscription.xml
/etc/host.conf
/etc/resolv.conf
/etc/hosts
/etc/crontab
EOF

# These files are recorded if --logs is specified, and deleted if
# --delete-logs is specified.
if [ ${SaveLogs} = YES ]
then
  cat > $Work.delete-files <<EOF
/var/log/sipxpbx/setup.log
/var/log/sipxpbx/configtest.log
/var/log/sipxpbx/dbmonitor.log
/var/log/sipxpbx/httpd_access_log
/var/log/sipxpbx/httpd_error_log
/var/log/sipxpbx/mediaserver.log
/var/log/sipxpbx/mediaserver_cgi.log
/var/log/sipxpbx/replicationcgi.log
/var/log/sipxpbx/sipauthproxy.log
/var/log/sipxpbx/sipcallresolver.log
/var/log/sipxpbx/sipproxy.log
/var/log/sipxpbx/sipregistrar.log
/var/log/sipxpbx/sipstatus.log
/var/log/sipxpbx/sipxconfig.log
/var/log/sipxpbx/sipxpark.log
/var/log/sipxpbx/sipxpresence.log
/var/log/sipxpbx/sipstunnel.log
/var/log/sipxpbx/vxmlengine.log
/var/log/sipxpbx/watchdog.log
EOF
  cat < $Work.delete-files >> $Work.copy-files
fi

# Record miscellaneous information about the host.

cat /dev/null            > ${SystemConfig}
echo -n "Snapshot:  "   >> ${SystemConfig}
echo $0                 >> ${SystemConfig}
echo ""                 >> ${SystemConfig}
echo -n "Host:      "   >> ${SystemConfig}
hostname                >> ${SystemConfig}
echo ""                 >> ${SystemConfig}
echo -n "Date:      "   >> ${SystemConfig}
date -u                 >> ${SystemConfig}
echo ""                 >> ${SystemConfig}
echo -n "Version:   "   >> ${SystemConfig}
uname -a                >> ${SystemConfig}
if [ -f /etc/redhat-release ]
then
echo ""                 >> ${SystemConfig}
echo "Release:"         >> ${SystemConfig}
cat /etc/redhat-release >> ${SystemConfig}
fi
echo ""                 >> ${SystemConfig}
echo    "sipXpbx User:" >> ${SystemConfig}
grep sipx /etc/passwd >> ${SystemConfig}
echo ""                 >> ${SystemConfig}
echo "SELinux:"                 >> ${SystemConfig}
if selinuxenabled               >> ${SystemConfig} 2>&1
then
    echo -n "   Enabled; mode=" >> ${SystemConfig}
    getenforce                  >> ${SystemConfig}
else
    echo    "   Disabled"       >> ${SystemConfig}
fi 
echo ""                         >> ${SystemConfig}

echo "SSL Configuration:"      >> ${SystemConfig}
ls -lR /usr/local/etc/sipxpbx/ssl/     >> ${SystemConfig}
echo "  Certificate Dump:"     >> ${SystemConfig}
cat /usr/local/etc/sipxpbx/ssl/ssl.crt >> ${SystemConfig}
echo ""

# Get configuration information on sipX components
for component in pbx config proxy registry publisher vxml commserverlib calllib medialib tacklib portlib
do
  echo "" >> ${SystemConfig}
  if test -x /usr/local/bin/sipx${component}-config
  then
      /usr/local/bin/sipx${component}-config --all >> ${SystemConfig}
  else
      echo Missing: /usr/local/bin/sipx${component}-config >>   ${SystemConfig}
  fi
done

# Get version info for key prerequisite packages
for prereq in pcre cgicc glib
do
  echo "" >> ${SystemConfig}
  prereq_version=`${prereq}-config --version 2> /dev/null`
  if test $? -eq 0
  then
      echo -n "$prereq --version : ${prereq_version}" >> ${SystemConfig}
  else
      echo -n "$prereq --version : (not available)" >> ${SystemConfig}
  fi
done

# Get info on installed sipx rpms
for sipName in `rpm -qa --nodigest --nosignature | grep sipx`
do
   echo "" >> ${SystemConfig}
   echo "======== RPM $d" >> ${SystemConfig}
        rpm -qi $sipName     >> ${SystemConfig}
done
echo "======== RPMs" >> ${SystemConfig}
rpm -qa --nodigest --nosignature | sort >> ${SystemConfig}

echo ""       >> ${SystemConfig}
echo ======== ifconfig >> ${SystemConfig}
ifconfig      >> ${SystemConfig}

# Get DNS and hostname information
locale=""
full_host=`hostname --fqdn | tr A-Z a-z`
full_locale=$full_locale

while [ -n "$full_locale" ]
do
    locale="$full_locale $locale"
    full_locale=`echo $full_locale | sed 's/^[^.]*\.//; s/^[^.]*$//'`
done

for d in  rr.$full_host ap.$full_host
do
  echo "" >> ${SystemConfig}
  echo ======== DNS SRV $d >> ${SystemConfig}
  dig -t srv +noidentify +nocmd +nocomments +noquestion +nostats +noauthority _sip._tcp.$d _sip._udp.$d \
  | sort -u -r \
  >> ${SystemConfig}
done

# Get any firewall or other tricky IP manipulations
echo "" >> ${SystemConfig}
echo "======== IPTables:"       >> ${SystemConfig}
for t in nat filter mangle
do
  echo "=== $t table:"            >> ${SystemConfig}
  iptables --table $t --list --verbose --numeric --line-numbers >> ${SystemConfig} 2>&1
done

# Execute system monitoring commands
for command in \
    "ps -efww" \
    "netstat -ap --ip --numeric-hosts" \
    "top n 1 b" \
    "vmstat 5 2" \
    "free" \
    "df"
do
  echo "" >> ${SystemConfig}
  echo ======== $command >> ${SystemConfig}
  $command >> ${SystemConfig} 2>&1
done

# Collect sipX configuration information
echo "" >> ${SystemConfig}

if [ "${Action}" = "SNAPSHOT" ]
then

  # Copy all the files and directories that should be copied.
  for file in `sort -u $Work.copy-files`
  do
    copyFile=`basename ${file}`
    copyDir=${Work}`dirname ${file}`
    if [ -f ${file} ]
    then
      mkdir -p ${copyDir}
      cp --archive ${file} ${copyDir}/${copyFile}
    else
      echo Missing: ${file} >> ${SystemConfig}
    fi
  done

  # Remove the passtokens from credential.xml if we should do so.
  if [ ${SaveCredentials} = NO ]
  then
    for file in `find $Work -name credential.xml`
    do
      mv ${file} ${file}.tmp
      sed < ${file}.tmp > ${file} \
            -e 's|<passtoken>[^<]*</passtoken>|<passtoken>ELIDED</passtoken>|'
      rm ${file}.tmp
    done
  fi
fi

if [ ${Tar} = YES ]
then
  # Tar the entire directory tree and compress it.
  # (Writing this pipe explicitly allows us to use tar's that do not understand
  # the -z option.)
  tar cf - -C ${Work} . | gzip >${ToFile}
  # Remove the temporary files.
  rm -rf $Work

  echo "Configuration saved in '${ToFile}'"

elif [ "${Action}" = "INFO" ]
then
  cat ${SystemConfig}
  echo "(Configuration information is in '${SystemConfig}')"

else
  echo "Configuration saved in '${Work}'"
fi

# Delete the log files, if requested.
if [ ${DeleteLogs} = YES ]
then
  rm $( cat $Work.delete-files )
  echo "Log files deleted"
fi

# Remove the temporary files.
rm -rf $Work.copy-files $Work.delete-files
