#include "fsync.h"

#include <util/generic/yexception.h>
#include <util/system/file.h>
#include <util/folder/path.h>

namespace {
    void Fsync(const TString& path) {
        TFileHandle dir(path, OpenExisting | RdOnly);
        Y_ENSURE_EX(dir.Flush(), TSystemError() << "Failed to fsync '" << path << "'");
    }
}

void FsyncDirRecursively(const TString& dir, const bool follow) {
    TVector<TFsPath> children;
    TFsPath{dir}.List(children);
    for (const auto& child : children) {
        if (child.IsDirectory() && (follow || !child.IsSymlink())) {
            FsyncDirRecursively(child.GetPath(), follow);
        } else {
            Fsync(child);
        }
    }
    Fsync(dir);
}
