#include "index_dir.h"

#include <util/system/yassert.h>

namespace NRTYServer {
   bool HasIndexNamePrefix(const TStringBuf& indexBasename, const TStringBuf& kindPrefix) noexcept {
        Y_ASSERT(TFsPath(indexBasename).Basename() == indexBasename);
        return indexBasename.StartsWith(kindPrefix.data(), kindPrefix.size());
   }

   bool IsIndexDirOnTmpfs(const TFsPath& indexDir) noexcept {
       Y_ASSERT(indexDir.IsDefined() && indexDir.Exists());

       constexpr auto criterion = [](TFsPath& path) {
           //We have no access to statfs(2) - it would need approval from g:util
           static const TFsPath devVfs = TFsPath("/dev").Fix();
           static const TFsPath shmVfs = TFsPath("/run/shm").Fix();
           return path.IsAbsolute() && (path.IsSubpathOf(devVfs) || path.IsSubpathOf(shmVfs));
       };

       try {
           TFsPath path(indexDir); //a copy (see the 'racy' comments in TFsPath::GetSplit())
           if (criterion(path)) {
               return true;
           }
           if (!path.Exists()) {
               return false;
           }
           path = path.RealPath(); //read symlinks, etc.
           return criterion(path);
       } catch(...) {
           return false;
       }
   }
}
