#!/bin/bash


#Preupgrade Assistant performs system upgradability assessment
#and gathers information required for successful operating system upgrade.
#Copyright (C) 2013 Red Hat Inc.
#Ondrej Vasik <ovasik@redhat.com>
#
#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 "pam"
#END GENERATED SECTION

POSTUPGRADE_DIR="$POSTUPGRADE_DIR/pam"
CLEANCONF_DIR="$VALUE_TMP_PREUPGRADE/cleanconf/etc/pam.d"

if [[ ! -d "$POSTUPGRADE_DIR" ]]; then
    mkdir -p "$POSTUPGRADE_DIR"
fi
if [[ ! -d "$CLEANCONF_DIR" ]]; then
    mkdir -p "$CLEANCONF_DIR"
fi

SCRIPT_NAME="postupgrade-pam.sh"
POST_SCRIPT="postupgrade.d/$SCRIPT_NAME"

cp -f $POST_SCRIPT $POSTUPGRADE_DIR/$SCRIPT_NAME

fail=0

comment_invalid () {
    perl -p -i -e 's/^/#/g if /^(?!.*#)(?=.*(pam_passwdqc|pam_ecryptfs))/;' "$1"
}
check_deprec_dirctv () {

    deprec_dirctv="$1"
    input_file="$2"
    export deprec_dirctv
    export input_file
    perl -ne '$deprec_dirctv = $ENV{deprec_dirctv};$input_file = $ENV{input_file};
    print "PAM: The $input_file file contains the $deprec_dirctv module, which is no longer supported.\n"
    if /^(?!.*#)(?=.*$deprec_dirctv)/' "$input_file"

}
copy_clean () {
    cp -p "$1" "$2"
}

#pam_passwdqc and pam_ecryptfs were removed
for file in $(find -P /etc/pam.d/ -maxdepth 1 -type f)
do
    clean_file="$CLEANCONF_DIR"/$(basename "$file")

    deprec_status=$(check_deprec_dirctv "pam_passwdqc" "$file")
    [ -n "$deprec_status" ] && log_medium_risk "$deprec_status" && \
    copy_clean "$file" "$clean_file" && comment_invalid "$clean_file" && fail=1

    deprec_status=$(check_deprec_dirctv "pam_ecryptfs" "$file")
    [ -n "$deprec_status" ] && log_high_risk "$deprec_status" && \
    copy_clean "$file" "$clean_file" && comment_invalid "$clean_file" && fail=1


done

test $fail = 1 && exit $RESULT_FAIL

rm -rf "$CLEANCONF_DIR" && exit $RESULT_PASS
