@echo off

rem ===================
rem GLOBAL VARS
rem ===================

set TOOLS=c:\tools
set SCRIPT_SETTINGS=%TOOLS%\scripts\settings.cmd
set COMPANY_SETTINGS=%TOOLS%\company\settings.cmd
set PERSONALFILES_DONE=%LOCALAPPDATA%\.personalfiles_done
set GITWORKDIR=%USERPROFILE%\workspace
set gitrepo=undefined
set gitserver=undefined

rem already done ?
if EXIST %PERSONALFILES_DONE% (
  echo.
  echo This was already DONE!
  echo please remove the file [ %PERSONALFILES_DONE% ] to re-execute this!  
  GOTO END
)

echo ####### %0 #######

rem ===================
rem CONFIGFILE CHECK
rem ===================

echo.
echo searching for SCRIPT settings ...
if NOT EXIST %SCRIPT_SETTINGS% (
  echo INFO: config file %SCRIPT_SETTINGS% NOT FOUND
) else (
  echo OK. Loading SCRIPT settings ...
  call %SCRIPT_SETTINGS%
)

echo.
echo searching for COMPANY settings ...
if NOT EXIST %COMPANY_SETTINGS% (
  echo INFO: config file %COMPANY_SETTINGS% NOT FOUND
) else (
  echo OK. Loading COMPANY settings ...
  call %COMPANY_SETTINGS%
)

echo ++++++++++++++++++
echo GITWORKDIR=%GITWORKDIR%
echo gitserver=%gitserver%
echo gitrepo=%gitrepo%
echo ++++++++++++++++++
echo.

rem GIT folder and REPO ...
echo Creating folder %GITWORKDIR% ...
mkdir %GITWORKDIR% 1>nul 2>nul

if NOT exist %GITWORKDIR% (
  echo ERROR: cannot create folder [ %GITWORKDIR% ] !
  echo ####### %0 #######
  exit /b
)

echo cloning GIT repository ...
cd %GITWORKDIR%
git clone https://%USERNAME%@%gitserver%/%USERNAME%/%gitrepo%.git

if %ERRORLEVEL% NEQ 0 (
  echo ERROR while executing "git clone".
  echo cannot continue!
  echo ####### %0 #######
  exit /b
)

rem Totalcommander ini file ...
if EXIST %GITWORKDIR%\%gitrepo%\WINCMD.ini (
  echo copying ini file for TOTALCOMMANDER ...
  copy /Y %GITWORKDIR%\%gitrepo%\WINCMD.ini %APPDATA%\GHISLER
)

rem Totalcommander ftp config ...
if EXIST %GITWORKDIR%\%gitrepo%\wcx_ftp.ini (
  echo copying TOTALCOMMANDER ftp config file ...
  copy /Y %GITWORKDIR%\%gitrepo%\wcx_ftp.ini %APPDATA%\GHISLER
)

rem SSH keys ...
if EXIST %GITWORKDIR%\%gitrepo% (
  echo copying users SSH keys ...
  copy /Y %GITWORKDIR%\%gitrepo%\id*.* %USERPROFILE%\.ssh 2>nul
)

rem GIT
if EXIST %GITWORKDIR%\%gitrepo%\gitconfig (
  echo copying users gitconfig ...
  copy /Y %GITWORKDIR%\%gitrepo%\gitconfig %USERPROFILE%\.gitconfig
)

rem create a statusfile (this codeblock must be executed only once per user) ...
echo 1 >%PERSONALFILES_DONE%

echo ####### %0 #######

:END

