#!/bin/bash
#
# avreg-restore - script to restore AVReg configuration
#
# Version 6.3p12 at May 2021
#
# Usage: sudo avreg-restore path/to/backup.tgz
#
# Help: avreg-restore --help or man avreg-restore
#
# Copyright: 2021 (C) "Setevye informatsionnye sistemy", Ltd
#                     "Network Information Systems", Ltd
#
# Report bugs: support@avreg.net
#
# TODO:
#  - restore /var/lib/avreg/* with right mode
#  - avreg-common: local_layouts_6_3_10_ORDER=... local_layouts_6_3_10_COLUMNS

set -e

LANG=C
export LANG

VERSION='6.3'

OPT_BEQUIET='no'
OPT_EXCLUDES=
OPT_REMOVE_ARCHIVE='no'
OPT_FORCE='no'
OPT_SKIP_ALL='no'
OPT_SKIP_PROFILES='no'
OPT_SKIP_APT='no'
OPT_SKIP_VARLIB='no'
OPT_LOCK_TABLES='no'
OPT_DROP_DATABASE='no'
OPT_DO_STOP_AVREG='no'
OPT_DO_START_AVREG='no'
OPT_AVREG_CONF='/etc/avreg/avreg.conf'
OPT_UPGRADE_CONF='no'
OPT_UPGRADE_AVREG_SERVER='no'
OPT_MIGRATE='no'

APT_UPDATE='env DEBIAN_FRONTEND=noninteractive apt -y -qq update'
APT_INSTALL='env DEBIAN_FRONTEND=noninteractive apt -y -qq install'

PGSQL_CSV_OPTIONS="DELIMITER ',' NULL '\N' CSV  QUOTE '\"' ESCAPE '\'"
MYSQL_CSV_OPTIONS="FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' ESCAPED BY '\\\' LINES TERMINATED BY '\n'"

DB_PARAMS='db-type db-host db-port db-name'
PARAMS="server-name $DB_PARAMS storage-dir user group"
SQLDIR="/usr/share/avreg-common/sql"
CUR_AVREG_COMMON_VER="$(dpkg-query -W -f='${Version}' avreg-common)"
CUR_AVREG_MAJOR_VER="${CUR_AVREG_COMMON_VER%%\.*}"
DEF_DB_NAME="avreg${CUR_AVREG_MAJOR_VER}_db"
CONF_TABLES='cameras users web_layouts local_layouts'
DATA_TABLES='events tree_events'
ALL_TABLES="$CONF_TABLES $DATA_TABLES"
DB_USERS='avregd avreg-site avreg-unlink avreg-mon'
TABLES=
SCRIPTNAME="$(basename $0)"
PROFILESDIR='/etc/avreg/profiles'
BACKUP_ARCHIVE_ARG=
TMPDIR="${TMP:-/tmp}"
CHKSUM='sha1sum'
FSQL=
BACKUP_DIR=
if [ -r '/etc/astra_version' -a -x '/usr/bin/pdp-id' ]; then
   ASTRA_SE_VER="$(sed -n 's/[^0-9]*\b\([0-9\.]\+\)\b[^0-9]*/\1/p' /etc/astra_version 2>/dev/null || true)"
else
   ASTRA_SE_VER=
fi
local_layouts_COLUMNS='bind_mac,display,mon_nr,mon_type,mon_name,is_default,win1,win2,win3,win4,win5,win6,win7,win8,win9,win10,win11,win12,win13,win14,win15,win16,win17,win18,win19,win20,win21,win22,win23,win24,win25,win26,win27,win28,win29,win30,win31,win32,win33,win34,win35,win36,win37,win38,win39,win40,win41,win42,win43,win44,win45,win46,win47,win48,win49,win50,win51,win52,win53,win54,win55,win56,win57,win58,win59,win60,change_host,change_user,change_time'

HAVE_AVREGD='no'
# AVREGD_RUNNING_NOW='no'
HAVE_APACHE2='no'

### if MYSQL @@secure_file_priv used.
# variable of @@secure_file_priv
MYSQL_LOAD_DIR=
# prefix to filename for dumps: ${MYSQL_LOAD_DIR}/${MYSQL_SECURE_FILE_PREFIX}_cameras.sql
# MUST BE empty if secure_file_priv not used
MYSQL_SECURE_FILE_PREFIX=
RANDOM_LENGTH=11

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

avreg_restore_cleanup() {
   local return_value=$?
   safe_rm_fR "$FSQL" "$BACKUP_DIR"

   if [ -n "$MYSQL_SECURE_FILE_PREFIX" ]; then
      rm ${MYSQL_LOAD_DIR}/${MYSQL_SECURE_FILE_PREFIX}*.csv 2>/dev/null
   fi

   exit $return_value
}

Usage() {
   cat >&2 <<-__EOF__
Usage: sudo ${SCRIPTNAME} [OPTIONS] BACKUP_ARCHIVE_ARG

Options:
  database access options:
    -T, --db-type=SQLTYPE     SQL server type: "mysql" or "pgsql",
                              default "mysql".
    -H, --db-host=HOST        SQL server hostname, default <empty>(=local).
    -N, --db-name=DBNAME      Database name, default "$DEF_DB_NAME"
    -U, --db-user=USER        Database user name, default <empty>.
    -P, --db-passwd=PASSWORD  Database user password, default <empty>.

   data options:
    -E, --skip-tables=LIST    List of excluded of tables to backup

    --skip-profiles           Exclude /etc/avreg/profiles/* avregd
                              sub-config files.
    --skip-varlib             Do not restore /var/lib/avreg.
    --skip-all                Do not restore any tables, files and profiles.
    --remove-archive          Truncate "events,tree_events" tables
                              and remove all media files into \$storage-dir.
    -f, --force               Ignore src/target avreg-common version mismatch.

  common options:
    -c, --conf=PATH           Path of config file, default
                              "${OPT_AVREG_CONF}".

    -L, --lock-tables         Lock tables.

    --drop-database           Drop target database and sql-users
                              before restoring data.
    --upgrade-conf            Upgrade avreg.conf with new target db-* values.
    --upgrade-avreg-server    Do apt install avreg-server-{DBNAME}.
    -M, --migrate             As --upgrade-conf --upgrade-avreg-server both.

    -q, --quiet               Be quiet.
    -h, --help                Print usage help and exit.
    -V, --version             Print version and exit.

Examples:
sudo ${SCRIPTNAME}
   local full backup with EVENTS table data

sudo ${SCRIPTNAME} -T pgsql -H 1.2.3.4 -U sqlrootuser -P sqlpassword --exclude-profiles
   remote backup, only conf tables, PostgreSQL server on 1.2.3.4 host
__EOF__
}

# Note that we use `"$@"' to let each command-line parameter expand to a
# separate word. The quotes around `$@' are essential!
# We need TEST as the `eval set --' would nuke the return value of getopt.
LONG_ARGS='quiet,help,version,conf:,\
db-type:,db-host:,db-name:,db-user:,db-passwd:,\
skip-tables:,lock-tables,skip-profiles,skip-all,\
remove-archive,force,\
drop-database,\
migrate,upgrade-conf,upgrade-avreg-server,
start-avreg,stop-avreg'

set +e
TEST=$(getopt -o 'qhVc:T:H:N:U:P:E:LMf' --longoptions "$LONG_ARGS" -n "${SCRIPTNAME}" -- "$@")
if [ $? -ne 0 ]; then
   Usage
   exit 1
fi
set -e

# Note the quotes around `$TEST': they are essential!
eval set -- "$TEST"

pos=0
while [ -n "$*" ]; do
   # echo "cmdopt[$pos]($#) = \"$1\""
   case "$1" in
   '-V' | '--version')
      echo "${SCRIPTNAME} $VERSION"
      exit 0
      ;;
   '-h' | '--help')
      Usage
      exit 0
      ;;
   '-q' | '--quiet')
      OPT_BEQUIET='no'
      shift
      ;;
   '-c' | '--conf')
      OPT_AVREG_CONF="$2"
      shift 2
      ;;
   '-T' | '--db-type')
      db_type="$2"
      shift 2
      ;;
   '-H' | '--db-host')
      db_host="$2"
      shift 2
      ;;
   '-N' | '--db-name')
      db_name="$2"
      shift 2
      ;;
   '-U' | '--db-user')
      db_user="$2"
      shift 2
      ;;
   '-P' | '--db-passwd')
      db_passwd="$2"
      shift 2
      ;;
   '-I' | '--include-tables')
      OPT_INCLUDES=$(echo $2 | tr [:upper:] [:lower:] | tr ',' ' ')
      shift 2
      ;;
   '-E' | '--skip-tables')
      OPT_EXCLUDES=$(echo $2 | tr [:upper:] [:lower:] | tr ',' ' ')
      shift 2
      ;;
   '-L' | '--lock-tables')
      OPT_LOCK_TABLES='yes'
      shift
      ;;
   '--skip-profiles')
      OPT_SKIP_PROFILES='yes'
      shift
      ;;
   '--skip-profiles')
      OPT_SKIP_VARLIB='yes'
      shift
      ;;
   '--skip-all')
      OPT_SKIP_ALL='yes'
      shift
      ;;
   '--drop-database')
      OPT_DROP_DATABASE='yes'
      shift
      ;;
   '--remove-archive')
      OPT_REMOVE_ARCHIVE='yes'
      shift
      ;;
   '-f' | '--force')
      OPT_FORCE='yes'
      shift
      ;;
   '--upgrade-conf')
      OPT_UPGRADE_CONF='yes'
      shift
      ;;
   '--upgrade-avreg-server')
      OPT_UPGRADE_AVREG_SERVER='yes'
      shift
      ;;
   '-M' | '--migrate')
      OPT_MIGRATE='yes'
      shift
      ;;
   '--stop-avreg')
      OPT_DO_STOP_AVREG='yes'
      shift
      ;;
   '--start-avreg')
      OPT_DO_START_AVREG='yes'
      shift
      ;;
   '--') shift ;;
   *)
      case "$pos" in
      0)
         BACKUP_ARCHIVE_ARG="$1"
         shift
         ;;
      *)
         Usage "Ambiguous option \"$1\""
         exit 1
         ;;
      esac
      pos=$(($pos + 1))
      ;;
   esac
done

if [ "$OPT_MIGRATE" = 'yes' ]; then
   OPT_UPGRADE_CONF='yes'
   OPT_UPGRADE_AVREG_SERVER='yes'
fi

mysql_install_server() {
   if ! test -x "$(which mysqld)"; then
      $APT_INSTALL 'default-mysql-server'
   fi
}

mysql_install_client() {
   if ! test -x "$(which mysql)"; then
      $APT_INSTALL 'default-mysql-client'
   fi
}

pgsql_install_server() {
   if ! test -x "$(which pg_ctlcluster)"; then
      $APT_INSTALL 'postgresql'
   fi
}

pgsql_install_client() {
   if ! test -x "$(which psql)"; then
      $APT_INSTALL 'postgresql-client'
   fi
}

mysql_get_restore_sql() {
   local out_path_prefix="$1" f= t= T= upd_tables_cnt= csvf=

   upd_tables_cnt=0
   for f in ${out_path_prefix}*.csv
   do
      if [ -s "${f}" ]; then
         csvf=${f##*/}
         tfilebase="${csvf%\.csv}"
         t=${tfilebase#$MYSQL_SECURE_FILE_PREFIX}
         if echo "$ALL_TABLES" | grep -qw "${t}"; then
            T="$(echo ${t} | tr [:lower:] [:upper:])"
            if [ -s "${out_path_prefix}${t}.csv" ]; then
               upd_tables_cnt=$((upd_tables_cnt + 1))
               UPDATED_TABLES="$UPDATED_TABLES ${t}"
               cat <<__EOF__
LOCK TABLES ${T} WRITE;
TRUNCATE ${T};
LOAD DATA INFILE '${f}' INTO TABLE ${T} $MYSQL_CSV_OPTIONS;

__EOF__
            fi
         fi
      fi
   done

   if [ -n "$UPDATED_TABLES" ]; then
      UPDATED_TABLES=$(echo "$UPDATED_TABLES" | xargs)
   fi

   if [ "$OPT_REMOVE_ARCHIVE" = 'yes' ]; then
      if echo "$UPDATED_TABLES" | grep -qvw 'events'; then
         cat <<__EOF__
LOCK TABLES EVENTS WRITE, TREE_EVENTS WRITE;
TRUNCATE EVENTS;
TRUNCATE TREE_EVENTS;
__EOF__
      fi
   fi

   if [ $upd_tables_cnt -gt 0 ]; then
      echo 'UNLOCK TABLES;'
   fi
}

pgsql_get_restore_sql() {
   local out_path_prefix="$1" f= t= T= upd_tables_cnt= csvf= cols=

   upd_tables_cnt=0
   if [ "$OPT_SKIP_ALL" = 'no' ]; then
      for f in ${out_path_prefix}*.csv
      do
         if [ -s "${f}" ]; then
            csvf=${f##*/}
            t="${csvf%\.csv}"
            if echo "$ALL_TABLES" | grep -qw "${t}" && echo "${OPT_EXCLUDES:-x}" | grep -qwv "${t}"; then
               upd_tables_cnt=$((upd_tables_cnt + 1))
               UPDATED_TABLES="$UPDATED_TABLES ${t}"
            fi
         fi
      done
   fi

   if [ -n "$UPDATED_TABLES" ]; then
      UPDATED_TABLES=$(echo "$UPDATED_TABLES" | xargs)
   fi

   echo 'BEGIN;'

   if [ $upd_tables_cnt -gt 0 ]; then
      cat <<__EOF__
LOCK TABLE $(echo $UPDATED_TABLES | tr ' ' ',') IN ROW EXCLUSIVE MODE;
__EOF__

      for t in $UPDATED_TABLES; do
         cols=$(get_var_val "${t}_COLUMNS")
         echo "TRUNCATE ${t};"
         if [ -n "$cols" ]; then
            cat <<__EOF__
COPY ${t} ($cols) FROM '${out_path_prefix}${t}.csv' $PGSQL_CSV_OPTIONS;
__EOF__
         else
            cat <<__EOF__
COPY ${t} FROM '${out_path_prefix}${t}.csv' $PGSQL_CSV_OPTIONS;
__EOF__
         fi
      done
   fi

   if [ "$OPT_REMOVE_ARCHIVE" = 'yes' ]; then
      if echo "$UPDATED_TABLES" | grep -qvw 'events'; then
         cat <<__EOF__
LOCK LOCK TABLE events,tree_events IN ROW EXCLUSIVE MODE;
TRUNCATE events;
TRUNCATE tree_events;
__EOF__
      fi
   fi

   echo 'COMMIT;'
}

# Astra SE Linux specific
create_real_user_for_db_access() {
   ulogin="$1"

   if getent passwd "$ulogin" >/dev/null; then
      return
   fi

   adduser \
      --disabled-login \
      --ingroup 'nogroup' \
      --no-create-home --home '/nonexisten' \
      --gecos 'for AVReg database access' \
      --shell '/bin/false' \
      "$ulogin" >/dev/null

   usermod --lock "$ulogin" >/dev/null

   if [ -n "$ASTRA_SE_VER" ]; then
      usermac -z "$ulogin" >/dev/null || true
   fi
}

create_update_sql_users() {
   # add AVReg applications user/passwd for avreg6_db access
   # TODO move pass/grant to each application
   local f= prog= prog_db_user= passwd= og= fp= new_users=

   # + Astra SE specific
   # create database user's (sql+system) accounts and
   # and initialize MAC attr for system users ( usermac --zero )
   for prog in $DB_USERS; do
      f="/etc/avreg/${prog}.secret"

      if [ -s "${f}" ]; then
         prog_db_user=$(global_value_of 'db-user' "${f}")
         prog_db_passwd=$(global_value_of 'db-passwd' "${f}")

         if [ -z "$prog_db_user" -a -z "$prog_db_passwd" ]; then
            log_error "invalid or empty \"db-user\" or \"db-passwd\" options in file \"${f}\""
         fi

         if [ ! "$prog" = "$prog_db_user" ]; then
            log_warn "db-user for prog \"$prog\" RECOMMEND \"$prog\", but \"$name\" in file \"${f}\""
         fi
      else
         prog_db_user="$prog"
         # генерируем случайный пароль
         prog_db_passwd=$(perl -e 'print map{("a".."z","A".."Z",0..9,"_","-")[int(rand(64))]}(1..28); print "Gr7_"')

         # create secret files
         case "$prog_db_user" in
         'avregd')
            fp='0640'
            og='root:avreg'
            ;;
         'avreg-unlink')
            fp='0600'
            og='root:root'
            ;;
         'avreg-mon')
            fp='0640'
            og='root:video'
            ;;
         'avreg-site')
            fp='0640'
            og='root:www-data'
            ;;
         esac

         # create secret files
         rm -f "${f}" 2>/dev/null
         echo "### $prog database connect options ###" >"${f}"
         echo "# (!) file right must be $fp $og" >>"${f}"
         echo >>"${f}"
         echo "db-user = '${prog_db_user}'" >>"${f}"
         echo "db-passwd = '${prog_db_passwd}'" >>"${f}"
         chown "$og" "${f}"
         chmod $fp "${f}"
      fi

      # Astra SE specific
      if [ -n "$ASTRA_SE_VER" ]; then
         create_real_user_for_db_access "$prog"
      fi

      # create "true" database users
      ${db_type}_create_user "$prog_db_user" "$prog_db_passwd" >/dev/null

      new_users="$new_users $prog"
   done

   if [ -n "$new_users" ]; then
      if [ -n "$ASTRA_SE_VER" ]; then
         user_types='sql+system'
      else
         user_types='sql'
      fi
      log "create ($user_types) users to AVReg database access: [$(echo $new_users | xargs | tr ' ' ',')]"
   fi
}

if [ ! -r "${OPT_AVREG_CONF}" -o ! -r '/usr/lib/avreg-common/helpers.sh' ]; then
   Usage 'required "avreg-common" package is not istalled'
   exit 2
fi

. '/usr/lib/avreg-common/helpers.sh'

if is_execs_exist avregd 'avreg-service'; then
   HAVE_AVREGD='yes'
fi
if is_execs_exist apache2; then
   HAVE_APACHE2='yes'
fi

if [ ! -r "${BACKUP_ARCHIVE_ARG}" ]; then
   log_error "backup archive \"$BACKUP_ARCHIVE_ARG\" is not exist or readable"
   exit 2
fi

DB_PARAMS='db-type db-host db-port db-name'
PARAMS="server-name $DB_PARAMS storage-dir user group"
PARAMS_SHELL="$(echo ${PARAMS} | tr '-' '_')"

parse_avreg_conf $PARAMS

[ -z "$db_type" ] && db_type='mysql'
[ -z "$db_name" ] && db_name="$DEF_DB_NAME"
[ -z "$storage_dir" ] && storage_dir='/var/spool/avreg'

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

if is_localhost "$db_host"; then
   ${db_type}_install_server
fi
${db_type}_install_client

${db_type}_prepare_client "$db_host" "$db_port" "$db_admin" "$db_admpass"

# XXX must before create-db
AVREG_DBS=$(${db_type}_list_database_like 'avreg_\_db%' | xargs || true)

trap '${db_type}_atexit; avreg_restore_cleanup' EXIT

FSQL="$(mktemp $TMPDIR/${db_name}.${db_type}.XXXXXX.sql)"
BACKUP_DIR="$(mktemp -d $TMPDIR/avreg_backup.XXXXXX)"
chmod a+r "$FSQL"
chmod a+rx "$BACKUP_DIR"

tar xzf "$BACKUP_ARCHIVE_ARG" -C "$BACKUP_DIR"

if [ ! -r "$BACKUP_DIR/.meta" -o ! -d "$BACKUP_DIR/database" ]; then
   log_error "file \"$BACKUP_ARCHIVE_ARG\" is not AVReg backup archive"
   exit 1
fi

. "$BACKUP_DIR/.meta"

if [ ! "x$backup_avreg_common_ver" = "x$CUR_AVREG_COMMON_VER" ]; then
   if [ "$OPT_FORCE" = 'yes' ]; then
      log_warn "AVReg version mismatch: \"$CUR_AVREG_COMMON_VER\" (target) != \"$backup_avreg_common_ver\" (source). Ignore by --force opt"
   else
      log_error "AVReg version mismatch: \"$CUR_AVREG_COMMON_VER\" (target) != \"$backup_avreg_common_ver\" (source). Exiting w/o --force opt..."
      exit 1
   fi
fi

log "check $backup_checksum_fn"
(
   cd $BACKUP_DIR
   if ! $backup_checksum_fn --status -c .${backup_checksum_fn}s; then
      log_error "checksums mismatch"
      exit 1
   fi
)

if [ -n "$AVREG_DBS" -a "$OPT_DROP_DATABASE" = 'yes' ] && echo "$AVREG_DBS" | grep -qw "$db_name"; then
   log "drop ${db_type} database \"$db_name\""
   echo "DROP DATABASE $(${db_type}_safe_db_name $db_name)" | ${db_type}_exec_sql >/dev/null

   log "drop sql user's accounts"
   for dbu in $DB_USERS; do
      ${db_type}_drop_user "$dbu" || true
   done

   # important
   AVREG_DBS=
fi

if [ -z "$AVREG_DBS" ] || echo "$AVREG_DBS" | grep -qwv "$db_name"; then
   # Need to create database
   log "create and populate ${db_type} database \"$db_name\"" >&2
   sed "s/$DEF_DB_NAME/$db_name/" "$SQLDIR/create-db/${db_type}.sql" | ${db_type}_exec_sql >/dev/null
   ${db_type}_exec_sql "$db_name" "$SQLDIR/create-tables/${db_type}.sql" >/dev/null
   ${db_type}_exec_sql "$db_name" "$SQLDIR/load-defaults-data/${db_type}.sql" >/dev/null

   create_update_sql_users

   if [ -s "$SQLDIR/grants/${db_type}.sql" ]; then
      log "set/change users GRANT" >&2
      ${db_type}_exec_sql "$db_name" "$SQLDIR/grants/${db_type}.sql" >/dev/null
   fi
fi

csv_indir_prefix="$BACKUP_DIR/database/"
if [ "$db_type" = 'mysql' ]; then
   msd=$(echo 'select @@secure_file_priv' | ${db_type}_exec_sql 2>/dev/null)
   if [ -n "$msd" -a -d "$msd" ]; then
      MYSQL_LOAD_DIR=${msd%/}
      MYSQL_SECURE_FILE_PREFIX=$(get_random_string $RANDOM_LENGTH ; echo -n -)
      csv_indir_prefix="$MYSQL_LOAD_DIR/$MYSQL_SECURE_FILE_PREFIX"

      # MySQL and @@secure_file_priv is not empty.
      for csv_orig_file in "$BACKUP_DIR/database/"*
      do
         if [ -s "$csv_orig_file" ]; then
            csv_target_name="${csv_orig_file##*/}"
            mv "$csv_orig_file" "$MYSQL_LOAD_DIR/${MYSQL_SECURE_FILE_PREFIX}${csv_target_name}"
         fi
      done
   fi
fi

${db_type}_get_restore_sql "$csv_indir_prefix" >"$FSQL"

if [ "$HAVE_AVREGD" = 'yes' ]; then
   log "stop AVReg service"
   sudo avreg-service stop
fi
if [ "$HAVE_APACHE2" = 'yes' ]; then
   log "stop Apache2 service"
   sudo service apache2 stop
fi

#cat "$FSQL"
log "replace [$(echo $UPDATED_TABLES | tr ' ' ',')] tables in \"${db_name}\" database (${db_type})"
${db_type}_exec_sql "${db_name}" "${FSQL}" >/dev/null

if [ "$OPT_REMOVE_ARCHIVE" = 'yes' ]; then
   log "remove AVReg media archive and truncate events and cache db-tables"
   safe_rm_fR "$storage_dir"/*
fi

if [ "$OPT_SKIP_PROFILES" = 'no' -a -d "$BACKUP_DIR/profiles" ] &&
     ! is_empty_dir "$BACKUP_DIR/profiles"
then
   log 'replace avregd profiles'
   safe_rm_fR "${PROFILESDIR:-/tmp/non-existent-dir}"/*
   cp "$BACKUP_DIR/profiles"/* "$PROFILESDIR"/
   chmod 0644 "$PROFILESDIR"/*
   if [ -d '/run/systemd/system' ]; then
      systemctl daemon-reload || true
   fi
fi

if [ "$OPT_SKIP_VARLIB" = 'no' -a -d "$BACKUP_DIR/var/lib/avreg" ]; then
   log 'copy /var/lib/avreg/'
   cp -aR "$BACKUP_DIR"/var/lib/avreg/* /var/lib/avreg/
   (cd "$BACKUP_DIR/var/lib/avreg/" && setfacl --restore ../../../var_lib_avreg_facl.lst)
fi

if [ -s "$BACKUP_DIR/avreg.conf" ]; then
   log 'copy source avreg.conf to /etc/avreg/avreg.conf.OLD'
   cp "$BACKUP_DIR/avreg.conf" "/etc/avreg/avreg.conf.OLD"
fi

if [ -n "$backup_ext_auth" -a -r "$BACKUP_DIR/$backup_ext_auth" ]; then
   log 'copy source ExternalAuthMap file to /etc/avreg/'
   cp -b "$BACKUP_DIR/$backup_ext_auth" "/etc/avreg/"
   chmod 0640 "/etc/avreg/$backup_ext_auth"
   chown root:www-data "/etc/avreg/$backup_ext_auth"
   if [ "$OPT_UPGRADE_CONF" = 'yes' ]; then
      update-avreg.conf update 'avreg-site' --param='ExternalAuthMap' --value="/etc/avreg/$backup_ext_auth" --force
   fi
fi

if [ "$db_type" != "$backup_db_type" -a "$OPT_UPGRADE_AVREG_SERVER" = 'yes' ]; then
   if ! check_deb_status "avreg-server-${db_type}" 'installed'; then
      log "install avreg-server-${db_type}"
      $APT_INSTALL "avreg-server-${db_type}"
   fi
fi

if [ "$OPT_UPGRADE_CONF" = 'yes' ]; then
   log "upgrade current avreg.conf"
   if [ -n "$db_type" ]; then
      update-avreg.conf update 'global' --param='db-type' --value="$db_type" --force
   fi
   if [ -n "$db_host" ]; then
      update-avreg.conf update 'global' --param='db-host' --value="$db_host"
   else
      # change local ident pgsql auth (default pg_hba.conf) to 127.0.0.1 (IPv4 localhost)
      # for avregd, avreg-mon and avreg-unlink
      if [ "$db_type" = 'pgsql' ]; then
         update-avreg.conf update 'global' --param='db-host' --value='127.0.0.1' --force
      fi
   fi
   if [ -n "$db_port" ]; then
      update-avreg.conf update 'global' --param='db-port' --value="$db_port"
   fi

   if [ -n "$db_name" -a "$db_name" != "$DB_NAME_DEF" ]; then
      update-avreg.conf update 'global' --param='db-name' --value="$db_name"
   fi
fi

log 'done.'

if [ "x$BEQUIET" != 'xyes' ]; then
   cat <<__EOF__

TODO:
Check/update "/etc/avreg/avreg.conf" by values from backup's "avreg.conf.OLD"
and start AVReg and Apache2 serices:

   sudo avreg-service start
   sudo service apache2 start

__EOF__
fi
