#!/bin/bash

#Preupgrade Assistant performs system upgradability assessment
#and gathers information required for successful operating system upgrade.
#Copyright (C) 2013 Red Hat Inc.
#
#
#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 3 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, see <http://www.gnu.org/licenses/>.
. /usr/share/preupgrade/common.sh
check_applies_to "iptables"
check_rpm_to "" "cmp"
#END GENERATED SECTION

check_root

custom_scf=false
custom_iptables=false
custom_ip6tables=false

CONFIG_FILE="/etc/sysconfig/system-config-firewall"
if [[ -f "${CONFIG_FILE}" ]]; then
  if ! grep -q "disabled" "${CONFIG_FILE}"; then
    custom_scf=true
    backup_config_file "${CONFIG_FILE}"
  fi
fi

CONFIG_FILE="/etc/sysconfig/iptables"
DEFAULT_CONFIG_FILE="iptables_default"
if [[ -f "${CONFIG_FILE}" ]]; then
  if ! cmp --quiet "${CONFIG_FILE}" "${DEFAULT_CONFIG_FILE}"; then
    custom_iptables=true
    backup_config_file "${CONFIG_FILE}"
  fi
fi

CONFIG_FILE="/etc/sysconfig/ip6tables"
DEFAULT_CONFIG_FILE="ip6tables_default"
if [[ -f "${CONFIG_FILE}" ]]; then
  if ! cmp --quiet "${CONFIG_FILE}" "${DEFAULT_CONFIG_FILE}"; then
    custom_ip6tables=true
    backup_config_file "${CONFIG_FILE}"
  fi
fi

if service_is_enabled "iptables" || service_is_enabled "ip6tables"; then
  POSTUPGRADE_DIR="$VALUE_TMP_PREUPGRADE/postupgrade.d/reenable-iptables"
  if [[ ! -d "$POSTUPGRADE_DIR" ]]; then
    log_info "Creating $POSTUPGRADE_DIR"
    mkdir -p "$VALUE_TMP_PREUPGRADE/postupgrade.d/reenable-iptables"
  fi

  if service_is_enabled "iptables"; then
    SCRIPT_NAME="iptables.sh"
    POST_SCRIPT="postupgrade.d/$SCRIPT_NAME"
    cp $POST_SCRIPT $POSTUPGRADE_DIR/$SCRIPT_NAME
  fi

  if service_is_enabled "ip6tables"; then
    SCRIPT_NAME="ip6tables.sh"
    POST_SCRIPT="postupgrade.d/$SCRIPT_NAME"
    cp $POST_SCRIPT $POSTUPGRADE_DIR/$SCRIPT_NAME
  fi

  log_warning "Read remediation instructions."
  exit_informational
fi

exit_pass
