@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%7za465\7za.exe
set EXCOMMAND=%SEVENZ% x -aoa -r
set CHKNEST=%SELFDIR%chknest.wsf
if not exist %SEVENZ% goto notfound

rem ==== syntax check ====
if x%1 == x goto syntax
if not x%2 == x set EXCOMMAND=%EXCOMMAND% "-o%~f2"

rem ==== first extraction ====
rem debug
rem echo EXCOMMAND1: %EXCOMMAND% %~f1

%EXCOMMAND% %~f1 || (echo failed to extract %~f1 & goto failed)

rem ==== archive type check ====
%CHKNEST% %~nx1 && goto end

rem chknest.wsf above is made of Windows Scripting Host(JScript),
rem so we have to use following operation if WSH is not available.
rem but this misunderstands the simle .gz/.bz2 (not TARed .tar.gz/.tar.bz2)
rem and causes errors in second extraction.
rem you can avoid aborting by removing "& goto failed" from second extraction,
rem but note that it's not secure and error messages will still appear.
rem ==== archive type check by "if" statement ====
rem if x%~x1 == x.gz goto nest
rem if x%~x1 == x.bz2 goto nest
rem goto end

rem ==== second extraction ====
:nest
rem debug
rem echo EXCOMMAND2: %EXCOMMAND% %~f2\%~n1

%EXCOMMAND% %~f2\%~n1 || (echo failed to extract %~f2\%~n1 & goto failed)
del /F /Q %~f2\%~n1
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
