@ECHO OFF
SETLOCAL

REM Validate the arguments.
IF "%~1" == "" EXIT /B 2
IF NOT "%~4" == "" EXIT /B 2

REM Configure the environment variables.
SET PROJECT_NAME=%~1
SET CONFIGURATION_NAME=%~2
IF "%PROJECT_NAME%" == "UnityWin32" (
	SET TARGET_DIRECTORY_1=%~dp0..\external\UnityApp1\Assets\Plugins\x86_64
	SET TARGET_DIRECTORY_2=%~dp0..\external\TwitchInGamesSDK\Assets\TwitchInGamesSDK\Plugins\x86_64
) ELSE IF "%PROJECT_NAME%" == "UnityAndroid" (
	SET TARGET_DIRECTORY_1=%~dp0..\external\UnityApp1\Assets\Plugins\Android
	SET TARGET_DIRECTORY_2=%~dp0..\external\TwitchInGamesSDK\Assets\TwitchInGamesSDK\Plugins\Android
) ELSE (
	ECHO unknown project
	EXIT /B 1
)
IF "%~3" == "" (
	SET SOURCE_ROOT=%~dp0%PROJECT_NAME%\bin\%CONFIGURATION_NAME%\Unity
) ELSE IF "%~3" == "x86_64" (
	SET SOURCE_ROOT=%~dp0..\x64\%CONFIGURATION_NAME%\UnityWin32
) ELSE (
	ECHO unknown target
	EXIT /B 1
)
SET MONO=%SystemDrive%\Program Files\Unity\Editor\Data\MonoBleedingEdge

REM Perform steps for the given project.
IF "%PROJECT_NAME%" == "UnityAndroid" (
	CALL "%~dp0%PROJECT_NAME%\Android\BuildPlugin.cmd"
	IF ERRORLEVEL 1 GOTO fail
)
FOR %%T IN ("%TARGET_DIRECTORY_1%" "%TARGET_DIRECTORY_2%") DO (
	IF NOT EXIST "%%~T" MD "%%~T"
	FOR %%I IN (dll pdb) DO COPY /Y "%SOURCE_ROOT%.%%I" "%%~T"
	IF "%~3" == "" (
		ECHO Converting PDB file...
		CALL "%MONO%\bin\cli.bat" "%MONO%\lib\mono\4.5\pdb2mdb.exe" "%%~T\Unity.dll"
		IF ERRORLEVEL 1 GOTO fail
		IF "%PROJECT_NAME%" == "UnityAndroid" (
			COPY /Y "%~dp0%PROJECT_NAME%\Android\twiglib\build\outputs\aar\twiglib-release.aar" "%%~T"
			COPY /Y "%~dp0%PROJECT_NAME%\Android\Java-WebSocket-1.3.4.jar" "%%~T"
		)
	) ELSE (
		ECHO Creating fake iOS plug-in assets...
		IF NOT EXIST "%%~T\..\iOS" MD "%%~T\..\iOS"
		ECHO. > "%%~T\..\iOS\Unity.dll"
		ECHO. > "%%~T\..\iOS\libUnityiOS.a"
	)
)

:fail
EXIT /B %ERRORLEVEL%
