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

# Usage:
#   ./clean-and-reset-htaccess.sh            # runs in current dir
#   ./clean-and-reset-htaccess.sh /path/to/site  # runs in provided dir

SITE_ROOT="${1:-$(pwd)}"

# safety: canonicalize path and avoid accidental root-wide delete
SITE_ROOT="$(cd "$SITE_ROOT" && pwd -P)"
if [ -z "$SITE_ROOT" ] || [ "$SITE_ROOT" = "/" ] || [ "$SITE_ROOT" = "" ]; then
  echo "Refusing to run: unsafe SITE_ROOT='$SITE_ROOT'"
  exit 1
fi

TS=$(date +%Y%m%d-%H%M%S)
BACKUP_ROOT="${HOME:-/tmp}/htaccess-backups"
WORKDIR="$BACKUP_ROOT/$TS"
ARCHIVE="$BACKUP_ROOT/htaccess-$TS.tar.gz"

echo "=== Starting .htaccess cleanup for $SITE_ROOT at $TS ==="
echo "Backups will be stored at: $ARCHIVE"
mkdir -p "$WORKDIR"
mkdir -p "$BACKUP_ROOT"

# 1) Backup all .htaccess files (preserving relative paths)
echo "[+] Backing up all .htaccess files (preserving paths) ..."
find "$SITE_ROOT" -type f -name ".htaccess" -print0 | while IFS= read -r -d '' f; do
  dest="$WORKDIR${f#$SITE_ROOT}"
  mkdir -p "$(dirname "$dest")"
  cp -p "$f" "$dest"
done

# archive the backup
if [ -d "$WORKDIR" ]; then
  tar -C "$WORKDIR" -czf "$ARCHIVE" . || true
  rm -rf "$WORKDIR"
  echo "[✓] Full backup stored at: $ARCHIVE"
else
  echo "[!] No .htaccess files found to backup."
fi

echo
echo "[+] Listing .htaccess files with permission 0444 (if any):"
find "$SITE_ROOT" -type f -name ".htaccess" -perm 0444 -ls || true

echo
echo "[+] Setting permission 0644 on all .htaccess files (if any)..."
find "$SITE_ROOT" -type f -name ".htaccess" -exec chmod 0644 {} \; || true

echo
echo "[+] Searching .htaccess files for suspicious rules (report only):"
grep -R --include=".htaccess" -HnE 
'http[s]?://|base64_decode|eval\(|gzinflate|RedirectMatch|RewriteCond|RewriteRule|ErrorDocument|SetHandler|AddHandler' 
"$SITE_ROOT" || true

echo
echo "[+] Creating a per-file .bak.$TS backup next to each .htaccess (if present)..."
find "$SITE_ROOT" -type f -name ".htaccess" -print0 | while IFS= read -r -d '' f; do
  cp -p "$f" "$f.bak.$TS"
  echo "    backed up: $f -> $f.bak.$TS"
done

echo
echo "[!] Now deleting ALL .htaccess files under $SITE_ROOT ..."
# change to SITE_ROOT first so the subsequent find -delete is local to this tree
cd "$SITE_ROOT"
# this is what you asked — deletes all .htaccess files in and below SITE_ROOT
find . -type f -name ".htaccess" -print -delete

echo
echo "[✓] Deleted .htaccess files. Re-creating WordPress default .htaccess in root of site..."

# Create WordPress default .htaccess at SITE_ROOT/.htaccess
cat > "$SITE_ROOT/.htaccess" <<'WPHT'
# BEGIN WordPress

RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress
WPHT

chmod 0644 "$SITE_ROOT/.htaccess" || true

echo
echo "[✓] Default WordPress .htaccess created at: $SITE_ROOT/.htaccess"
echo "[✓] Per-file backups (if any) are next to original files as .bak.$TS and full archive is: $ARCHIVE"
echo
echo "IMPORTANT:"
echo " - Inspect backups before deleting anything."
echo " - If your site is not WordPress, replace the created .htaccess with the correct rules for your app."
echo " - After this, consider running scans for PHP webshells and rotating credentials."
echo
echo "Done."

