// Copyright 2023-2024 Gentoo Authors
// Distributed under the terms of the GNU General Public License v2

namespace Gdmt.CleanTmp

module Private =
    open System.IO

    open SimpleLog.SimpleLog

    let UnwantedFileGlobs =
        [ "CoreFxPipe_PSHost.*"
          "MSBuild*"
          "NuGetScratch*"
          "System.IO.Directory System.Runtime*"
          "System.IO.File System.Runtime*"
          "clr-debug-pipe-*"
          "dotnet-diagnostic-*"
          "system-commandline-sentinel-files" ]

    let DirectoryDeleteRecursive (path: string) : unit = Directory.Delete(path, true)

    let CleanUnwantedFilesFromTmpdir (path: string) (dryRun: bool) : unit =
        for unwantedFileGlob in UnwantedFileGlobs do
            let unwantedFiles =
                Directory.GetDirectories(path, unwantedFileGlob)
                |> Array.append (Directory.GetFiles(path, unwantedFileGlob))

            for unwantedFile in unwantedFiles do
                let (fileType: string, removalFunction: string -> unit) =
                    match unwantedFile with
                    | d when Directory.Exists d -> ("dir ", DirectoryDeleteRecursive)
                    | _ -> ("file", File.Delete)

                LogMessage Debug $"Discovered {fileType} {unwantedFile}"

                if not dryRun then
                    try
                        removalFunction unwantedFile

                        LogMessage Success $"Successfully removed {fileType} {unwantedFile}"
                    with ex ->
                        LogMessage Error $"Failed to remove {fileType} {unwantedFile}"
                        LogMessage Error ex.Message
