#!/bin/bash

BACKUP_DIR=${IMUNIFY360_RESTORE_BACKUP_DIR:-/var/imunify360/restore-files}

STRIP='
BEGIN { cmd = "ipset -n list 2>/dev/null"; while ((cmd | getline name) > 0) exists[name] = 1; close(cmd) }
function tokenize(line, tokens,    n, i, c, tok, quoted) {
    n = 0; tok = ""; quoted = 0
    for (i = 1; i <= length(line); i++) {
        c = substr(line, i, 1)
        if (quoted) {
            if (c == "\\") { i++; tok = tok substr(line, i, 1) }
            else if (c == "\"") quoted = 0
            else tok = tok c
        }
        else if (c == "\"") quoted = 1
        else if (c == " " || c == "\t") { if (tok != "") tokens[++n] = tok; tok = "" }
        else tok = tok c
    }
    if (tok != "") tokens[++n] = tok
    return n
}
function references_missing_imunify_set(rule,    tokens, n, i) {
    n = tokenize(rule, tokens)
    for (i = 1; i < n; i++)
        if (tokens[i] == "--match-set" && index(tokens[i + 1], "i360.") == 1 && !(tokens[i + 1] in exists))
            return 1
    return 0
}
references_missing_imunify_set($0) { removed++; next }
{ print > out }
END { if (close(out) != 0) exit 1; print removed + 0 }'

for file in "$@"; do
    [ -s "$file" ] || continue
    case $file in /*) ;; *) file=$PWD/$file ;; esac
    target=$(readlink -f "$file") || continue
    tmp=$(mktemp "$target.imunify.XXXXXX" 2>/dev/null) || continue

    if removed=$(LC_ALL=C awk -v out="$tmp" "$STRIP" "$file") && [ "$removed" -gt 0 ] && [ -s "$tmp" ]; then
        mkdir -p "$BACKUP_DIR$(dirname "$file")" && chmod 00700 "$BACKUP_DIR" && cp -p "$file" "$BACKUP_DIR$file.backup" \
            && echo "imunify360: original of $file kept as $BACKUP_DIR$file.backup" >&2
        chmod --reference="$file" "$tmp" 2>/dev/null
        chown --reference="$file" "$tmp" 2>/dev/null
        if mv -f "$tmp" "$target"; then
            command -v restorecon >/dev/null 2>&1 && restorecon "$target" 2>/dev/null
            echo "imunify360: removed $removed agent rule(s) from $file" >&2
            continue
        fi
    fi
    rm -f "$tmp"
done
exit 0
