#!/bin/bash

# Function to get the internet IP
get_internet_ip() {
    INTERFACE=$(ip route get 8.8.8.8 2>/dev/null | awk '{for(i=1;i<=NF;i++) if ($i=="dev") {print $(i+1); exit}}')

    if [ -z "$INTERFACE" ] || [ "$INTERFACE" = "lo" ]; then
        return 1
    fi

    IP=$(ip -4 addr show dev "$INTERFACE" scope global | grep -oP '(?<=inet\s)\d{1,3}(\.\d{1,3}){3}(?=/)' | head -n1)

    if [ -z "$IP" ]; then
        return 1
    fi

    echo "$IP"
    return 0
}

# Get all global non-loopback IPv4 addresses
ALL_IPS=$(ip -4 addr show scope global | grep -oP '(?<=inet\s)\d{1,3}(\.\d{1,3}){3}(?=/)')

ARG="${1:-local}"

if [ "$ARG" = "internet" ]; then
    INTERNET_IP=$(get_internet_ip)
    if [ $? -ne 0 ]; then
        echo "No valid default route or global IPv4 address found."
        exit 1
    fi
    echo "$INTERNET_IP"
else
    # For "local" or anything else
    INTERNET_IP=$(get_internet_ip) || INTERNET_IP=""  # If fails, set to empty so no exclusion

    for IP in $ALL_IPS; do
        if [ "$IP" != "$INTERNET_IP" ]; then
            echo "$IP"
        fi
    done
fi
