#!/bin/bash
. /usr/share/preupgrade/common.sh

#END GENERATED SECTION


AUDIT_FLAG=0
fix_audit65="fix_audit65.sh"

check_audit() {
  # this is special case of /etc/audit/audit.rules
  if [ ! -d /etc/audit/rules.d ]; then
    # RHEL6.5 and older
    cp $fix_audit65 $POSTUPGRADE_DIR/$fix_audit65
  else
    # Handle RHEL 6.6 and later this way. If augenrules is not used (AUGENRULES="no")
    # then they need to migrate to the new setup. Otherwise they have already migrated.
    grep -E "^\s*AUGENRULES=" /etc/sysconfig/auditd | grep -i "no"
    [ $? -ne 0 ] && {
      AUDIT_FLAG=1
      return 1
    }
  fi


  return 0
}

declare -a noreplace_files
truncate -s 0 solution.txt
while read line; do
  # remove begin of line (waste) and get flag value:
  #....L....  c /etc/pam.d/system-auth
  flname=$(echo $line | awk '{print $3}' )

  # when a config file is removed by user, rpm -qcV returns string
  # 'missing  c /path/file' instead of usual output
  for fflags in $(rpm -q --qf '[%{filenames}: %{fileflags}\n]' -f ${flname} | grep "^${flname}:" | cut -d ":" -f 2)
    do
      # Only the 1 << 4 b (== 16) matters here. That is the RPMFILE_NOREPLACE
      # flag. So mask the other bits.
      if [ $[ $fflags & 16 ] -eq 16 ]; then
        noreplace_files+=("${flname}")
        break
      fi
    done

done < $VALUE_CONFIGCHANGED

[ ${#noreplace_files[@]} -gt 0 ] && {
  log_slight_risk "Certain configuration files are changed and the .rpmnew files will be generated."
  echo -e "Check these configuration files after the upgrade to Red Hat Enterprise Linux 7:\n" > solution.txt
  for i in ${noreplace_files[@]}; do
    [ "$i" == "/etc/audit/audit.rules" ] && check_audit || { echo "$i" >> solution.txt; }
  done

  [ $AUDIT_FLAG -eq 1 ] && {
    log_high_risk "Manual intervention recommended before the upgrade."
    echo "
Pay special attention to the /etc/audit/* files. The /etc/audit/audit.rules file
is now generated by the /sbin/augenrules script, and your configuration files must be in the
/etc/audit/rules.d/ directory with '.rules' extensions. When you handle it, create
the /etc/audit/audit.rules file by the /sbin/augenrules script. See the augenrules(8) man pages.
Do this before the upgrade."
  }
  exit $RESULT_FAIL
}

exit $RESULT_PASS
