#!/usr/bin/env bash
# snifinder.sh - POSIX/Bash equivalent of your SniFinder .bat
# Requires: bash, curl
# Asn.csv should be in the same directory as this script (format: ASN;SNI)

set -euo pipefail

# directory where script resides (works in most cases)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" >/dev/null 2>&1 && pwd)"
ASN_FILE="$SCRIPT_DIR/Asn.csv"

# handle ctrl-c nicely
trap 'echo; echo "Interrupted."; exit 130' INT

while true; do
    # prompt
    printf '\nEnter domain (for example, youtube.com) : '
    if ! IFS= read -r domain; then
        echo
        break
    fi

    # trim whitespace
    domain="${domain## }"
    domain="${domain%% }"

    [ -z "$domain" ] && continue

    # ask ip-api for the "as" field (timeout 5s, force IPv4, silent, show errors suppressed)
    json="$(curl -4ks -m 5 "http://ip-api.com/json/${domain}?fields=as" || true)"

    if [ -z "$json" ]; then
        echo "ERROR: Failed to query ip-api for ${domain}"
        read -r -p "Press Enter to continue..."
        continue
    fi

    # extract the value of "as" from JSON (e.g. "AS15169 Google LLC")
    # awk -F'"' prints the 4th field for a JSON like {"as":"AS15169 Google LLC"}
    as_full="$(printf '%s' "$json" | awk -F'"' '/"as"[[:space:]]*:/ { print $4; exit }' || true)"

    if [ -z "$as_full" ]; then
        echo "ERROR: Can't find Asn for ${domain}"
        read -r -p "Press Enter to continue..."
        continue
    fi

    # take the first token from the "as" value (so "AS15169 Google LLC" -> "AS15169")
    asn="$(printf '%s' "$as_full" | awk '{print $1}')"

    if [ -z "$asn" ]; then
        echo "ERROR: Can't determine ASN from response for ${domain}"
        read -r -p "Press Enter to continue..."
        continue
    fi

    echo "------------------------------------------------------------------------------"
    echo "Asn: $asn"
    echo "------------------------------------------------------------------------------"

    # check Asn.csv exists
    if [ ! -f "$ASN_FILE" ]; then
        echo "ERROR: Asn file not found: $ASN_FILE"
        read -r -p "Press Enter to continue..."
        continue
    fi

    # search Asn.csv (semicolon-separated). case-insensitive match of the ASN (left field).
    i=0
    # Use while-read to preserve whitespace in SNI columns
    while IFS=';' read -r col_as col_sni rest; do
        # skip empty/comment lines
        [ -z "${col_as// /}" ] && continue
        case "${col_as,,}" in
            "${asn,,}")
                i=$((i + 1))
                echo "Sni N$i: $col_sni"
                ;;
        esac
    done < "$ASN_FILE"

    if [ "$i" -eq 0 ]; then
        echo "ERROR: Can't find Sni for ${domain}"
    fi

    read -r -p "Press Enter to continue..."
done
