/**
 * Copyright (c) 2020, The Android Open Source Project
 *
 * 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
 *
 * 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.
 */

#include "ProcPidDir.h"

#include "UidProcStatsCollector.h"

#include <android-base/file.h>
#include <android-base/result.h>

#include <errno.h>

namespace android {
namespace automotive {
namespace watchdog {
namespace testing {

using ::android::base::Error;
using ::android::base::Result;
using ::android::base::WriteStringToFile;

namespace {

Result<void> makeDir(std::string path) {
    if (mkdir(path.c_str(), 0700) && errno != EEXIST) {
        return Error() << "Could not mkdir " << path << ": " << strerror(errno);
    }
    return {};
}

}  // namespace

Result<void> populateProcPidDir(const std::string& procDirPath,
                                const std::unordered_map<pid_t, std::vector<pid_t>>& pidToTids,
                                const std::unordered_map<pid_t, std::string>& processStat,
                                const std::unordered_map<pid_t, std::string>& processStatus,
                                const std::unordered_map<pid_t, std::string>& processSmapsRollup,
                                const std::unordered_map<pid_t, std::string>& processStatm,
                                const std::unordered_map<pid_t, std::string>& threadStat,
                                const std::unordered_map<pid_t, std::string>& threadTimeInState) {
    for (const auto& it : pidToTids) {
        // 1. Create /proc/PID dir.
        const auto& pidDirRes = makeDir(StringPrintf("%s/%" PRIu32, procDirPath.c_str(), it.first));
        if (!pidDirRes.ok()) {
            return Error() << "Failed to create top-level per-process directory: "
                           << pidDirRes.error();
        }

        // 2. Create /proc/PID/stat file.
        uint32_t pid = it.first;
        if (processStat.find(pid) != processStat.end()) {
            std::string path = StringPrintf((procDirPath + kStatFileFormat).c_str(), pid);
            if (!WriteStringToFile(processStat.at(pid), path)) {
                return Error() << "Failed to write pid stat file " << path;
            }
        }

        // 3. Create /proc/PID/status file.
        if (processStatus.find(pid) != processStatus.end()) {
            std::string path = StringPrintf((procDirPath + kStatusFileFormat).c_str(), pid);
            if (!WriteStringToFile(processStatus.at(pid), path)) {
                return Error() << "Failed to write pid status file " << path;
            }
        }

        // 4. Create /proc/PID/smaps_rollup file.
        if (processSmapsRollup.find(pid) != processSmapsRollup.end()) {
            std::string path = StringPrintf((procDirPath + kSmapsRollupFileFormat).c_str(), pid);
            if (!WriteStringToFile(processSmapsRollup.at(pid), path)) {
                return Error() << "Failed to write pid smaps_rollup file " << path;
            }
        }

        // 5. Create /proc/PID/statm file.
        if (processStatm.find(pid) != processStatm.end()) {
            std::string path = StringPrintf((procDirPath + kStatmFileFormat).c_str(), pid);
            if (!WriteStringToFile(processStatm.at(pid), path)) {
                return Error() << "Failed to write pid statm file " << path;
            }
        }

        // 6. Create /proc/PID/task dir.
        const auto& taskDirRes = makeDir(StringPrintf((procDirPath + kTaskDirFormat).c_str(), pid));
        if (!taskDirRes.ok()) {
            return Error() << "Failed to create task directory: " << taskDirRes.error();
        }

        // 7. Create /proc/PID/task/TID dirs, /proc/PID/task/TID/stat and
        //    /proc/PID/task/TID/time_in_state files.
        for (const auto& tid : it.second) {
            const auto& tidDirRes = makeDir(
                    StringPrintf((procDirPath + kTaskDirFormat + "/%" PRIu32).c_str(), pid, tid));
            if (!tidDirRes.ok()) {
                return Error() << "Failed to create per-thread directory: " << tidDirRes.error();
            }
            if (threadStat.find(tid) != threadStat.end()) {
                std::string path =
                        StringPrintf((procDirPath + kTaskDirFormat + kStatFileFormat).c_str(), pid,
                                     tid);
                if (!WriteStringToFile(threadStat.at(tid), path)) {
                    return Error() << "Failed to write thread stat file " << path;
                }
            }
            if (threadTimeInState.find(tid) != threadTimeInState.end()) {
                std::string path =
                        StringPrintf((procDirPath + kTaskDirFormat + kTimeInStateFileFormat)
                                             .c_str(),
                                     pid, tid);
                if (!WriteStringToFile(threadTimeInState.at(tid), path)) {
                    return Error() << "Failed to write thread time_in_state file " << path;
                }
            }
        }
    }

    return {};
}

}  // namespace testing
}  // namespace watchdog
}  // namespace automotive
}  // namespace android
