//
// ext2all.c
//
// List entries in the all directories of the floppy disk.
// Assumes no directory is more than one block in size.
//
// Nick Howe
// Emanuele Altieri
//
///////////////////////////////////////////////////////////////////////////////
//
// HEADER FILES
//

#define __LINUX_PERCPU_H
// avoid including files that generate errors

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <linux/ext2_fs.h>

///////////////////////////////////////////////////////////////////////////////
//
//  DEFINITIONS AND MACROS
//

#define BASE_OFFSET 1024  // beginning of the super block (first group) 
#define USB_DEVICE "/dev/sda1"     // the memory stick device 

#define BLOCK_OFFSET(block) (BASE_OFFSET+(block-1)*block_size)


///////////////////////////////////////////////////////////////////////////////
//
//  main() opens the device and initializes some of the data structures.
//

int main(void) {
  struct ext2_super_block super;
  struct ext2_group_desc group;
  struct ext2_inode inode;
  int i;
  int fd;
  int num_groups;
  static unsigned int block_size = 0; // to be calculated

  // open usb device 
  if ((fd = open(USB_DEVICE, O_RDONLY)) < 0) {
    perror(USB_DEVICE);
    exit(1);  // error while opening the floppy device 
  }

  // read super-block 
  lseek(fd, BASE_OFFSET, SEEK_SET); 
  read(fd, &super, sizeof(super));

  if (super.s_magic != EXT2_SUPER_MAGIC) {
    fprintf(stderr, "Not an Ext2 filesystem\n");
    exit(1);
  }
		
  block_size = 1024 << super.s_log_block_size;

  // create and read in group descriptors
  num_groups = (super.s_blocks_count+super.s_blocks_per_group-1)
    /super.s_blocks_per_group;
  for (i = 0; i < num_groups; i++) {
    lseek(fd,BASE_OFFSET+block_size+i*sizeof(struct ext2_group_desc),SEEK_SET);
    read(fd, &group, sizeof(struct ext2_group_desc));
    printf("Reading group-descriptor %d from device " USB_DEVICE ":\n"
	   "Blocks bitmap block: %u\n"
	   "Inodes bitmap block: %u\n"
	   "Inodes table block : %u\n"
	   "Free blocks count  : %u\n"
	   "Free inodes count  : %u\n"
	   "Directories count  : %u\n\n"
	   ,i,
	   group.bg_block_bitmap,
	   group.bg_inode_bitmap,
	   group.bg_inode_table,
	   group.bg_free_blocks_count,
	   group.bg_free_inodes_count,
	   group.bg_used_dirs_count);    // directories count
  }

  close(fd);
  exit(0);
} // end of main() 

///////////////////////////////////////////////////////////////////////////////
