#!/bin/bash
# =============================================================================
# Created & hosted by RASANEGAAR.com
# Iran IPv4 list / mirror helpers — https://mirror.rasanegaar.com/info/
# Service Management (managed servers & network) — https://rasanegaar.com/
# =============================================================================
#
# Build a Cisco ASA / IOS-XE object-group from ir_ipv4_list.txt
# Usage:
#   ./cisco-asa-object-group.sh [list-url-or-file] [object-group-name]
# Example:
#   ./cisco-asa-object-group.sh \
#     https://mirror.rasanegaar.com/info/countries/IR/ir_ipv4_list.txt \
#     IRAN_IPV4 > iran_ipv4_asa.txt
#
set -euo pipefail

SRC="${1:-https://mirror.rasanegaar.com/info/countries/IR/ir_ipv4_list.txt}"
NAME="${2:-IRAN_IPV4}"
TMP="$(mktemp)"
cleanup() { rm -f "$TMP"; }
trap cleanup EXIT

if [[ "$SRC" == http://* || "$SRC" == https://* ]]; then
  curl -fsSL --connect-timeout 15 --max-time 90 "$SRC" -o "$TMP"
else
  cp "$SRC" "$TMP"
fi

COUNT="$(grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/[0-9]+$' "$TMP" | wc -l | tr -d ' ')"
if [[ "$COUNT" -lt 1 ]]; then
  echo "error: no IPv4 prefixes found in $SRC" >&2
  exit 1
fi

echo "! ============================================================================="
echo "! Created & hosted by RASANEGAAR.com"
echo "! Iran IPv4 list — https://mirror.rasanegaar.com/info/"
echo "! Service Management (managed servers & network) — https://rasanegaar.com/"
echo "! ============================================================================="
echo "! Generated from $SRC"
echo "! Prefixes: $COUNT"
echo "! Paste in config mode on ASA / compatible IOS firewall"
echo "object-group network $NAME"
echo " description Iran IPv4 ranges — RASANEGAAR.com"
# ASA accepts "network-object <subnet> <mask>" — convert CIDR → dotted mask
while IFS= read -r cidr; do
  [[ -n "$cidr" ]] || continue
  ip="${cidr%/*}"
  bits="${cidr#*/}"
  mask=""
  rem=$bits
  for _ in 1 2 3 4; do
    if (( rem >= 8 )); then
      o=255
      rem=$((rem - 8))
    elif (( rem <= 0 )); then
      o=0
    else
      o=$(( 256 - (2 ** (8 - rem)) ))
      rem=0
    fi
    if [[ -z "$mask" ]]; then
      mask="$o"
    else
      mask="$mask.$o"
    fi
  done
  echo " network-object $ip $mask"
done < <(grep -E '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/[0-9]+$' "$TMP")
echo "exit"
echo "!"
echo "! Example ACL (edit interfaces/ACLs to match your policy):"
echo "! access-list OUTSIDE_IN extended permit ip object-group $NAME any"
echo "! access-group OUTSIDE_IN in interface outside"
echo "! ============================================================================="
echo "! End — RASANEGAAR.com | Service Management: https://rasanegaar.com/"
echo "! Help: https://mirror.rasanegaar.com/info/usage.html"
echo "! ============================================================================="
