@echo off

rem usage: "extract.bat archive.tar.gz outputdir"
rem usage: outputdir should not contain trailing "\"

rem %SELFDIR% is based on this .bat

rem ==== setup ====
setlocal
rem this includes trailing "\"
set SELFDIR=%~dp0
rem debug
rem echo SELFDIR: %SELFDIR%
set EXITCODE=0
set SEVENZ="%SELFDIR%7za916\7za.exe"
set EXCOMMAND=%SEVENZ% x -aoa -r
set CHKNEST="%SELFDIR%chknest.wsf"
set CHKNESTBAT="%SELFDIR%chknest.bat"
if not exist %SEVENZ% goto notfound

rem ==== syntax check ====
if x%1 == x goto syntax
if x%2 == x goto syntax

rem ==== archive type check ====
rem we cant use this syntax for batch file.
rem     call %CHKNESTBAT% "%~n1" || goto nest
rem "exit /b value" in batch file changes only %ERRORLEVEL% of parent batch file
call %CHKNESTBAT% "%~n1" & if ERRORLEVEL 1 goto nest

rem ==== straight extraction ====
:straight
echo INFO: straight extraction
%EXCOMMAND% "-o%~f2" "%~f1" || (echo failed to extract "%~f1" & goto failed)
goto end

rem ==== nesting extraction ====
:nest
echo INFO: nesting extraction
(%EXCOMMAND% "%~f1" -so | %EXCOMMAND% "-o%~f2" "-si%~n1") || (echo failed to extract "%~f2\%~n1" & goto failed)
goto end

rem ==== errors ====
:syntax
echo ERROR: syntax error
set EXITCODE=1
goto end


:notfound
echo ERROR: cannot find the 7za.exe
set EXITCODE=1
goto end


:failed
echo ERROR: extraction failed
set EXITCODE=1
goto end


:end
exit /b %EXITCODE%
endlocal
