#!/bin/bash

# Colors first:
RED='\e[1;31m'
GREEN='\e[1;33m'
BLUE='\e[1;34m'
CYAN='\e[1;36m'
NC='\e[0m' 

echo -e "${CYAN}Please enter your password:${NC}"
stty -echo
read password
stty echo
password_length=${#password}

ord() 
{
  printf '%d' "'$1"
}

space_num=0
space_maj=0
space_min=0
space_res=0

count_plain=$(grep -F -c -i "$password" /usr/share/dict/words)
stripped=$(echo $password | sed -e 's/^[0-9]*//g' -e 's/[0-9]*$//g')
stripped_length=${#stripped}

if [ $count_plain -gt 0 ]; then
	echo -e "${GREEN}$password${NC} seems to be a common dictionary word. Please try again."
   
else 
		if [ $stripped_length -eq 0 ]; then
			echo -e "Using numbers only is discouraged, but here you go ..."
		fi
		
		if [ $stripped_length -gt 0 ]; then
			count_stripped=$(grep -F -c -i "$stripped" /usr/share/dict/words) 
			if [ $count_stripped -gt 0 ]; then
				echo -e "${GREEN}$stripped${NC} is close to a common dictionary word. Better think again."	
			fi
		fi

		for ((i=0;i<=$password_length-1;i+=1)); do
		  ascii_number=$(ord ${password:i:1})
			  if [ $ascii_number -ge 48 ] && [ $ascii_number -le 57 ]; then
				  charspace="num"	
			  elif [ $ascii_number -ge 65 ] && [ $ascii_number -le 90 ]; then
				  charspace="maj"
			  elif [ $ascii_number -ge 97 ] && [ $ascii_number -le 122 ]; then
				  charspace="min"
			  else
				  charspace="res"
			  fi
			  if [ "$charspace" = "num" ]; then
				  space_num=10
			  elif [ "$charspace" = "maj" ]; then
				  space_maj=26
			  elif [ "$charspace" = "min" ]; then
				  space_min=26
			  elif [ "$charspace" = "res" ]; then
				  space_res=32
			  fi
			  done

  space="$(echo "$space_num+$space_maj+$space_min+$space_res" | bc)"
  strength="$(echo "$password_length*l($space)/l(2)" | bc -l | xargs printf "%.0f")"

  entropy="$(echo -n "$password" | ent | grep Entropy | awk '{print $3}')"
  adv_strength="$(echo "$password_length*$entropy" | bc -l | xargs printf "%.0f")"


  echo -e ""
  echo -e "${GREEN}Simple analysis${NC}"
  echo -e "Length: $password_length"
  echo -e "Character Space: $space" 
  echo -e "Strength: $strength bit"
  echo -e ""
  echo -e "${GREEN}Advanced analysis${NC}"
  echo -e "Entropy: $entropy bits per byte"
  echo -e "Strength: $adv_strength bit"
  echo -e "________________________________________${RED}"
  if [ -x /usr/bin/fortune ]; then
	  /usr/bin/fortune -s 
	  echo -e "${NC}" 
  fi

fi

# numbers: 48 - 57 (10)
# major letters: 65 - 90 (26)
# minor letters: 97 - 122 (26)
# the rest: 33 - 47, 58 - 64, 91 - 96, 123 - 126 (32)
