#!/bin/bash

#==============================================================================
# description : Checks a list of hostnames on certificate.
# author      : Joachim
# email       : contact@joachim.gent
# version     : 2.6
#==============================================================================

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m' # No Color

show_help() {
    echo
    echo "Usage: $0 [file]"
    echo
    echo "Checks a list of hostnames for DNS, SSL certificate, and expiry date."
    echo
    echo "Options:"
    echo "  file    A file containing domain names (one per line)."
    echo "  -h      Show help."
    echo "  -v      Show version."
    echo
    exit 0
}

case "$1" in
    -h|--help)
        show_help
        ;;
    -v|--version)
        echo "Version: 2.6"
        exit 0
        ;;
esac

#───────────────────────────────────────────────────────────────────────────────
# Functions
#───────────────────────────────────────────────────────────────────────────────

check_dns() {
    local ip netname dns
    ip=$(dig a +short "$domainname" | head -n1)
    if [[ -z "$ip" ]]; then
        echo -e "${RED}NoDNS${NC}"
    else
        netname=$(whois "$ip" 2>/dev/null | grep -i '^netname' | awk '{print $2}')
        dns=$(dig +short +noshort "$domainname" | awk '{gsub(/\.$/, "",$1); print $1, $4, $5}')
        echo "$dns NetName:$netname"
    fi
}

check_ssl() {
    local ssl_output enddate issuer subject expire_epoch now_epoch days_left color

    ssl_output=$(echo Q | openssl s_client -connect "${domainname}:443" 2>/dev/null \
        | openssl x509 -noout -enddate -issuer -subject 2>/dev/null)

    if [[ -z "$ssl_output" ]]; then
        echo -e "${RED}NoCert${NC}"
        return
    fi

    enddate=$(echo "$ssl_output" | grep 'notAfter=' | cut -d= -f2)
    issuer=$(echo "$ssl_output" | grep 'issuer=' | sed 's/issuer=//')
    subject=$(echo "$ssl_output" | grep 'subject=' | sed 's/subject=//')

    # Convert expiry to epoch seconds
    expire_epoch=$(date -d "$enddate" +%s 2>/dev/null)
    now_epoch=$(date +%s)
    days_left=$(( (expire_epoch - now_epoch) / 86400 ))

    # Determine color based on remaining days
    if (( days_left < 30 )); then
        color=$RED
    else
        color=$GREEN
    fi

    echo -e "${color}Expiry:${enddate}${NC}, Issuer:${issuer}, Subject:${subject}"
}

#───────────────────────────────────────────────────────────────────────────────
# Setup
#───────────────────────────────────────────────────────────────────────────────

mkdir -p ./log ./archive
clear

echo "┌───────────────────────────────────────┐"
echo "│╔═╗╔═╗╦  ╦  ┌─┐┌─┐┬ ┬  ╔═╗┌─┐┬─┐┬┌─┐┌┬┐│"
echo "│╚═╗╚═╗║  ║  ├─┤┌─┘└┬┘  ╚═╗│  ├┬┘│├─┘ │ │"
echo "│╚═╝╚═╝╩═╝╩═╝┴ ┴└─┘ ┴   ╚═╝└─┘┴└─┴┴   ┴ │"
echo "└───────────────────────────────────────┘"
echo

list="$1"

if [[ -z "$list" || ! -f "$list" ]]; then
    echo "─────────────────────────────────────────────────────────────────────────────"
    echo "Available lists:"
    echo "─────────────────────────────────────────────────────────────────────────────"
    ls | egrep -v 'bulkssl.script|exported|openssl.script|sslcheck|ssllazy.script|processedlists|archive|log'
    echo
    echo "Enter your list:"
    read -r list
fi

if [[ ! -f "$list" ]]; then
    echo "Error: File '$list' not found."
    exit 1
fi

listexport=$(basename "$list" | cut -d. -f1)
timestamp=$(date +"%Y%m%d_%H%M")
start=$(date +%s)
logfile="./log/${listexport}_${timestamp}.export"

mapfile -t domains < "$list"
counter=${#domains[@]}

echo
echo "─────────────────────────────────────────────────────────────────────────────"
echo "Checking $counter domains..."
echo "─────────────────────────────────────────────────────────────────────────────"
echo

for domainname in "${domains[@]}"; do
    dns_info=$(check_dns)
    ssl_info=$(check_ssl)
    echo -e "${domainname} $dns_info $ssl_info" | tee -a "$logfile"
    echo
done

end=$(date +%s)
runtime=$((end - start))

echo "─────────────────────────────────────────────────────────────────────────────" | tee -a "$logfile"
echo "Checked $counter hostnames in $runtime seconds" | tee -a "$logfile"
echo "Full export saved to $logfile" | tee -a "$logfile"
echo "─────────────────────────────────────────────────────────────────────────────" | tee -a "$logfile"

read -rp "Would you like to move your list to ./archive? (y/n): " opt
case "$opt" in
    [Yy]*)
        mv "$list" ./archive/
        echo "Moved '$list' to ./archive/"
        ;;
    [Nn]*)
        ;;
    *)
        echo "Invalid option, skipping."
        ;;
esac

echo "─────────────────────────────────────────────────────────────────────────────"
exit 0
