:: Name:     updcygwin.cmd
:: Purpose:  Updates Existing Cygwin Installation
:: Author:   mikepruett3@gmail.com
:: Revision: 20170118 - initial version

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS
SET _script=%~n0
SET _parentdir=%~dp0

:: Check if we are interactive
:: https://steve-jansen.github.io/guides/windows-batch-scripting/part-10-advanced-tricks.html
Set interactive=0
ECHO %CMDCMDLINE% | FINDSTR /L %COMSPEC% >NUL 2>&1
IF %ERRORLEVEL% == 0 SET interactive=1

:: Borrowed Code from - https://stackoverflow.com/questions/7985755/how-to-detect-if-cmd-is-running-as-administrator-has-elevated-privileges
NET SESSION > NUL 2>&1
IF %ERRORLEVEL% NEQ 0 (
    ECHO.
    ECHO You are NOT running this script as an administator. Exiting...
    EXIT /B 0
)

:: More Borrowed Code from - http://ss64.com/nt/syntax-64bit.html
:: Installed OS
Set _os_bitness=64
IF %PROCESSOR_ARCHITECTURE% == x86 (
    IF NOT DEFINED PROCESSOR_ARCHITEW6432 Set _os_bitness=32
)

:: Select the correct Cygwin Setup Executable to use
IF %_os_bitness% == 64 (
    Set program=setup-x86_64.exe
    Set arch=x86_64
    set _rootdir=%SYSTEMDRIVE%\cygwin64
    set _cachedir=%SYSTEMDRIVE%\cygtmp
) ELSE (
    Set program=setup-x86.exe
    Set arch=x86
    set _rootdir=%SYSTEMDRIVE%\cygwin
    set _cachedir=%SYSTEMDRIVE%\cygtmp
)
Set download=%_cachedir%\%program%
set _site=http://mirrors.kernel.org/sourceware/cygwin

:: Create RootDir and CacheDir, if they dont exist already
IF NOT EXIST %_rootdir% (
    ECHO .
    ECHO %_rootdir% Not Found!!!
    EXIT /B 0
)
IF NOT EXIST %_cachedir% (
    ECHO .
    ECHO %_cachedir% Not Found!!!
    EXIT /B 0
)

:: Download the latest Cygwin Setup Executable
bitsadmin /transfer myDownloadJob /download /priority normal https://cygwin.com/%program% %download%
ECHO.
ECHO Cygwin Setup Executable downloaded to %download%

:: Find the location to the Cygwin Setup Executable
IF %_os_bitness% == 64 (
    for /f %%i in ('where /R %_cachedir%\ setup-x86_64.exe') do set setup=%%i
) ELSE (
    for /f %%i in ('where /R %_cachedir%\ setup-x86.exe') do set setup=%%i
)

:: Install Cygwin using Quiet Mode with packages
:: Command Line Switches from https://superuser.com/questions/214831/how-to-update-cygwin-from-cygwins-command-line
START "Installing Cygwin" ^
/WAIT ^
%setup% ^
--site %_site% ^
--root %_rootdir% ^
--quiet-mode ^
--upgrade-also

:: Run rebaseall
echo Running rebaseall
"%_rootdir%\bin\dash.exe" -c 'cd /usr/bin; PATH=. ; rebaseall'

:: Pause exiting script if we are run interactivly
IF "%interactive%"=="0" PAUSE
EXIT /B 0