#!/usr/bin/env bash
VERSION=8

read -p "Please enter your support case number: " case_number

timestamp=$(date +%F-%H%M)
collection="cfengine_support_case_$case_number-$timestamp"

tmpdir="$(mktemp -d)/$collection"
mkdir -p $tmpdir/system_info

echo "Collecting memory information"
free -m > $tmpdir/system_info/free_memory.txt

echo "Collecting disk free"
df -h > $tmpdir/system_info/disk_free.txt

echo "Collecting process information"
ps auwwx > $tmpdir/system_info/ps.txt

echo "Collecting list of open files"
lsof > $tmpdir/system_info/lsof.txt

echo "Collecting mounted file systems"
mount > $tmpdir/system_info/mount.txt

echo "Collecting cf-key -s output"
cf-key -s > $tmpdir/system_info/cf_key.txt

echo "Collecting fstab"
cp /etc/fstab $tmpdir/system_info/fstab.txt

echo "Collecting sar info for past 25 days"
for i in $(seq 1 25); do
  OUTPUT=$tmpdir/system_info/sar/days_ago/$i
  SALOG="/var/log/sa/sa$(date +%d -d "$i days ago")"
  mkdir -p $OUTPUT
  sar -q -f $SALOG > $OUTPUT/sar_q.txt
  sar -dp -f $SALOG > $OUTPUT/sar_dp.txt
  sar -w -f $SALOG > $OUTPUT/sar_w.txt
  sar -r -f $SALOG > $OUTPUT/sar_r.txt
  sar -P ALL -f $SALOG > $OUTPUT/sar_P_ALL.txt
done

echo "Collecting iostat for 10 minutes, thank you for your patience"
iostat -xk 10 60 > $tmpdir/system_info/iostat_xk_10_60.txt

echo "Collecting database table sizes"
/var/cfengine/bin/psql cfdb -c "SELECT nspname || '.' || relname AS "relation",
    pg_size_pretty(pg_total_relation_size(C.oid)) AS "total_size"
  FROM pg_class C
  LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
  WHERE nspname NOT IN ('pg_catalog', 'information_schema')
  AND C.relkind <> 'i'
  AND nspname !~ '^pg_toast'
  ORDER BY pg_total_relation_size(C.oid) DESC
  LIMIT 20;" > $tmpdir/system_info/postgres_db_table_sizes.txt

echo "Collecting wasted space in database"
/var/cfengine/bin/psql cfdb -c " CREATE VIEW relbloat AS SELECT pg_namespace.nspname, pg_class.relname, pg_class.reltuples, 
pg_class.relpages, rowwidths.avgwidth, ceil(pg_class.reltuples * 
rowwidths.avgwidth::double precision / 
current_setting('block_size'::text)::double precision) AS expectedpages, 
pg_class.relpages::double precision / ceil(pg_class.reltuples * 
rowwidths.avgwidth::double precision / 
current_setting('block_size'::text)::double precision) AS bloat, 
ceil((pg_class.relpages::double precision * 
current_setting('block_size'::text)::double precision - ceil(pg_class.reltuples 
* rowwidths.avgwidth::double precision)) / 1024::double precision) AS wastedspace
    FROM ( SELECT pg_statistic.starelid, sum(pg_statistic.stawidth) AS avgwidth
            FROM pg_statistic
           GROUP BY pg_statistic.starelid) rowwidths
    JOIN pg_class ON rowwidths.starelid = pg_class.oid
    JOIN pg_namespace ON pg_namespace.oid = pg_class.relnamespace
   WHERE pg_class.relpages > 1;"
/var/cfengine/bin/psql cfdb -c "select * from relbloat order by wastedspace desc;" > $tmpdir/system_info/postgres_db_wasted_space.txt



mkdir -p $tmpdir/var/cfengine/state/pg/data
cp /var/cfengine/state/pg/data/postgresql.conf $tmpdir/var/cfengine/state/pg/data

echo "Collecting '/etc/security/limits.conf'"
mkdir -p $tmpdir/etc/security
cp /etc/security/limits.conf $tmpdir/etc/security/

echo "Collecting '/var/cfengine/*runlog*'"
rsync -az /var/cfengine/*runlog* $tmpdir/var/cfengine

echo "Collecting '/var/cfengine/*lmdb*'"
rsync -az /var/cfengine/*lmdb* $tmpdir/var/cfengine

echo "Collecting '/var/cfengine/outputs'"
rsync -az /var/cfengine/outputs $tmpdir/var/cfengine

echo "Collecting '/var/cfengine/state' excluding '/var/cfengine/state/pg'"
rsync -az --exclude pg /var/cfengine/state/ $tmpdir/var/cfengine/state

echo "Collecting '/var/cfengine/httpd/logs'"
rsync -az /var/cfengine/httpd/logs $tmpdir/var/cfengine/httpd/

echo "Collecting '/var/cfengine/httpd/htdocs/application/logs'"
mkdir -p $tmpdir/var/cfengine/httpd/htdocs/application/logs
rsync -az /var/cfengine/httpd/htdocs/application/logs $tmpdir/var/cfengine/httpd/htdocs/application/logs/

echo "Collecting logs: '/var/log/messages', '/var/log/CFEngineHub-Install.log', '/var/log/postgresql.log'"
mkdir -p $tmpdir/var/log
cp /var/log/messages $tmpdir/var/log/messages
cp /var/log/CFEngineHub-Install.log $tmpdir/var/log
cp /var/log/postgresql.log $tmpdir/var/log

echo "Collect list of processes and threads in lastseens readers table"
/var/cfengine/bin/mdb_stat -r -n /var/cfengine/cf_lastseen.lmdb > $tmpdir/cf_lastseen_processes_and_threads_readers.txt

echo "Collecting cpuinfo"
cat /proc/cpuinfo > $tmpdir/system_info/cpuinfo.txt

echo "Collecting current MAXREADERS limit"
/var/cfengine/bin/mdb_stat -n -e /var/cfengine/cf_lastseen.lmdb > $tmpdir/system_info/current_maxreaders_limit.txt

echo "Collecting list of processes and threads in lastseen readres table"
/var/cfengine/bin/mdb_stat -r -n /var/cfengine/cf_lastseen.lmdb > $tmpdir/system_info/current_processes_and_threads_in_lastseen_readers_table.txt

echo "Collecting count of open readers for each process"
/var/cfengine/bin/mdb_stat -r -n /var/cfengine/cf_lastseen.lmdb | sed '1d;$d' | tr -s \  | cut -d\  -f2 | sort -n | xargs -i ps -p '{}' -o comm= | sort | uniq -c > $tmpdir/system_info/count_of_open_readers.txt


read -r -p "Include masterfiles in support submission [Y/n]: " response
case $response in
    [yY][eE][sS]|[yY]|"") 
        echo "Including masterfiles in support submission"
        rsync -az /var/cfengine/masterfiles $tmpdir/var/cfengine
        ;;
    *)
        echo "Not including masterfiles in support submission"
        ;;
esac

tar -czf "$collection.tar.gz" --directory $tmpdir/../ . && rm -rf $tmpdir

echo "Please send $collection.tar.gz to CFEngine support staff."
