/**
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * This program is free software, you can redistribute it and/or modify it under the terms and conditions of 
 * CANN Open Software License Agreement Version 2.0 (the "License").
 * Please refer to the License for details. You may not use this file except in compliance with the License.
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, 
 * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
 * See LICENSE in the root of the software repository for the full text of the License.
 */

#include "cache/te_cache_utils.h"
#include <fcntl.h>
#include <sys/stat.h>
#include "inc/te_fusion_log.h"
#include "inc/te_fusion_check.h"
#include "inc/te_fusion_util_constants.h"
#include "common/common_utils.h"
#include "common/te_file_utils.h"

namespace te {
namespace fusion {
FILE* TeCacheUtils::LockAndOpenCacheFile(const std::string &cacheDirPath, const std::string &cacheKernelName)
{
    std::string cacheLockRealPath = cacheDirPath + "/" + cacheKernelName + ".lock";
    FILE *fp = fopen(cacheLockRealPath.c_str(), "a+");
    if (fp == nullptr) {
        TE_INFOLOGF("Cannot Open file[%s].", cacheLockRealPath.c_str());
        return nullptr;
    }

    int res = chmod(cacheLockRealPath.c_str(), FILE_AUTHORITY);
    if (res == -1) {
        TE_INFOLOGF("Cannot Update file[%s] authority.", cacheLockRealPath.c_str());
    }

    if (!TeFileUtils::FcntlLockFileSet(fileno(fp), F_WRLCK, 0)) {
        TE_FUSION_LOG_EXEC(TE_FUSION_LOG_WARNING, "Lock file[%s] failed.", cacheLockRealPath.c_str());
        fclose(fp);
        return nullptr;
    }
    TE_INFOLOG("Lock file [%s] success.", cacheLockRealPath.c_str());

    return fp;
}

void TeCacheUtils::UnlockAndCloseCacheFile(FILE *fp)
{
    if (fp == nullptr) {
        return;
    }
    if (!TeFileUtils::FcntlLockFileSet(fileno(fp), F_UNLCK, 0)) {
        TE_INFOLOG("Release file lock not successfully.")
    }
    fclose(fp);
    fp = nullptr;
}
}
}