#!/bin/bash

# Rassemble informations sur le systeme et l'installation ScoDoc pour 
# faciliter le support a distance.
#
# Avec option:
#    -a : sauve aussi les bases de données
#
DEST_ADDRESS=emmanuel.viennet@univ-paris13.fr 

INSTANCE_DIR=/opt/scodoc

TMP=/tmp/scodoc-$(date +%F-%s)

DEPTS_TO_SAVE=""
SAVE_USERS=0
SEND_BY_MAIL=1

# -------------------------------------
# Arguments
# -------------------------------------

function join_by { local IFS="$1"; shift; echo "$*"; }

while getopts ":d:aunh" opt; do
  case $opt in
      a)
	  # Liste des noms des departements, a partir des bases SQL SCO*
	  DEPTS_TO_SAVE=$( (su postgres -c "psql -l") | grep SCO | grep -v SCOUSERS | awk '{ gsub("SCO", "", $1); print $1}' )
	  SAVE_USERS=1
	  ;;
      u)
	  SAVE_USERS=1
	  ;;
      n)
	  SEND_BY_MAIL=0
	  ;;
      d)
	  DEPTS_TO_SAVE=$( join_by ' ' $DEPTS_TO_SAVE $OPTARG )
	  ;;
      h)
	  echo "Diagnostic installation ScoDoc"
	  echo "Rassemble informations sur le systeme et l'installation ScoDoc"
	  echo "Usage: $0 [-h] [-n] [-a] [-u] [-d dept]"
	  echo "  -h  cette aide"
	  echo "  -n  pas d'envoi par mail"
	  echo "  -a  enregistre aussi toutes les bases de donnees"
	  echo "  -u  enregistre la base utilisateurs"
	  echo "  -d dept   enregistre la base du departement dept"
	  exit 0
	  ;;
      \?)
	  echo "Invalid option: -$OPTARG" >&2
	  exit 1
	  ;;
      :)
	  echo "Option -$OPTARG requires an argument." >&2
	  exit 1
	  ;;
  esac
done


# -------------------------------------
# Configuration
# -------------------------------------

# needed for uuencode
if [ ! -e /usr/bin/uuencode ]
then
   apt-get install sharutils
fi

mkdir $TMP

# Files to copy:
FILES="/etc/hosts /etc/debian_version /etc/apt /etc/apache2"


echo "ScoDoc diagnostic: informations about your system will be "
if [ "${SEND_BY_MAIL}" = "1" ]
then
    echo "sent to ${DEST_ADDRESS}"
    echo -n "and "
fi
echo "left in ${TMP}"


# -------------------------------------
# Logs
# -------------------------------------

copy_log() {
 if [ -e $1 ]
 then
   cp $1 $TMP/scodoc_logs/
 fi
}
mkdir $TMP/scodoc_logs/
copy_log /opt/scodoc/instance/log/event.log
copy_log /opt/scodoc/instance/log/event.log.1
copy_log /opt/scodoc/instance/log/notes.log
copy_log /opt/scodoc/instance/log/notes.log.1


# -------------------------------------
# Linux System Configuration
# -------------------------------------

iptables -L > $TMP/iptables.out
ip a > $TMP/ifconfig.out
ps auxww > $TMP/ps.out
df -h > $TMP/df.out
dpkg -l > $TMP/dpkg.lst

(cd /opt/scodoc/instance/Products/ScoDoc; svn status > $TMP/svn.status)
(cd /opt/scodoc/instance/Products/ScoDoc; svn diff > $TMP/svn.diff)

(cd /opt/scodoc/instance/Products/ScoDoc; svnversion >  $TMP/svn.version)
ls -laR /opt/scodoc/instance/Products/ScoDoc > $TMP/ls-laR


# -------------------------------------
# Databases configurations
# -------------------------------------
(su postgres -c "psql -l") > "${TMP}/psql-l.out"
for dept in "${INSTANCE_DIR}"/var/scodoc/config/depts/*.cfg
do
  cnx=$(cat $dept)
  (su postgres -c "echo '\dt' | psql -d $cnx") > "${TMP}/psql-$(basename ${dept%%.*}).out"
done


# -------------------------------------
# Other system configuration files
# -------------------------------------
# copy files:
for f in $FILES 
do 
   cp -R $f $TMP
done


# -------------------------------------
# Optionally save dept(s) database(s)
# -------------------------------------
DEPTS_TO_SAVE=$(echo ${DEPTS_TO_SAVE} | tr ' ' '\n' | sort | uniq)

# Dump database of a dept (eg "RT")
function dump_dept_db {
    dept=$1
    DB=$2
    echo "Dumping database ${DB}..."
    mkdir -p "${TMP}/depts/${dept}"
    chmod -R a+wr "${TMP}/depts/"
    (su postgres -c "pg_dump --create ${DB}") | gzip > "${TMP}/depts/${dept}/${DB}.dump.gz"
    # may add archives ? (but probably too big)
}

for dept in ${DEPTS_TO_SAVE}
do
    dump_dept_db "${dept}" "SCO${dept}"
done


# -------------------------------------
# Optionally saveUSERS db
# -------------------------------------
if [ "${SAVE_USERS}" = "1" ]
then
    dump_dept_db "USERS" "SCOUSERS"
fi


# -------------------------------------
# Archive all stuff to /tmp
# -------------------------------------

tar cfz $TMP.tgz $TMP

echo
echo "Fichier de diagnostic:  $TMP.tgz"
echo

# If no mail, stop here
if [ "${SEND_BY_MAIL}" = "0" ]
then
    exit 0
fi

# -------------------------------------
# Send by e-mail
# -------------------------------------


# Code below found on http://www.zedwood.com/article/103/bash-send-mail-with-an-attachment

#requires: basename,date,md5sum,sed,sendmail,uuencode
function fappend {
    echo "$2">>$1;
}
YYYYMMDD=`date +%Y%m%d`

# CHANGE THESE
TOEMAIL=$DEST_ADDRESS
FREMAIL="scodoc-diagnostic@none.org";
SUBJECT="ScoDoc diagnostic - $YYYYMMDD";
MSGBODY="ScoDoc diagnostic sent by diagnostic.sh";
ATTACHMENT="$TMP.tgz"
MIMETYPE="application/gnutar" #if not sure, use http://www.webmaster-toolkit.com/mime-types.shtml


# DON'T CHANGE ANYTHING BELOW
TMP="/tmp/tmpfil_123"$RANDOM;
BOUNDARY=`date +%s|md5sum`
BOUNDARY=${BOUNDARY:0:32}
FILENAME=`basename $ATTACHMENT`

rm -rf $TMP;
cat $ATTACHMENT|uuencode --base64 $FILENAME>$TMP;
sed -i -e '1,1d' -e '$d' $TMP;#removes first & last lines from $TMP
DATA=`cat $TMP`

rm -rf $TMP;
fappend $TMP "From: $FREMAIL";
fappend $TMP "To: $TOEMAIL";
fappend $TMP "Reply-To: $FREMAIL";
fappend $TMP "Subject: $SUBJECT";
fappend $TMP "Content-Type: multipart/mixed; boundary=\""$BOUNDARY"\"";
fappend $TMP "";
fappend $TMP "This is a MIME formatted message.  If you see this text it means that your";
fappend $TMP "email software does not support MIME formatted messages.";
fappend $TMP "";
fappend $TMP "--$BOUNDARY";
fappend $TMP "Content-Type: text/plain; charset=ISO-8859-1; format=flowed";
fappend $TMP "Content-Transfer-Encoding: 7bit";
fappend $TMP "Content-Disposition: inline";
fappend $TMP "";
fappend $TMP "$MSGBODY";
fappend $TMP "";
fappend $TMP "";
fappend $TMP "--$BOUNDARY";
fappend $TMP "Content-Type: $MIMETYPE; name=\"$FILENAME\"";
fappend $TMP "Content-Transfer-Encoding: base64";
fappend $TMP "Content-Disposition: attachment; filename=\"$FILENAME\";";
fappend $TMP "";
fappend $TMP "$DATA";
fappend $TMP "";
fappend $TMP "";
fappend $TMP "--$BOUNDARY--";
fappend $TMP "";
fappend $TMP "";
#cat $TMP>out.txt
cat $TMP|sendmail -t -f none@example.com;
rm $TMP;

