#!/bin/bash
#
# clean_redirects.sh
# Interactively find and remove malicious redirect lines from JS/HTML/PHP files.
# Usage: ./clean_redirects.sh /var/www/SiteName
#
# For each match:
#   y = delete this line from this file
#   n = skip this occurrence
#   a = delete this line everywhere it appears with IDENTICAL content (auto-applies for rest of run)
#   s = show more context around the match
#   q = quit
#
# All actions are logged to clean_redirects.log so you have a record of what was removed.

set -u

TARGET_DIR="${1:-}"
if [ -z "$TARGET_DIR" ] || [ ! -d "$TARGET_DIR" ]; then
    echo "Usage: $0 /path/to/site"
    exit 1
fi

LOGFILE="./clean_redirects_$(date +%Y%m%d_%H%M%S).log"
PATTERN='https?://[a-zA-Z0-9.-]*short[a-zA-Z0-9.-]*\.[a-zA-Z]{2,}'

# Track lines that have been approved for blanket removal (exact string match)
declare -A APPROVED_LINES
# Track lines the user explicitly skipped, so we don't ask again this run
declare -A SKIPPED_LINES

echo "Scanning $TARGET_DIR for suspicious redirect pattern..."
echo "Log file: $LOGFILE"
echo "----------------------------------------"

# Find candidate files - adjust extensions as needed
mapfile -t FILES < <(grep -rlE "$PATTERN" "$TARGET_DIR" --include=*.js --include=*.html --include=*.php 2>/dev/null)

if [ ${#FILES[@]} -eq 0 ]; then
    echo "No matches found."
    exit 0
fi

echo "Found ${#FILES[@]} file(s) with matches."
echo ""

TOTAL_REMOVED=0

for FILE in "${FILES[@]}"; do
    echo "=========================================="
    echo "FILE: $FILE"
    echo "=========================================="

    # Get matching line numbers for this file (recalculated each time, since file may shrink as we edit)
    while true; do
        MATCH_LINE=$(grep -nE "$PATTERN" "$FILE" 2>/dev/null | head -1)
        if [ -z "$MATCH_LINE" ]; then
            break
        fi

        LINE_NUM="${MATCH_LINE%%:*}"
        LINE_CONTENT="${MATCH_LINE#*:}"
        # Trim leading whitespace for display
        TRIMMED=$(echo "$LINE_CONTENT" | sed 's/^[[:space:]]*//')

        # If this exact line content was already approved for blanket removal, apply silently
        if [ -n "${APPROVED_LINES[$TRIMMED]:-}" ]; then
            sed -i "${LINE_NUM}d" "$FILE"
            echo "[auto-removed, previously approved] $FILE:$LINE_NUM"
            echo "$(date) AUTO-REMOVED $FILE:$LINE_NUM :: $TRIMMED" >> "$LOGFILE"
            TOTAL_REMOVED=$((TOTAL_REMOVED+1))
            continue
        fi

        # If this exact line was already skipped, don't ask again - but don't loop forever either
        if [ -n "${SKIPPED_LINES[$TRIMMED]:-}" ]; then
            echo "[skipped earlier, leaving in place] $FILE:$LINE_NUM"
            break
        fi

        echo ""
        echo "--- Match at line $LINE_NUM ---"
        echo "$TRIMMED" | fold -w 100
        echo "---"
        read -p "Delete this line? [y]es / [n]o / [a]ll identical / [s]how context / [q]uit: " ANSWER

        case "$ANSWER" in
            y|Y)
                sed -i "${LINE_NUM}d" "$FILE"
                echo "$(date) REMOVED $FILE:$LINE_NUM :: $TRIMMED" >> "$LOGFILE"
                TOTAL_REMOVED=$((TOTAL_REMOVED+1))
                ;;
            a|A)
                APPROVED_LINES["$TRIMMED"]=1
                sed -i "${LINE_NUM}d" "$FILE"
                echo "$(date) REMOVED (approved for all) $FILE:$LINE_NUM :: $TRIMMED" >> "$LOGFILE"
                TOTAL_REMOVED=$((TOTAL_REMOVED+1))
                ;;
            s|S)
                echo ""
                echo "Context (5 lines before/after):"
                sed -n "$((LINE_NUM>5?LINE_NUM-5:1)),$((LINE_NUM+5))p" "$FILE" | cat -n
                echo ""
                # loop back without consuming this match - ask again
                continue
                ;;
            q|Q)
                echo "Quitting. $TOTAL_REMOVED line(s) removed so far. See $LOGFILE for details."
                exit 0
                ;;
            *)
                SKIPPED_LINES["$TRIMMED"]=1
                echo "$(date) SKIPPED $FILE:$LINE_NUM :: $TRIMMED" >> "$LOGFILE"
                ;;
        esac
    done
done

echo ""
echo "=========================================="
echo "Done. $TOTAL_REMOVED line(s) removed."
echo "Full log: $LOGFILE"
echo "=========================================="
