#!/usr/bin/env bash
set -uo pipefail
cd /root/switch

echo "=== sounds/music packages that DO exist ==="
apt-cache search '^freeswitch' | grep -iE 'sound|music' | sort

echo
echo "=== install lines in the script ==="
grep -n 'apt-get install' install-switch.sh

echo
echo "=== validation of every freeswitch-* name used ==="
grep 'apt-get install' install-switch.sh \
  | grep -oE '\bfreeswitch-[a-z0-9.-]+' | sed 's/\.$//' | sort -u \
  | while read -r p; do
      apt-cache show "$p" >/dev/null 2>&1 && echo "OK   $p" || echo "MISS $p"
    done

echo
echo "=== auto-patch known-renamed packages ==="
patch_one() {
  local bad="$1" pat="$2" new
  if apt-cache show "$bad" >/dev/null 2>&1; then echo "keep  $bad"; return; fi
  new=$(apt-cache search '^freeswitch' | awk -v p="$pat" '$1 ~ p {print $1; exit}')
  if [ -n "$new" ]; then
    sed -i "s/\b${bad}\b/${new}/g" install-switch.sh
    echo "PATCH $bad -> $new"
  else
    echo "MANUAL $bad (no match for /$pat/)"
  fi
}
patch_one freeswitch-sounds-music        'music'
patch_one freeswitch-sounds-en-us-callie 'sounds-en-us-callie'

echo
echo "=== install lines after patching ==="
grep -n 'apt-get install' install-switch.sh
