#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include "fs.h"

int bread(int blkno, void *buf);
int fsfd;

int main(int argc, char *argv[])
{
  if (argc < 2) {
    printf("Usage:df <image(s)>\n");
    return 1;
  }

  printf("Filesystem      Size Used Avail Use%%\n");

  for(int i=1; i < argc; i++) {
    if ((fsfd = open(argv[i], O_RDWR)) < 0) {
      perror(argv[i]);
      exit(1);
    }

    char *iname = strrchr(argv[i], '/');
    if (iname == NULL) iname = argv[i];
    else iname++;

    char bmap[BSIZE];
    struct superblock sb;

    if (bread(1, bmap) != BSIZE) return 1;
    memcpy(&sb, bmap, sizeof(sb));

    int inuse = 0, bn = 0;
    int bpb = BSIZE*8;
  
    for(int blk = sb.bmapstart; bn < 1000 ;blk++) {
      bread(blk, bmap);
      for(int i=0; i < bpb && bn < 1000; i++, bn++) {
	inuse += bmap[bn>>3] & (1<<(bn&7))? 1 : 0;
      }
    }
  
    printf("%-15.15s %-4d %-4d %-5d %-4d\n", iname, 1000, inuse, 1000-inuse, (int)(((float)inuse/1000.0)*100));

    close(fsfd);
  }

  return 0;
}

int bread(int blkno, void *buf)
{
  int n;
  if (lseek(fsfd, blkno*BSIZE, SEEK_SET) != blkno*BSIZE) {
    perror("lseek");
    return -1;
  }
  if ((n = read(fsfd, buf, BSIZE)) < 0) {
    perror("read");
    return -1;
  }
  return n;
}
