#!/bin/bash
#
# Make the database the only place a credential exists on this server.
#
# The Mac is already clean. This is the other half: nineteen .env files were
# found here on 22 August 2026, of which most are backups nobody reads and two
# belong to other installs that should never have carried Final Target's keys.
#
# Nothing is deleted before you have seen the list and typed yes. Live .env
# files belonging to other installs are never touched by this script, only
# reported, because blanking one would take that site down.
#
# Usage, on the server:
#   bash deploy/lock-credentials-to-db.sh
#
set -uo pipefail

SECRETS='^(STRIPE_SECRET_KEY|STRIPE_WEBHOOK_SECRET|STRIPE_PUBLIC_KEY|OPENAI_API_KEY|RECAPTCHA_SECRET_KEY|RECAPTCHA_V2_SECRET_KEY|RECAPTCHA_SITE_KEY|EMAIL_HOST_PASSWORD|SUPPORT_EMAIL_PASSWORD|TWILIO_AUTH_TOKEN|ESENDEX_API_KEY|NAMECHEAP_API_KEY|FAB_OAUTH_CLIENT_SECRET|FIELD_ENCRYPTION_KEY)=.+'

# A file is only removed if its name says it is a backup, or it sits under
# /root. Everything else is reported and left alone.
#
# The whitelist runs this way round on purpose. Final Target's settings read
# only `.env`, so `.env.production` here is dead weight, but mostafaei runs an
# older generation of the code and I have not read its settings. Guessing
# wrong deletes a live config. So the rule is: prove it is a backup by its
# name, or leave it.
is_disposable() {
  case "$1" in
    /root/*)                     return 0;;
    *.env.bak|*.env.bak-*|*.env.bak.*)   return 0;;
    *.env.save|*.env.save.*|*.env.*.save) return 0;;
    *.env.tmp|*.env.before-*)    return 0;;
  esac
  return 1
}

echo "════ 1. Every .env on this server, and what it holds ═══════════════════"
mapfile -t FOUND < <(find / -name ".env*" -not -path "*/venv/*" -not -name "*.example" -type f 2>/dev/null | sort)

DOOMED=()
for f in "${FOUND[@]}"; do
  n=$(grep -cE "$SECRETS" "$f" 2>/dev/null)
  perm=$(stat -c %a "$f" 2>/dev/null)
  if is_disposable "$f"; then
    printf '  backup  %2s secret(s)  %s  %s\n' "$n" "$perm" "$f"
    DOOMED+=("$f")
  else
    printf '  KEEP    %2s secret(s)  %s  %s\n' "$n" "$perm" "$f"
  fi
done

echo
echo "════ 2. Do the backups sweep .env in with them ═════════════════════════"
# A nightly tar that includes .env puts every key back on disk, in a file that
# is often world readable and often copied offsite. Worth knowing.
grep -rn "exclude.*env\|\.env" /usr/local/bin/ft-*.sh /root/*.sh 2>/dev/null \
  | grep -v "^Binary" | head -10 || echo "  no backup script mentions .env either way"

echo
echo "════ 3. Who can reach the database ═════════════════════════════════════"
su - postgres -c "psql -tAc \"select rolname, rolsuper, rolcanlogin from pg_roles where rolcanlogin\"" 2>/dev/null \
  | sed 's/^/  role: /' || echo "  could not read pg_roles, run this as root"
echo "  listening on:"
ss -lntp 2>/dev/null | grep -E '5432' | sed 's/^/    /' || echo "    postgres not on a TCP socket"

echo
echo "════ 4. Delete the disposable ones ═════════════════════════════════════"
if [ ${#DOOMED[@]} -eq 0 ]; then
  echo "  nothing to remove"
  exit 0
fi
printf '  %s\n' "${DOOMED[@]}"
echo
echo "  ${#DOOMED[@]} file(s). None of these is read by a running site."
read -r -p "  Shred them? [y/N] " reply
if [ "$reply" = "y" ] || [ "$reply" = "Y" ]; then
  for f in "${DOOMED[@]}"; do
    shred -u "$f" 2>/dev/null || rm -f "$f"
    [ -f "$f" ] && echo "    FAILED   $f" || echo "    shredded $f"
  done
else
  echo "  Left alone. Nothing removed."
fi

echo
echo "════ 5. What is left ═══════════════════════════════════════════════════"
find / -name ".env*" -not -path "*/venv/*" -not -name "*.example" -type f 2>/dev/null \
  | while read -r f; do
      printf '  %2s secret(s)  %s\n' "$(grep -cE "$SECRETS" "$f" 2>/dev/null)" "$f"
    done

cat <<'NOTE'

Anything still showing secrets belongs to mostafaei or paneltest. Those two
run the older code that reads .env, so their keys cannot simply be deleted.
They need either their own credentials or the database-only port, and until
then they are carrying Final Target's.
NOTE
