﻿using System.Linq.Expressions;
using System.Net.NetworkInformation;

class FileSearchProgram
{
    static string resultFilePath = "results.txt";

    static void Main(string[] args)
    {
        // Очищаем файл результатов при каждом новом запуске
        File.WriteAllText(resultFilePath, $"Поиск файла начат: {DateTime.Now}\n\n");

        Console.WriteLine("Программа поиска файла в доменных компьютерах");
        LogToFile("Программа поиска файла в доменных компьютерах");

        string fileName = "Monitoring850.exe";
        string searchPath = "D:\\";
        string computersFile = "computers.txt";

        try
        {
            if (!File.Exists(computersFile))
            {
                string error = $"Файл {computersFile} не найден. Создайте файл со списком компьютеров.";
                Console.WriteLine(error);
                LogToFile(error);
                return;
            }

            string[] computers = File.ReadAllLines(computersFile)
                                    .Where(c => !string.IsNullOrWhiteSpace(c))
                                    .ToArray();

            string startMessage = $"Начинаем поиск файла {fileName} в {computers.Length} компьютерах...";
            Console.WriteLine(startMessage);
            LogToFile(startMessage);

            foreach (string computer in computers)
            {
                try
                {
                    if (PingComputer(computer))
                    {
                        string checkingMsg = $"Проверяем компьютер {computer}...";
                        Console.WriteLine(checkingMsg);
                        LogToFile(checkingMsg);

                        string uncPath = $"\\\\{computer}\\{searchPath.Replace(":", "$")}";

                        if (Directory.Exists(uncPath))
                        {
                            SearchFiles(uncPath, fileName);
                        }
                        else
                        {
                            string pathError = $"Путь {uncPath} недоступен на компьютере {computer}";
                            Console.WriteLine(pathError);
                            LogToFile(pathError);
                        }
                    }
                    else
                    {
                        string unavailable = $"Компьютер {computer} недоступен";
                        Console.WriteLine(unavailable);
                        LogToFile(unavailable);
                    }
                }
                catch (Exception ex)
                {
                    string compError = $"Ошибка при обработке компьютера {computer}: {ex.Message}";
                    Console.WriteLine(compError);
                    LogToFile(compError);
                }
            }

            string endMessage = $"\nПоиск завершен: {DateTime.Now}";
            Console.WriteLine(endMessage);
            LogToFile(endMessage);
        }
        catch (Exception ex)
        {
            string fatalError = $"Критическая ошибка: {ex.Message}";
            Console.WriteLine(fatalError);
            LogToFile(fatalError);
        }
    }

    static bool PingComputer(string computerName)
    {
        try
        {
            Ping ping = new Ping();
            PingReply reply = ping.Send(computerName, 1000);
            return reply.Status == IPStatus.Success;
        }
        catch
        {
            return false;
        }
    }

    static void SearchFiles(string path, string fileName)
    {
        try
        {
            foreach (string file in Directory.GetFiles(path, fileName))
            {
                string foundMsg = $"Найден файл: {file}";
                Console.WriteLine(foundMsg);
                LogToFile(foundMsg);
            }

            foreach (string directory in Directory.GetDirectories(path))
            {
                SearchFiles(directory, fileName);
            }
        }
        catch (Exception ex)
        {
            string searchError = $"Ошибка при поиске в {path}: {ex.Message}";
            Console.WriteLine(searchError);
        }
    }

    static void LogToFile(string message)
    {
        try
        {
            File.AppendAllText(resultFilePath, message + Environment.NewLine);
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Ошибка при записи в файл результатов: {ex.Message}");
        }
    }
}