@echo off
chcp 65001 >nul
setlocal EnableExtensions EnableDelayedExpansion
cd /d "%~dp0"
title OK ITHAKI - PUBLISH SIGNED APK TO SITE

echo ============================================================
echo OK ITHAKI - PUBLISH SIGNED APK TO SITE
echo Target: https://www.ok-ithaki.gr/downloads/ok-ithaki.apk
echo No password is stored in this file.
echo ============================================================

set "APK=%~1"
if not defined APK set /p "APK=Paste the full path of the signed release APK: "
set "APK=%APK:"=%"
if not exist "%APK%" (
  echo ERROR_APK_NOT_FOUND=%APK%
  pause
  exit /b 1
)

where scp >nul 2>&1 || (
  echo ERROR_SCP_NOT_FOUND
  echo Enable Windows OpenSSH Client first.
  pause
  exit /b 1
)
where ssh >nul 2>&1 || (
  echo ERROR_SSH_NOT_FOUND
  echo Enable Windows OpenSSH Client first.
  pause
  exit /b 1
)

if not exist OUTPUT mkdir OUTPUT
copy /Y "%APK%" "OUTPUT\ok-ithaki.apk" >nul || goto :fail
for /f "tokens=*" %%H in ('powershell -NoProfile -Command "(Get-FileHash -Algorithm SHA256 -LiteralPath ''%CD%\OUTPUT\ok-ithaki.apk'').Hash.ToLower()"') do set "SHA=%%H"
if not defined SHA goto :fail
>"OUTPUT\ok-ithaki.apk.sha256" echo !SHA!  ok-ithaki.apk

echo APK_SHA256=!SHA!
echo Uploading signed APK and checksum...
scp -o StrictHostKeyChecking=no "OUTPUT\ok-ithaki.apk" "OUTPUT\ok-ithaki.apk.sha256" "REMOTE_PUBLISH_OK_ITHAKI_APK.sh" root@185.185.80.71:/tmp/ || goto :fail
ssh -tt -o StrictHostKeyChecking=no root@185.185.80.71 "chmod +x /tmp/REMOTE_PUBLISH_OK_ITHAKI_APK.sh && /tmp/REMOTE_PUBLISH_OK_ITHAKI_APK.sh" || goto :fail

echo ============================================================
echo APK_PUBLISH_RESULT=COMPLETED
echo Download: https://www.ok-ithaki.gr/downloads/ok-ithaki.apk
echo Checksum: https://www.ok-ithaki.gr/downloads/ok-ithaki.apk.sha256
echo ============================================================
pause
exit /b 0

:fail
echo APK_PUBLISH_RESULT=FAILED
pause
exit /b 1
