; Hooks customizadas do instalador NSIS (Tauri)
;
; Objetivo:
; - Remover a marca "Nullsoft Install System" exibida no canto inferior esquerdo
; - Instalar o Raven Service para operacoes privilegiadas sem UAC
;
; Nota: o bundler do Tauri injeta estes macros no script principal do instalador.

BrandingText " "

!macro NSIS_HOOK_PREINSTALL
  ; Para e remove qualquer instancia anterior do servico antes de atualizar
  DetailPrint "Parando servicos anteriores..."

  ; Para o servico
  nsExec::ExecToLog 'sc stop RavenService'

  ; Aguarda o servico parar completamente (ate 10 segundos)
  nsExec::ExecToLog 'powershell -Command "$$i=0; while((Get-Service RavenService -ErrorAction SilentlyContinue).Status -eq \"Running\" -and $$i -lt 10){Start-Sleep 1;$$i++}"'

  ; Remove o servico antigo (IMPORTANTE para reinstalacoes)
  DetailPrint "Removendo servico antigo..."
  IfFileExists "$INSTDIR\raven-service.exe" 0 +2
    nsExec::ExecToLog '"$INSTDIR\raven-service.exe" uninstall'

  ; Fallback: remove via sc delete se o executavel nao existir
  nsExec::ExecToLog 'sc delete RavenService'

  ; Forca encerramento de processos remanescentes
  nsExec::ExecToLog 'taskkill /F /IM raven-service.exe'
  nsExec::ExecToLog 'taskkill /F /IM appsdesktop.exe'

  ; Aguarda liberacao dos arquivos e remocao completa do servico
  Sleep 3000
!macroend

!macro NSIS_HOOK_POSTINSTALL
  ; =========================================================================
  ; Instala e inicia o Raven Service
  ; =========================================================================

  DetailPrint "Instalando Raven Service..."

  ; Garante que nao ha servico residual
  nsExec::ExecToLog 'sc delete RavenService'
  Sleep 1000

  ; O servico ja esta em $INSTDIR (copiado como resource pelo Tauri)
  ; Registra o servico Windows
  nsExec::ExecToLog '"$INSTDIR\raven-service.exe" install'
  Pop $0

  ${If} $0 != 0
    DetailPrint "Aviso: Falha ao registrar servico (codigo: $0)"
    ; Tenta remover completamente e reinstalar
    nsExec::ExecToLog '"$INSTDIR\raven-service.exe" uninstall'
    nsExec::ExecToLog 'sc delete RavenService'
    Sleep 1000
    nsExec::ExecToLog '"$INSTDIR\raven-service.exe" install'
    Pop $0
  ${EndIf}

  ; Aguarda registro do servico
  Sleep 500

  ; Inicia o servico
  DetailPrint "Iniciando Raven Service..."
  nsExec::ExecToLog 'sc start RavenService'
  Pop $0

  ${If} $0 == 0
    DetailPrint "Raven Service iniciado com sucesso!"
  ${Else}
    ; Tenta novamente apos breve espera
    Sleep 1000
    nsExec::ExecToLog 'sc start RavenService'
    Pop $0
    ${If} $0 == 0
      DetailPrint "Raven Service iniciado com sucesso (segunda tentativa)!"
    ${Else}
      DetailPrint "Aviso: Servico sera iniciado na proxima reinicializacao (codigo: $0)"
    ${EndIf}
  ${EndIf}

  ; =========================================================================
  ; Verifica se RustDesk esta instalado
  ; Se nao estiver, o Raven Service instalara automaticamente no primeiro uso
  ; =========================================================================

  IfFileExists "$PROGRAMFILES\RustDesk\rustdesk.exe" rustdesk_found rustdesk_not_found

  rustdesk_not_found:
    DetailPrint "RustDesk sera instalado automaticamente pelo Raven Service."
    Goto rustdesk_done

  rustdesk_found:
    DetailPrint "RustDesk ja esta instalado."

  rustdesk_done:
!macroend

!macro NSIS_HOOK_PREUNINSTALL
  ; =========================================================================
  ; Para e remove o Raven Service
  ; =========================================================================

  DetailPrint "Parando Raven Service..."
  nsExec::ExecToLog 'sc stop RavenService'
  Sleep 1000

  DetailPrint "Removendo Raven Service..."
  nsExec::ExecToLog '"$INSTDIR\raven-service.exe" uninstall'

  ; Aguarda um pouco para garantir que o servico foi removido
  Sleep 500
!macroend

!macro NSIS_HOOK_POSTUNINSTALL
  ; Nada adicional necessario
!macroend

