#!/usr/bin/env bash
set -euo pipefail

if [ "$#" -ne 2 ]; then
  echo "Usage: $0 <old-ip> <new-ip>"
  echo "Example: $0 192.168.60.146 192.168.60.146"
  exit 1
fi

OLD_IP="$1"
NEW_IP="$2"

is_valid_ip() {
  local ip="$1"

  [[ "$ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] || return 1

  IFS='.' read -r a b c d <<< "$ip"

  for part in "$a" "$b" "$c" "$d"; do
    (( part >= 0 && part <= 255 )) || return 1
  done
}

if ! is_valid_ip "$OLD_IP"; then
  echo "Invalid old IP: $OLD_IP"
  exit 1
fi

if ! is_valid_ip "$NEW_IP"; then
  echo "Invalid new IP: $NEW_IP"
  exit 1
fi

export OLD_IP
export NEW_IP

changed_files=0
skipped_files=0

while IFS= read -r -d '' file; do
  # Пропускаем бинарные файлы
  if ! grep -Iq . "$file"; then
    skipped_files=$((skipped_files + 1))
    continue
  fi

  if perl -0ne '
    BEGIN { $old = quotemeta($ENV{"OLD_IP"}); }
    exit 0 if /(?<![0-9.])$old(?![0-9.])/;
    exit 1;
  ' "$file"; then
    perl -0pi -e '
      BEGIN {
        $old = quotemeta($ENV{"OLD_IP"});
        $new = $ENV{"NEW_IP"};
      }
      s/(?<![0-9.])$old(?![0-9.])/$new/g;
    ' "$file"

    echo "changed: $file"
    changed_files=$((changed_files + 1))
  fi
done < <(
  find . \
    -path './.git' -prune -o \
    -type f \
    -print0
)

echo ""
echo "Done."
echo "IP replaced: $OLD_IP -> $NEW_IP"
echo "Files updated: $changed_files"
echo "Files skipped: $skipped_files"
