#!/bin/bash


#Preupgrade Assistant performs system upgradability assessment
#and gathers information required for successful operating system upgrade.
#Copyright (C) 2013 Red Hat Inc.
#Jakub Mazanek <jmazanek@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
#END GENERATED SECTION

# The execution time of the script is not acceptable for INFORMATIONAL script
# ONLY. The bottleneck seems to be in find utility and file utility.

# The 'find' could be replaced using VALUE_ALLMYFILES and/or VALUE_EXECUTABLES 
# (similar to http://git.app.eng.bos.redhat.com/git/preupgrade-assistant-contents-users.git/tree/RHEL6_7/system/BinariesRebuild/check.sh )
# The 'file' performance could be improved using custom magic file (i.e.
# custom set of the rules for file utility. This set should be modified
# to reach required data faster)



# RHBZ #1072389
#
# Description of problem:
# This content should discover all /home directories and provides
# some summary about content. Like number of scripts, number of documents, binaries, git repositories and other.
#
# Bash function 'file' can be used for detection kind of file.
#
# How reproducible:
# On a RHEL6 system create any type of the document/scripts/repo mentioned in the description and execute preupg assessment
#
# Actual results:
# Missing content
#
# Expected results:
# Content which covers the /home directories with summarization what each directory contains
#
# Additional info:
# All local system files can be taken from $VALUE_ALLMYFILES which refers to /var/cache/preupgrade/common/allmyfiles.log

SOLUTION_TEXT=""
if [ -z $SOLUTION_FILE ]; then
  SOLUTION_FILE="./solution.txt"
fi
cat /dev/null > $SOLUTION_FILE
_FIRST_APPEND=1
append_to_solution()
{
    if test ! $_FIRST_APPEND -eq 1; then
        echo >> $SOLUTION_FILE
    fi
    _FIRST_APPEND=0
    cat >> $SOLUTION_FILE
}

declare -a defdirs=$(conf_get_section "$PREUPGRADE_CONFIG" "home-dirs"| egrep -v "\[|^$|\#")


# Make sure only root can run our script
if [ "$(id -u)" != "0" ]; then
   log_error "This script must be run as root"
   echo "This script must be run as root" 2>&1
   exit $RESULT_ERROR
fi

IFS="
"
start=$(date +%s);
# all directories in homedir are homes

all_pythons=0
all_perls=0
all_elfs=0
all_docs=0
all_gits=0
all_other=0
bll=".preupgrade_blacklist"
whl=".preupgrade_whitelist"
find_cmd_list="find_cmd_list"
whlval=1




### home directories of active users is listed in /etc/passwd ?
declare -a homes=$(awk -F":" '$7 ~ /sh\>/ { print $6 }' /etc/passwd )

printf '%s\n' ${homes[@]} | while IFS= read -r home
do
user=$(basename $home)
### interpret whitelist / blacklist rules

whlfind () {
while IFS=' ' read -r line; do
echo -n " $home/$line " >> "$home/$find_cmd_list"
whline=$home/$line
done < "$home/$whl"
}

bllfind () {
while IFS=' ' read -r line; do
if [[ -e "$home/$whl" ]];then
  echo -n " ! -path $whline/$line/\* " >> "$home/$find_cmd_list"
else
  echo -n " ! -path $home/$line/\* " >> "$home/$find_cmd_list"
fi
done < "$home/$bll"
}

deffind () {
printf '%s\n' ${defdirs[@]} | while IFS=' ' read -r line
do
  if [[ -e "$home/$line" ]];then
     echo -n " $home/$line " >> "$home/$find_cmd_list"
  fi
done
}

### define subdirectories to be searched

echo -n "find" > "$home/$find_cmd_list"

if [[ -e "$home/$whl" ]] && ! [[ -s "$home/$whl" ]];then
   echo > "$home/$find_cmd_list"
elif [[ -e "$home/$whl" ]];then
    if [[ -e "$home/$bll" ]];then
       whlfind
       bllfind
    else
       whlfind
    fi
elif [[ -e "$home/$bll" ]];then
   echo -n " $home " >> "$home/$find_cmd_list"
   bllfind
else
   deffind
fi
barefind=$(grep -x "^find$" "$home/$find_cmd_list")
if [[ -n "$barefind" ]];then
   cd "$home"
   sed -i 's/^find$/find . -maxdepth 1/g' "$home/$find_cmd_list"
fi
chmod u+x "$home/$find_cmd_list"


pythons=0
perls=0
elfs=0
docs=0
gits=0
other=0

 for fn in $($home/$find_cmd_list)
         do

      #result=$(file -bh --mime-type $fn)
      result=$(file -bh --mime $fn | awk -F';| ' '{print $1}' )

### Sort by file type

      case "$result" in
        "application/x-executable")
          elfs=$(expr $elfs + 1)
        ;;
        "application/msword")
          docs=$(expr $docs + 1)
        ;;
        "application/pdf")
          docs=$(expr $docs + 1)
        ;;
#        "application/vnd.oasis.opendocument.graphics")
#          docs=$(expr $docs + 1)
#        ;;
#        "application/vnd.oasis.opendocument.presentation")
#          docs=$(expr $docs + 1)
#        ;;
#        "application/vnd.oasis.opendocument.spreadsheet")
#          docs=$(expr $docs + 1)
#        ;;
        "application/x-zip")
           nomime=$(file -bh $fn | awk -F';|,| ' '{print $1}')
           if [ "$nomime" =~ "OpenDocument Text" ];then
             docs=$(expr $docs + 1)
           elif [ "$nomime" =~ "OpenDocument Spreadsheet" ];then
             docs=$(expr $docs + 1)
           else
             other=$(expr $other + 1)
           fi
        ;;
#        "application/vnd.openxmlformats-officedocument.wordprocessingml.document")
#          docs=$(expr $docs + 1)
#        ;;
        "text/html")
          nomime=$(file -bh $fn | awk -F';|,| ' '{print $1}')
          if [ "$nomime" =~ "html" ];then
            docs=$(expr $docs + 1)
          else
            other=$(expr $other + 1)
          fi
        ;;
        "text/rtf")
          docs=$(expr $docs + 1)
        ;;
        "text/x-perl")
          perls=$(expr $perls + 1)
        ;;
        "text/x-java")
             shebang=$(head -1 $fn)
             if [[ "$shebang" =~ "python" ]];then
               pythons=$(expr $pythons + 1)
             else
               other=$(expr $other + 1)
             fi
        ;;
#        "application/octet-stream")
#            if [[ "$result2" =~ ^Git ]]; then
#              gits=$(expr $gits + 1)
#            else 
#              other=$(expr $other + 1)
#            fi
#        ;;
        "application/x-not-regular-file")
           nomime=$(file -bh $fn | awk -F';|,| ' '{print $1}')
           bn=$(basename $fn);
           if [ "$nomime" = "directory" ] && [ x"$bn" = x".git" ]; then
              gits=$(expr $gits + 1)
           else
              other=$(expr $other + 1)
           fi
        ;;
        *)
          other=$(expr $other + 1)
        ;;
      esac


  done
#set +x
  ## accumulate into global statistics

  all_pythons=$(expr $all_pythons + $pythons)
  all_perls=$(expr $all_perls + $perls)
  all_elfs=$(expr $all_elfs + $elfs)
  all_docs=$(expr $all_docs + $docs)
  all_gits=$(expr $all_gits + $gits)
  all_other=$(expr $all_other + $other)

  ## show per-user statistics

  append_to_solution <<EOF
Summary for "$user" in "$home"
  Python script(s): $pythons
  Perl script(s): $perls
  ELF(s): $elfs
  Document(s): $docs
  Git repositorie(s): $gits
  Other file(s): $other
EOF

rm -f "$home/$find_cmd_list"
done
#set +x
end=$(date +%s)
duration=$(expr $end - $start)

log_info $"Scanning taken $duration second(s)"


  if [ 0$all_pythons -gt 0 ]; then
        append_to_solution <<EOF
* Be careful. It seems that some of the users have python scripts in their home directory.
EOF
  fi

  if [ 0$all_perls -gt 0 ]; then
        append_to_solution <<EOF
* Be careful. It seems that some of the users have perls scripts in their home directory.
EOF
  fi

  if [ 0$all_elfs -gt 0 ]; then
        append_to_solution <<EOF
* Be careful. It seems that some of the users have ELF binary files in home directory.
  It will be necessary to recompile them.
EOF
  fi

  if [ 0$all_docs -gt 0 ]; then
        append_to_solution <<EOF
* Be careful. It seems that some of the users have Documents in their home directory.
EOF
  fi

  if [ 0$all_gits -gt 0 ]; then
        append_to_solution <<EOF
* Be careful. It seems that some of the users have GIT repositories in their home directory.
EOF
  fi


  if [ 0$all_other -gt 0 ]; then
        append_to_solution <<EOF
* Be careful. It seems that some of the users have other files in their home directory.
EOF
  fi



exit $RESULT_INFORMATIONAL

