ShutdownFileCleaner.kt

/*
  Copyright (C) 2026 Sber

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  In any derivative products, you must retain the information of
  owner of the original code and provide clear attribution to the project

  https://dochub.info

  The use of this product or its derivatives for any purpose cannot be a secret.


  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

  Maintainers:
      Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2025

  Contributors:
      Sergeev Viktor <sergeevviktor017@gmail.com>, Sber - 2025
*/

package org.archtool.archloader.service.zip

import java.nio.file.Files
import java.nio.file.Path
import kotlin.io.path.name
import org.slf4j.LoggerFactory
import org.springframework.context.ApplicationListener
import org.springframework.context.event.ContextClosedEvent
import org.springframework.stereotype.Service
import org.archtool.archloader.configuration.properties.ZipProperties
import org.archtool.archloader.service.zip.FileConst.ZIP_NAME_PREFIX

@Service
class ShutdownFileCleaner(
    private val zipProperties: ZipProperties,
) : ApplicationListener<ContextClosedEvent> {

    private val log = LoggerFactory.getLogger(javaClass)

    override fun onApplicationEvent(event: ContextClosedEvent) {
        val tmpDir = zipProperties.tmpDir
        if (zipProperties.deleteFilesOnShutdown) {
            log.info("Очистка {} после завершения работы включена", tmpDir)
            Files.newDirectoryStream(tmpDir).use { stream ->
                stream.forEach { path ->
                    deleteRecursively(path)
                }
            }
        } else {
            log.info(
                "Очистка {} после завершения работы не производится, т.к. выключен флаг очистки (seaf.zip.delete-files-on-shutdown)",
                tmpDir
            )
        }
    }

    private fun deleteRecursively(path: Path) {
        if (Files.isDirectory(path)) {
            Files.newDirectoryStream(path).use { stream ->
                stream.forEach { deleteRecursively(it) }
            }
        }
        if (!path.name.startsWith(ZIP_NAME_PREFIX)) {
            log.debug(
                "Видим файл {}, но он не удален, т.к. не начинается с нашего префикса {}, если требуется, то удалить вручную",
                path,
                ZIP_NAME_PREFIX
            )
            return
        }
        val isDeleted = Files.deleteIfExists(path)
        if (isDeleted) {
            log.debug("Удален старый каталог/файл по пути {}", path)
        }
    }

}