#!/usr/bin/env bash

# Prowler - the handy cloud security tool (c) by Toni de la Fuente
#
# This Prowler check is licensed under a
# Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
#
# You should have received a copy of the license along with this
# work. If not, see <http://creativecommons.org/licenses/by-nc-sa/4.0/>.

CHECK_ID_check11="1.1,1.01"
CHECK_TITLE_check11="[check11] Avoid the use of the root account (Scored)"
CHECK_SCORED_check11="SCORED"
CHECK_TYPE_check11="LEVEL1"
CHECK_ALTERNATE_check101="check11"

check11(){
  # "Avoid the use of the root account (Scored)."
  MAX_DAYS=-1
  last_login_dates=$(cat $TEMP_REPORT_FILE | awk -F, '{ print $1,$5,$11,$16 }' | grep '<root_account>' | cut -d' ' -f2,3,4)

  failures=0
  for date in $last_login_dates; do
    if [[ ${date%T*} =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]];then
      days_not_in_use=$(how_many_days_from_today ${date%T*})
      if [ "$days_not_in_use" -gt "$MAX_DAYS" ];then
          failures=1
          textFail "Root user in the account was last accessed ${MAX_DAYS#-} day ago"
          break
      fi
    fi
  done

  if [[ $failures == 0 ]]; then
      textPass "Root user in the account wasn't accessed in the last ${MAX_DAYS#-} days"
  fi
}
