#!/bin/bash
#
# Copyright (C) 2004-2021 LLC "Setevye informacionnye sistemy", Russia
#                             ("Network information systems")
# Author: Andrey Nikitin nik-a at mail.ru
#
# 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 2 of the License, or
# (at your option) 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

LANG=C
export LANG

if [ "${DEBUG:-no}" != 'no' ]; then
   set -x
fi

PATH="/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin:/usr/local/sbin"
COLUMNS=120
export PATH COLUMNS

PROGBASE=${0##*/}
MAX_TAIL_LINES=${1:-5000}

if [ -t 1 ]; then
   # stdout is are tty
   echo "Usage: \`$PROGBASE > avreglog.tgz'" 1>&2
   exit 1
fi

# load helpers funcs (global_value_of())
. '/usr/lib/avreg-common/helpers.sh'

atexit() {
   safe_rm_fR "$DIR" "$TMPF" || true
}

have_dir() {
   case "$1" in
   */*) return 0 ;;
   esac
   return 1
}

etc_FILES='apt/sources.list apt/sources.list.d/*.list default/avreg init/avreg-worker.conf init/avreg.conf init.d/avreg X11/xorg.conf cron.d/avreg-unlink cron.d/avregd cron.d/avreg-site debian_version modules modprobe.d/video4linux.conf modprobe.d/v4loop.conf network/interfaces timezone fstab rc.local'
proc_FILES='cmdline cpuinfo devices fb interrupts iomem ioports loadavg mdstat meminfo modules mounts stat uptime version'
log_FILES='dmesg daemon.log kern.log syslog messages mysql/error.log Xorg.0.log apache2/error.log apache2/access.log'

umask 077
DIR=$(mktemp -dt avreg-bug.XXXXXXXX)
TMPF=$(mktemp --tmpdir)
cd "$DIR"

trap atexit EXIT

# log files
mkdir -p 'var/log'
dmesg >'var/log/dmesg_' || true
for logf in $log_FILES; do
   if [ -f "/var/log/$logf" ]; then
      >$TMPF
      if [ -r "/var/log/$logf" ]; then
         tail -n $MAX_TAIL_LINES "/var/log/$logf" >$TMPF
      else
         sudo tail -n $MAX_TAIL_LINES "/var/log/$logf" >$TMPF 2>/dev/null
      fi
      if [ -s "$TMPF" ]; then
         have_dir "$logf" && mkdir -p "var/log/${logf%/*}"
         cat $TMPF >"var/log/$logf"
      fi
   fi
done
>$TMPF

if [ -d '/var/log/avreg' ]; then
   mkdir -p 'var/log/avreg'
   for logf in $(cd /var/log/avreg 2>/dev/null && ls *.err *.log 2>/dev/null); do
      if [ -r "/var/log/avreg/$logf" ]; then
         tail -n $MAX_TAIL_LINES "/var/log/avreg/$logf" >"var/log/avreg/$logf"
      else
         sudo tail -n $MAX_TAIL_LINES "/var/log/avreg/$logf" >"var/log/avreg/$logf"
      fi
   done
fi

# static files
for m in etc proc; do
   a=$(eval "echo \$${m}_FILES")
   [ -d "$m" ] || mkdir "$m"
   for p in $a; do
      case "$p" in
      */*) cp -f --parents $(echo /$m/$p) "./" 2>/dev/null ;;
      *) cp -f "/$m/$p" "$m/" 2>/dev/null ;;
      esac
   done
done

# systemd init
if [ -d '/run/systemd/system' -a -x "$(which systemctl 2>/dev/null)" ]; then
   touch systemd
   echo '********************************' >>systemd
   echo "list-unit-files\n" >>systemd
   systemctl list-unit-files >>systemd 2>/dev/null
   echo '********************************' >>systemd
   echo "\n\nlist-units 'avreg*'\n" >>systemd
   systemctl list-units 'avreg*' >>systemd 2>/dev/null
   echo '********************************' >>systemd
   echo "\n\nshow avreg*" >>systemd
   systemctl show 'avreg*' >>systemd 2>/dev/null
fi

# sys programs
if [ -x "$(which lspci 2>/dev/null)" ]; then
   lspci >lspci
   lspci -vvv >>lspci
fi

uname -a >uname
if [ -x "$(which lsb_release 2>/dev/null)" ]; then
   lsb_release -a >lsb_release 2>/dev/null
fi

if [ -x "$(which ip 2>/dev/null)" ]; then
   ip addr >ip
   ip route >>ip
fi
if [ -x "$(which ifconfig 2>/dev/null)" ]; then
   ifconfig >ifconfig
fi
if [ -x "$(which netstat 2>/dev/null)" ]; then
   netstat -r --numeric-hosts >netstat
   netstat -i --numeric-hosts >>netstat
   netstat --tcp --udp --listen --numeric-hosts >>netstat
fi
if [ -x "$(which ss 2>/dev/null)" ]; then
   ss -ltpn >ss.tcp.listen.txt
fi
if [ -x "$(which hostname 2>/dev/null)" ]; then
   >hostname
   for k in 'domain' 'fqdn' 'short' 'alias' 'ip-address'; do
      printf "\$ hostname --$k\n" >>hostname
      hostname "--$k" >>hostname
   done
fi

top -bcn1 >top
free >free
df -hTP >df
date -R >date
zdump /etc/localtime >localtime
env >env

echo -ne "LONG_BIT\t" >getconf
getconf LONG_BIT >>getconf
echo -ne "GNU_LIBC_VERSION\t" >>getconf
getconf GNU_LIBC_VERSION >>getconf
echo -ne "PATH_MAX\t" >>getconf
getconf PATH_MAX / >>getconf
echo -ne "PIPE_BUF\t" >>getconf
getconf PIPE_BUF / >>getconf
echo -ne "PATH_MAX\t" >>getconf
getconf PAGESIZE >>getconf
echo -ne "CLK_TCK\t" >>getconf
getconf CLK_TCK >>getconf

mkdir -p 'dev/video'
ls -l /dev/video* >'dev/video/ls.video' 2>/dev/null
if [ -x "$(which v4l2-ctl 2>/dev/null)" ]; then
   for p in $(cd '/dev' && ls video* 2>/dev/null); do
      if [ -r "/dev/$p" ]; then
         v4l2-ctl --all -lL -nN --list-standards -P --list-formats-ext -V -d "/dev/$p" >"dev/video/$p" 2>&1
      fi
   done
fi

# AVReg conf
mkdir -p 'etc/avreg'
dpkg -l '*avreg*' 'v4loop*' 'ruby*' 'php*' 'apache*' 2>/dev/null | grep -v '^un' >'etc/avreg/dpkg.avreg'

# ls
>etc/avreg/ls
for p in /etc/avreg \
   /etc/avreg/profiles \
   /etc/avreg/scripts \
   /var/run/avreg \
   /var/lib/avreg/masks \
   /var/spool/avreg \
   /var/lock/avreg; do
   ls -dlAF $p >>'etc/avreg/ls'
   ls -lAF $p >>'etc/avreg/ls'
   echo >>'etc/avreg/ls'
done

# key
active_key="$(global_value_of 'key' '/etc/avreg/avreg.conf')"
if [ -e "$active_key" ]; then
   keybasename="${active_key##*/}"
   if [ -r "$active_key" ]; then
      grep -v '^key_ver5_part2' "$active_key" >"etc/avreg/$keybasename"
   else
      echo "sudo tail -n 50 $active_key > etc/avreg/$keybasename" 1>&2
      sudo tail -n 50 "$active_key" |
         grep -v '^key_ver5_part2' "$active_key" >"etc/avreg/$keybasename"
   fi
fi

for p in site-apache2.conf site-apache2-user.conf site-defaults.php; do
   case "$p" in
   */*) cp -f --parents "/etc/avreg/$p" . ;;
   *) cp -f "/etc/avreg/$p" 'etc/avreg/' ;;
   esac
done

for dir_pref in /etc/php/*; do
   for instance in apache2 cli; do
      if [ -r "$dir_pref/$instance/php.ini" ]; then
         php --php-ini "$dir_pref/$instance/php.ini" -r 'phpinfo();' >etc/avreg/phpinfo.$instance
      fi
   done
done

update-avreg.conf print --strict >etc/avreg/avreg.conf
if [ -d '/etc/avreg/profiles' ]; then
   mkdir etc/avreg/profiles
   for p in $(cd '/etc/avreg/profiles' && ls [A-Za-z0-9][A-Za-z0-9_-:]* 2>/dev/null); do
      update-avreg.conf -c "/etc/avreg/profiles/$p" print --strict >"etc/avreg/profiles/$p"
   done
fi

# databases

DB_PARAMS='db-type db-host db-port db-name'
DB_PARAMS_SHELL='db_type db_host db_port db_name'

# define global AVReg variables + db_admin and db_admpass
for p in $DB_PARAMS_SHELL 'db_admin' 'db_admpass'; do
   eval "$p="
done

# load global AVReg variables which are set by avreg.conf
if [ -r '/etc/avreg/avreg.conf' ]; then
   for p in $DB_PARAMS; do
      v=$(global_value_of "$p" '/etc/avreg/avreg.conf')
      if [ -n "$v" ]; then
         p1=$(echo $p | tr '-' '_')
         eval "$p1='$v'"
      fi
   done
fi

[ -z "$db_type" ] && db_type='mysql'
[ -z "$db_name" ] && db_name='avreg6_db'

. "/usr/lib/avreg-common/${db_type}"
trap "${db_type}_atexit;atexit" EXIT

if [ -t 0 ]; then
   # stdin is are tty = interactive
   echo -n 'enter your database admin name: ' 1>&2
   read db_admin
   echo -n 'enter your database admin password: ' 1>&2
   read dbadm_pass
elif [ -r '/etc/avreg/avreg-site.secret' ]; then
   db_admin="$(global_value_of 'db-user' '/etc/avreg/avreg-site.secret')"
   dbadm_pass="$(global_value_of 'db-passwd' '/etc/avreg/avreg-site.secret')"
   if [ -z "$db_admin" -o -z "$dbadm_pass" ]; then
      echo "ERROR: Invalid or empty \`db-user' or \`db-passwd' options in file \`/etc/avreg/avreg-site.secret'" 1>&2
   fi
else
   echo "Could't obtain \`db_admin' and/or \`db_admin'" 1>&2
fi

if ${db_type}_prepare_client "$db_host" "$db_port" "$db_admin" "$dbadm_pass" 2>/dev/null; then
   # AVREG_DBS=$(${db_type}_list_database_like 'avreg_\_db%' || true)
   db_exist=$(${db_type}_check_db_exist "$db_name")

   if [ "$db_exist" = 'yes' ]; then
      mkdir database
      if [ "${db_type}" = 'mysql' ]; then
         ${db_type}_exec_sql "$db_name" >"database/$db_name" <<EOF
set names 'utf8' collate 'utf8_general_ci';
show table status\G
select CAM_NR, PARNAME, PARVAL from CAMERAS where PARVAL is not null and PARVAL <> '' ORDER BY CAM_NR, PARNAME;
select * from USERS;
select * from LOCAL_LAYOUTS;
select * from WEB_LAYOUTS;
show status;
show variables;
EOF
      else
         ${db_type}_exec_sql "$db_name" >"database/$db_name" <<EOF
set names 'utf8';
select CAM_NR, PARNAME, PARVAL from CAMERAS where PARVAL is not null and PARVAL <> '' ORDER BY CAM_NR, PARNAME;
select * from USERS;
select * from LOCAL_LAYOUTS;
select * from WEB_LAYOUTS;
EOF
      fi
   fi
fi

# tar
tar -cz './'
ret=$?

exit $ret
