1/*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16#include "erase_commander.h"
17
18#include "flashd_define.h"
19#include "flashd_utils.h"
20#include "updater/updater.h"
21
22
23namespace Flashd {
24namespace {
25constexpr size_t CMD_PARAM_COUNT_MIN = 2;
26}
27
28void EraseCommander::DoCommand([[maybe_unused]] const std::string &cmdParam, [[maybe_unused]] size_t fileSize)
29{
30    FLASHD_LOGI("unsupport");
31}
32
33void EraseCommander::DoCommand(const uint8_t *payload, int payloadSize)
34{
35    FLASHD_LOGI("start to erase");
36    if (payload == nullptr || payloadSize <= 0) {
37        NotifyFail(CmdType::ERASE);
38        FLASHD_LOGI("payload is null or payloadSize is invaild");
39        return;
40    }
41
42    std::string cmdParam(reinterpret_cast<const char *>(payload), payloadSize);
43    auto params = Split(cmdParam, { "-f" });
44    if (params.size() < CMD_PARAM_COUNT_MIN) {
45        NotifyFail(CmdType::ERASE);
46        FLASHD_LOGE("param is invaild");
47        return;
48    }
49    if (!DoErase(params[1])) {
50        NotifyFail(CmdType::ERASE);
51        return;
52    }
53    NotifySuccess(CmdType::ERASE);
54}
55
56bool EraseCommander::DoErase(const std::string &partitionName) const
57{
58    FLASHD_LOGI("start to erase %s", partitionName.c_str());
59    Partition part(partitionName);
60    if (auto ret = part.DoErase(); ret != 0) {
61        FLASHD_LOGE("DoErase fail, ret = %d", ret);
62        return false;
63    }
64    return true;
65}
66
67void EraseCommander::PostCommand()
68{
69    Updater::PostUpdater(false);
70}
71} // namespace Flashd