#!/usr/bin/env bash
# php-legacy.sh - find PHP 5.x / 7.x / 8.0 / 8.1 on Ubuntu/Debian and optionally remove them.
#   sudo bash php-legacy.sh            report, then ask what to remove
#   sudo bash php-legacy.sh --report   report only, change nothing
# Log: /root/php-legacy-<host>-<timestamp>.log

set -uo pipefail
[ "$(id -u)" -eq 0 ] || { echo "Run with sudo."; exit 1; }
REPORT_ONLY=0; [ "${1:-}" = "--report" ] && REPORT_ONLY=1
LOG=/root/php-legacy-$(hostname)-$(date +%F-%H%M).log
exec > >(tee -a "$LOG") 2>&1

LEGACY='(5[.][0-9]|7[.][0-9]|8[.][01])'
hr(){ echo; echo "===== $* ====="; }
ask(){ local a; read -rp "$1 " a </dev/tty; echo "$a"; }
APACHE=0; command -v apache2ctl >/dev/null && APACHE=1

hr "HOST"; hostname; lsb_release -ds 2>/dev/null; date

# ---------- discovery ----------
mapfile -t ALLPKGS < <(dpkg-query -W -f='${db:Status-Abbrev} ${Package}\n' 2>/dev/null \
  | awk -v re="^(php|libapache2-mod-php)$LEGACY(-|\$)" '$2 ~ re {print substr($1,1,2), $2}')

mapfile -t BRANCHES < <( { printf '%s\n' "${ALLPKGS[@]}" | grep -oE "php$LEGACY" | sed 's/^php//';
                          ls /etc/php 2>/dev/null | grep -xE "$LEGACY"; } | sort -uV)

if [ ${#BRANCHES[@]} -eq 0 ]; then
  hr "RESULT"; echo "No PHP 5.x, 7.x, 8.0 or 8.1 found. Nothing to do."; exit 0
fi

declare -A INUSE
for b in "${BRANCHES[@]}"; do
  br=${b/./[.]}
  hr "BRANCH $b"
  echo "-- packages (ii=installed, rc=config only):"
  printf '%s\n' "${ALLPKGS[@]}" | awk -v re="^(php|libapache2-mod-php)$br(-|\$)" '$2 ~ re {print "   " $0}'
  echo "-- binaries:"; ls -1 /usr/bin/php$b /usr/sbin/php-fpm$b /usr/bin/php-cgi$b /usr/lib/cgi-bin/php$b /usr/bin/lsphp$b 2>/dev/null | sed 's/^/   /'

  reasons=()
  svc=$(systemctl list-units --type=service --all --no-legend 2>/dev/null | awk '{print $1, $3, $4}' | grep -E "^php$br-")
  [ -n "$svc" ] && echo "-- services:" && echo "$svc" | sed 's/^/   /'
  echo "$svc" | grep -qw running && reasons+=("service running")

  if [ $APACHE -eq 1 ]; then
    [ -e /etc/apache2/mods-enabled/php$b.load ] && reasons+=("Apache mod_php$b ENABLED (live)")
    [ -e /etc/apache2/conf-enabled/php$b-fpm.conf ] && reasons+=("Apache conf php$b-fpm enabled")
  fi

  refs=$(grep -RlE "php$br([^0-9]|\$)" /etc/apache2/sites-enabled /etc/apache2/conf-enabled /etc/apache2/mods-enabled \
         /etc/nginx /etc/cron* /var/spool/cron /etc/systemd/system /etc/supervisor 2>/dev/null | grep -vE "/php$br-fpm[.]conf\$|/php$br[.](load|conf)\$")
  [ -n "$refs" ] && reasons+=("referenced in config/cron") && echo "-- referenced in:" && echo "$refs" | sed 's/^/   /'

  procs=$(pgrep -a -f "php$br([^0-9]|\$)" 2>/dev/null | grep -v php-legacy)
  [ -n "$procs" ] && reasons+=("processes running") && echo "-- processes:" && echo "$procs" | head -5 | sed 's/^/   /'

  [ "$(readlink -f /usr/bin/php 2>/dev/null)" = "/usr/bin/php$b" ] && reasons+=("default 'php' command points here")

  shebang=$(timeout 60 grep -RIlE --exclude-dir={.git,vendor,node_modules,logs,cache} "^#!.*php$br" \
            /var/www /opt /home /usr/local/bin /srv 2>/dev/null | head -10)
  [ -n "$shebang" ] && reasons+=("scripts call it directly") && echo "-- scripts with php$b shebang:" && echo "$shebang" | sed 's/^/   /'

  if [ ${#reasons[@]} -gt 0 ]; then
    INUSE[$b]=$(IFS=';'; echo "${reasons[*]}"); echo ">> IN USE: ${INUSE[$b]}"
  else
    echo ">> Not in use (safe to remove)"
  fi
done

hr "PHP OUTSIDE APT (handle manually)"
ls -1d /usr/local/bin/php* /opt/*/bin/php* /usr/local/lsws/lsphp* 2>/dev/null || echo "   (none)"

hr "SUMMARY"
for b in "${BRANCHES[@]}"; do printf '   %-5s %s\n' "$b" "${INUSE[$b]:-not in use}"; done
[ $REPORT_ONLY -eq 1 ] && { echo; echo "Report only. Log: $LOG"; exit 0; }

# ---------- selection ----------
echo
ans=$(ask "Remove which? [a]ll, branches separated by spaces (e.g. 5.6 8.1), or [n]one:")
case "$ans" in
  a|A|all) SEL=("${BRANCHES[@]}") ;;
  ""|n|N|none) echo "Nothing removed. Log: $LOG"; exit 0 ;;
  *) SEL=(); for s in $ans; do
       if printf '%s\n' "${BRANCHES[@]}" | grep -qx "$s"; then SEL+=("$s"); else echo "Skipping '$s' (not a found legacy branch)"; fi
     done ;;
esac
[ ${#SEL[@]} -eq 0 ] && { echo "Nothing selected."; exit 0; }

FINAL=()
for b in "${SEL[@]}"; do
  if [ -n "${INUSE[$b]:-}" ]; then
    echo; echo "WARNING: $b looks in use: ${INUSE[$b]}"
    [ "$(ask "Remove $b anyway? Type the branch number ($b) to confirm, anything else skips:")" = "$b" ] && FINAL+=("$b") || echo "Skipping $b"
  else FINAL+=("$b"); fi
done
[ ${#FINAL[@]} -eq 0 ] && { echo "Nothing left to remove."; exit 0; }

TARGETS=()
for b in "${FINAL[@]}"; do
  br=${b/./[.]}
  mapfile -t -O ${#TARGETS[@]} TARGETS < <(printf '%s\n' "${ALLPKGS[@]}" | awk -v re="^(php|libapache2-mod-php)$br(-|\$)" '$2 ~ re {print $2}')
done

# ---------- dry run ----------
hr "DRY RUN"
SIM=$(apt-get -s purge "${TARGETS[@]}" 2>&1)
INST=$(echo "$SIM" | awk '/^Inst /{print $2}')
GONE=$(echo "$SIM" | awk '/^(Purg|Remv) /{print $2}')
EXTRA=$(comm -23 <(echo "$GONE" | sort -u) <(printf '%s\n' "${TARGETS[@]}" | sort -u))
echo "Will purge (${#TARGETS[@]}):"; printf '   %s\n' "${TARGETS[@]}"
if [ -n "$INST" ]; then
  echo; echo "ABORT: apt wants to INSTALL packages to satisfy dependencies:"; echo "$INST" | sed 's/^/   /'
  echo "Nothing changed. Send this output for review."; exit 1
fi
if [ -n "$EXTRA" ]; then
  echo; echo "CAUTION: these packages OUTSIDE the selected branches would also be removed:"; echo "$EXTRA" | sed 's/^/   /'
  [ "$(ask "Type YES to accept the extra removals:")" = "YES" ] || { echo "Aborted. Nothing changed."; exit 1; }
fi

[ "$(ask "Type REMOVE to purge PHP ${FINAL[*]}:")" = "REMOVE" ] || { echo "Aborted. Nothing changed."; exit 1; }

# ---------- execute ----------
hr "EXECUTE"
URL=https://localhost/; BEFORE=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 10 "$URL")
echo "localhost HTTP before: $BEFORE"

BK=/root/php-legacy-etc-backup-$(date +%F-%H%M).tgz
tar czf "$BK" $(for b in "${FINAL[@]}"; do [ -d /etc/php/$b ] && echo /etc/php/$b; done) /etc/apache2 2>/dev/null
echo "Config backup: $BK"

# point the default php command away from a branch being removed
CUR=$(readlink -f /usr/bin/php 2>/dev/null)
for b in "${FINAL[@]}"; do
  if [ "$CUR" = "/usr/bin/php$b" ]; then
    NEW=$(ls -1 /usr/bin/php[0-9]* 2>/dev/null | grep -vE "php$LEGACY\$" | sort -V | tail -1)
    [ -n "$NEW" ] && update-alternatives --set php "$NEW" && echo "Default php -> $NEW"
  fi
done

RESTART=0
if [ $APACHE -eq 1 ]; then
  for b in "${FINAL[@]}"; do
    [ -e /etc/apache2/mods-enabled/php$b.load ] && a2dismod -q php$b && RESTART=1
    [ -e /etc/apache2/conf-enabled/php$b-fpm.conf ] && a2disconf -q php$b-fpm && RESTART=1
  done
  if ! apache2ctl configtest >/dev/null 2>&1; then
    echo "ABORT: Apache config breaks without the old PHP module(s). Restoring and stopping."
    tar xzf "$BK" -C / etc/apache2 2>/dev/null; apache2ctl configtest; exit 1
  fi
fi

for b in "${FINAL[@]}"; do
  for u in $(systemctl list-units --type=service --all --no-legend 2>/dev/null | awk '{print $1}' | grep -E "^php${b/./[.]}-"); do
    systemctl disable --now "$u" 2>/dev/null && echo "Stopped $u"
  done
done

DEBIAN_FRONTEND=noninteractive apt-get purge -y "${TARGETS[@]}"
for b in "${FINAL[@]}"; do [ -d /etc/php/$b ] && rm -rf /etc/php/$b && echo "Removed leftover /etc/php/$b (in backup)"; done

if [ $APACHE -eq 1 ]; then
  if apache2ctl configtest >/dev/null 2>&1; then
    [ $RESTART -eq 1 ] && systemctl restart apache2 || systemctl reload apache2
  else echo "WARNING: apache2ctl configtest failed after purge. Apache NOT restarted:"; apache2ctl configtest; fi
fi

# ---------- verify ----------
hr "VERIFY"
LEFT=$(dpkg-query -W -f='${db:Status-Abbrev} ${Package}\n' 2>/dev/null | awk -v re="^(php|libapache2-mod-php)$LEGACY(-|\$)" '$2 ~ re')
echo "Legacy PHP packages remaining:"; [ -n "$LEFT" ] && echo "$LEFT" | sed 's/^/   /' || echo "   (none)"
echo "Default php: $(readlink -f /usr/bin/php 2>/dev/null) ($(php -r 'echo PHP_VERSION;' 2>/dev/null))"
AFTER=$(curl -sk -o /dev/null -w '%{http_code}' --max-time 10 "$URL")
echo "localhost HTTP before: $BEFORE  after: $AFTER"
[ "$BEFORE" != "$AFTER" ] && echo "CHECK THE SITE: response code changed. Roll back Apache with: tar xzf $BK -C / etc/apache2 && systemctl restart apache2"
echo; echo "Optional tidy-up (review the list first): apt-get autoremove --purge --dry-run"
echo "Log: $LOG"
