Imports System.Diagnostics
Imports System.Environment
Imports System.IO
Imports System.Reflection

Module FFMP4_Wrapper_Module

    Sub Main(ByVal args() As String)
        Console.WriteLine("FFmp3_Wrapper: Dieses Programm dient als Bridge für FFmpeg (GPL).")

        If args.Length = 0 Then
            Console.Error.WriteLine("FEHLER: Keine Kommandozeilen-Argumente übergeben.")
            ExitCode = 1
            Exit Sub
        End If

        Dim quotedArgs As New List(Of String)()
        For Each arg In args
            If Not arg.StartsWith("""") AndAlso arg.Contains(" ") AndAlso (arg.Contains(":") OrElse arg.Contains("\")) Then
                quotedArgs.Add($"""{arg}""")
            Else
                quotedArgs.Add(arg)
            End If
        Next

        Dim ffmpegArgs As String = String.Join(" ", quotedArgs)

        Call StartFFmpegProcess(ffmpegArgs)
    End Sub

    Private Sub StartFFmpegProcess(ByVal args As String)

        Dim wrapperDir As String = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
        Dim ffmpegExePath As String = Path.Combine(wrapperDir, "ffmpeg.exe")

        If Not File.Exists(ffmpegExePath) Then
            Console.Error.WriteLine($"FEHLER: Die Datei '{ffmpegExePath}' wurde nicht gefunden.")
            ExitCode = 2
            Exit Sub
        End If

        Dim startInfo As New ProcessStartInfo With {
            .FileName = ffmpegExePath,
            .Arguments = args,
            .WorkingDirectory = wrapperDir,
            .UseShellExecute = False,
            .RedirectStandardOutput = True,
            .RedirectStandardError = True,
            .CreateNoWindow = True
        }

        Using ffmpegProcess As New Process With {.StartInfo = startInfo}

            AddHandler ffmpegProcess.OutputDataReceived, Sub(sender, e)
                                                             If e.Data IsNot Nothing Then Console.WriteLine(e.Data)
                                                         End Sub

            AddHandler ffmpegProcess.ErrorDataReceived, Sub(sender, e)
                                                            If e.Data IsNot Nothing Then Console.Error.WriteLine(e.Data)
                                                        End Sub

            Try
                ffmpegProcess.Start()
                ffmpegProcess.BeginOutputReadLine()
                ffmpegProcess.BeginErrorReadLine()
                ffmpegProcess.WaitForExit()

                ExitCode = ffmpegProcess.ExitCode

            Catch ex As Exception
                Console.Error.WriteLine($"FEHLER beim Starten von FFmpeg: {ex.Message}")
                ExitCode = 3
            End Try
        End Using
    End Sub

End Module
