#include "copy_recursive.h"

#include <library/cpp/regex/pcre/regexp.h>

#include <util/system/fs.h>
#include <library/cpp/logger/global/global.h>

namespace NUtil {
    TVector<TString> CopyRecursive(const TFsPath& from, const TFsPath& to, const char* regPattern, bool force) {
        TVector<TString> res;
        try {
            if (from.IsFile()) {
                to.Parent().MkDirs();
                NFs::Copy(from, to);
            } else {
                to.MkDirs();
                TVector<TFsPath> internals;
                from.List(internals);
                TSimpleSharedPtr<TRegExMatch> re;
                if (regPattern) {
                    re.Reset(new TRegExMatch(regPattern));
                }
                for (ui32 i = 0; i < internals.size(); ++i) {
                    if (!re || re->Match(internals[i].GetName().data())) {
                        if (!!re) {
                            res.push_back(internals[i].GetName());
                        }
                        CopyRecursive(internals[i], to / internals[i].GetName());
                    }
                }
            }
        } catch (...) {
            ERROR_LOG << "Can't copy " << from << " to " << to << " : " << CurrentExceptionMessage() << Endl;
            if (!force)
                throw;
        }
        return res;
    }
}
