@echo off
setlocal enabledelayedexpansion

set "TARGET=C:\Users\dohertj2\Desktop\lmxopcua2"
set "REPO=https://gitea.dohertylan.com/dohertj2/lmxopcua.git"

:: Get today's date at midnight in format YYYY-MM-DD 00:00:00
for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /value') do set "DT=%%I"
set "TODAY=%DT:~0,4%-%DT:~4,2%-%DT:~6,2% 00:00:00"

echo ============================================
echo  LmxOpcUa Clean Export
echo ============================================
echo.

:: Step 1: Remove existing folder if it exists, otherwise create it
if exist "%TARGET%" (
    echo Removing existing folder: %TARGET%
    rmdir /s /q "%TARGET%"
    if errorlevel 1 (
        echo ERROR: Failed to remove %TARGET%. Check if files are in use.
        exit /b 1
    )
    echo Removed.
) else (
    echo Target folder does not exist, will be created by git clone.
)
echo.

:: Step 2: Clone the repository
echo Cloning repository to %TARGET%...
git clone "%REPO%" "%TARGET%"
if errorlevel 1 (
    echo ERROR: git clone failed.
    exit /b 1
)
echo Clone complete.
echo.

:: Step 3: Remove all git repository info
echo Removing git repository data...
rmdir /s /q "%TARGET%\.git"
if exist "%TARGET%\.gitattributes" del /f /q "%TARGET%\.gitattributes"
echo Git data removed.
echo.

:: Step 4: Reset all timestamps to today at midnight
echo Setting all timestamps to %TODAY%...

:: Use PowerShell for reliable recursive timestamp setting
powershell -NoProfile -Command ^
    "$target = '%TARGET%'; " ^
    "$date = Get-Date -Year %DT:~0,4% -Month %DT:~4,2% -Day %DT:~6,2% -Hour 0 -Minute 0 -Second 0; " ^
    "Get-ChildItem -Path $target -Recurse -Force | ForEach-Object { " ^
    "    $_.CreationTime = $date; " ^
    "    $_.LastWriteTime = $date; " ^
    "    $_.LastAccessTime = $date; " ^
    "}; " ^
    "$root = Get-Item $target; " ^
    "$root.CreationTime = $date; " ^
    "$root.LastWriteTime = $date; " ^
    "$root.LastAccessTime = $date; " ^
    "Write-Host ('Timestamps set to ' + $date.ToString('yyyy-MM-dd HH:mm:ss') + ' on all files and folders.')"

if errorlevel 1 (
    echo WARNING: Some timestamps may not have been updated.
) else (
    echo Timestamps updated.
)

echo.
echo ============================================
echo  Export complete: %TARGET%
echo ============================================

endlocal
