// SPDX-License-Identifier: MPL-2.0
#include "../include/disk.h"
#include <Uefi.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Protocol/BlockIo.h>
#include <Protocol/SimpleFileSystem.h>
#include <Guid/FileInfo.h>
EFI_STATUS bp_disk_check_dir_existence(EFI_FILE_PROTOCOL *root,CHAR16 *dir) {
  EFI_STATUS status;
  EFI_FILE_PROTOCOL *object;
  status=root->Open(root,&object,dir,EFI_FILE_MODE_READ,EFI_FILE_DIRECTORY);
  if (!EFI_ERROR(status)) {
    object->Close(object);
  }
  return status;
}
EFI_STATUS bp_disk_check_file_existence(EFI_FILE_PROTOCOL *root,CHAR16 *file) {
  EFI_STATUS status;
  EFI_FILE_PROTOCOL *object;
  status=root->Open(root,&object,file,EFI_FILE_MODE_READ,0);
  if (!EFI_ERROR(status)) {
    object->Close(object);
  }
  return status;
}
EFI_STATUS bp_disk_open_file(EFI_FILE_PROTOCOL *root,CHAR16 *file,EFI_FILE_PROTOCOL **opened_file) {
  EFI_STATUS status;
  status=root->Open(root,opened_file,file,EFI_FILE_MODE_READ,0);
  return status;
}
EFI_STATUS bp_disk_get_file_info(EFI_FILE_PROTOCOL *opened_file,EFI_FILE_INFO **file_info) {
  EFI_STATUS status;
  UINTN file_info_size=0;
  status=opened_file->GetInfo(opened_file,&gEfiFileInfoGuid,&file_info_size,NULL);
  if (status!=EFI_BUFFER_TOO_SMALL) {
    return status;
  }
  *file_info=AllocateZeroPool(file_info_size);
  if (*file_info==NULL) {
    return EFI_OUT_OF_RESOURCES;
  }
  status=opened_file->GetInfo(opened_file,&gEfiFileInfoGuid,&file_info_size,*file_info);
  return status;
}
EFI_STATUS bp_disk_read_file(EFI_FILE_PROTOCOL *opened_file,bp_disk_FILE **file) {
  EFI_STATUS status;
  if (file==NULL) {
    return EFI_INVALID_PARAMETER;
  }
  *file=AllocateZeroPool(sizeof(bp_disk_FILE));
  if (!*file) {
    return EFI_OUT_OF_RESOURCES;
  }
  EFI_FILE_INFO *file_info;
  status=bp_disk_get_file_info(opened_file,&file_info);
  if (EFI_ERROR(status)) {
    return status;
  }
  (*file)->file_size_bytes=file_info->FileSize;
  FreePool(file_info);
  (*file)->content=AllocateZeroPool((*file)->file_size_bytes);
  if ((*file)->content==NULL) {
    FreePool(*file);
    return EFI_OUT_OF_RESOURCES;
  }
  status=opened_file->Read(opened_file,&((*file)->file_size_bytes),(*file)->content);
  return status;
}
