#!/usr/bin/env python3

# /string_search.py --search "//kut.inxs.me/downloads" --dir /opt/scripts_local --ext .sh .conf
# •	--search (required): the string to look for
# •	--dir (optional): the directory to search (default: /opt/scripts_local)
# •	--ext (optional): restrict search to files with specific extensions (e.g. .sh, .py, .conf)
# •	Uses apprise for notifications (via env var in /etc/apprise.env)

import argparse
import os
from pathlib import Path
import subprocess
import sys
import socket

DEFAULT_DIR = "/opt/scripts_local"
ENV_FILE = "/etc/apprise.env"

def load_apprise_url():
    if not os.path.isfile(ENV_FILE):
        print(f"❌ Apprise env file not found at {ENV_FILE}")
        sys.exit(1)
    with open(ENV_FILE) as f:
        for line in f:
            if line.startswith("export APPRISE_URL="):
                return line.strip().split("=", 1)[1].strip('"')
    print("❌ APPRISE_URL not found in env file.")
    sys.exit(1)

def find_matches(search_str, directory, extensions):
    matches = []
    for path in Path(directory).rglob("*"):
        if path.is_file() and (not extensions or any(path.name.endswith(ext) for ext in extensions)):
            try:
                with open(path, "r", encoding="utf-8", errors="ignore") as f:
                    if search_str in f.read():
                        matches.append(str(path))
            except Exception as e:
                print(f"⚠️ Error reading {path}: {e}")
    return matches

def notify_apprise(message, apprise_url):
    subprocess.run(["apprise", "-b", message, apprise_url], check=False)

def main():
    parser = argparse.ArgumentParser(description="Check for string in files and notify via Apprise.")
    parser.add_argument("--search", required=True, help="String to search for")
    parser.add_argument("--dir", default=DEFAULT_DIR, help="Directory to search in")
    parser.add_argument("--ext", nargs="*", help="File extensions to include (e.g. .sh .py)")
    args = parser.parse_args()

    apprise_url = load_apprise_url()
    matches = find_matches(args.search, args.dir, args.ext)

    hostname = socket.gethostname()

    if matches:
        message = (
            f"🚨 On `{hostname}`: Files containing '{args.search}' found:\n"
            + "\n".join(matches)
        )
        print(message)
        notify_apprise(message, apprise_url)
    else:
        print(f"✅ No files containing '{args.search}' found in {args.dir}")

if __name__ == "__main__":
    main()