//
// Copyright (C) 2018 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.
//

#ifndef LIBLP_LIBLP_H
#define LIBLP_LIBLP_H

#include <stddef.h>
#include <stdint.h>

#include <map>
#include <memory>
#include <string>

#include "metadata_format.h"

namespace android {
namespace fs_mgr {

// Helper structure for easily interpreting deserialized metadata, or
// re-serializing metadata.
struct LpMetadata {
    LpMetadataGeometry geometry;
    LpMetadataHeader header;
    std::vector<LpMetadataPartition> partitions;
    std::vector<LpMetadataExtent> extents;
    std::vector<LpMetadataPartitionGroup> groups;
    std::vector<LpMetadataBlockDevice> block_devices;
};
//
// Read logical partition metadata from its predetermined location on a block
// device. If readback fails, we also attempt to load from a backup copy.
std::unique_ptr<LpMetadata> ReadMetadata(const std::string& super_partition, uint32_t slot_number);

// Helper to extract safe C++ strings from partition info.
std::string GetPartitionName(const LpMetadataPartition& partition);
std::string GetPartitionGroupName(const LpMetadataPartitionGroup& group);
std::string GetBlockDevicePartitionName(const LpMetadataBlockDevice& block_device);

// Return the block device that houses the super partition metadata; returns
// null on failure.
const LpMetadataBlockDevice* GetMetadataSuperBlockDevice(const LpMetadata& metadata);

// Return the total size of all partitions comprising the super partition.
uint64_t GetTotalSuperPartitionSize(const LpMetadata& metadata);

// Get the list of block device names required by the given metadata.
std::vector<std::string> GetBlockDevicePartitionNames(const LpMetadata& metadata);

// Slot suffix helpers.
uint32_t SlotNumberForSlotSuffix(const std::string& suffix);
std::string SlotSuffixForSlotNumber(uint32_t slot_number);
std::string GetPartitionSlotSuffix(const std::string& partition_name);

// Helpers for common functions.
const LpMetadataPartition* FindPartition(const LpMetadata& metadata, const std::string& name);
uint64_t GetPartitionSize(const LpMetadata& metadata, const LpMetadataPartition& partition);

}  // namespace fs_mgr
}  // namespace android

#endif  // LIBLP_LIBLP_H
