@echo off
setlocal enabledelayedexpansion
title SecureOffice File Type Registration
echo ===================================================
echo  SecureOffice - Đăng ký đuôi .xlsxs và .docxs
echo ===================================================

:: --- Đặt thư mục cố định lưu icon ---
set "ICONDIR=C:\ProgramData\SecureOffice\Icons"

echo [1/5] Tạo thư mục icon vĩnh viễn...
if not exist "%ICONDIR%" mkdir "%ICONDIR%" >nul 2>&1

echo [2/5] Sao chép icon từ thư mục hiện tại vào C:\ProgramData...
set "CURDIR=%~dp0"
copy /Y "%CURDIR%secureexcel.ico" "%ICONDIR%\" >nul 2>&1
copy /Y "%CURDIR%secureword.ico" "%ICONDIR%\" >nul 2>&1

:: --- Lấy đường dẫn Excel và Word ---
echo [3/5] Đang tìm EXCEL.EXE và WINWORD.EXE...
set "EXCELPATH="
set "WORDPATH="

for /f "tokens=2,*" %%A in ('reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\EXCEL.EXE" /ve 2^>nul') do set "EXCELPATH=%%B"
for /f "tokens=2,*" %%A in ('reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WINWORD.EXE" /ve 2^>nul') do set "WORDPATH=%%B"

if "%EXCELPATH%"=="" set "EXCELPATH=C:\Program Files\Microsoft Office\root\Office16\EXCEL.EXE"
if "%WORDPATH%"=="" set "WORDPATH=C:\Program Files\Microsoft Office\root\Office16\WINWORD.EXE"

echo   Excel: %EXCELPATH%
echo   Word : %WORDPATH%

:: --- Ghi registry ---
echo [4/5] Đăng ký định dạng .xlsxs và .docxs...

:: .xlsxs
reg add "HKCR\.xlsxs" /ve /d "SecureExcel.File" /f
reg add "HKCR\.xlsxs" /v "PerceivedType" /d "document" /f
reg add "HKCR\.xlsxs" /v "Content Type" /d "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" /f
reg add "HKCR\SecureExcel.File" /ve /d "Secure Excel Encrypted File" /f
reg add "HKCR\SecureExcel.File\DefaultIcon" /ve /d "\"%ICONDIR%\\secureexcel.ico\"" /f
reg add "HKCR\SecureExcel.File\shell\open\command" /ve /d "\"%EXCELPATH%\" \"%%1\"" /f

:: .docxs
reg add "HKCR\.docxs" /ve /d "SecureWord.File" /f
reg add "HKCR\.docxs" /v "PerceivedType" /d "document" /f
reg add "HKCR\.docxs" /v "Content Type" /d "application/vnd.openxmlformats-officedocument.wordprocessingml.document" /f
reg add "HKCR\SecureWord.File" /ve /d "Secure Word Encrypted File" /f
reg add "HKCR\SecureWord.File\DefaultIcon" /ve /d "\"%ICONDIR%\\secureword.ico\"" /f
reg add "HKCR\SecureWord.File\shell\open\command" /ve /d "\"%WORDPATH%\" \"%%1\"" /f

echo.
echo ✅ Đăng ký hoàn tất!
echo.
echo 🔄 Làm mới icon cache và Windows Explorer...

:: --- Làm mới cache icon / explorer ---

:: 1. Làm mới cache icon (Windows 10/11)
if exist "%SystemRoot%\System32\ie4uinit.exe" (
    ie4uinit.exe -show >nul 2>&1
)

:: 2. Làm mới Explorer (restart nhẹ)
taskkill /IM explorer.exe /F >nul 2>&1
start explorer.exe

echo.
echo ✅ Biểu tượng và liên kết file đã được cập nhật.
echo.
pause
endlocal
exit /b
