/**************************************************************************************
 Copyright (c) 2002 The UbixOS Project
 All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions, the following disclaimer and the list of authors.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions, the following disclaimer and the list of authors
in the documentation and/or other materials provided with the distribution. Neither the name of the UbixOS Project nor the names of its
contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

 $Id: ubixfs.c,v 1.22 2003/04/24 05:16:28 reddawg Exp $

**************************************************************************************/

#include <ubixfs/ubixfs.h>
#include <ubixos/file.h>
#include <ubixos/mount.h>
#include <sys/video.h>
#include <sys/drives.h>
#include <ubixos/types.h>
#include <ubixos/fs.h>
#include <ubixos/schedule.h>
#include <lib/kmalloc.h>
#include <lib/string.h>
#include <vmm/paging.h>

int sprintf(char *buf,const char *fmt, ...); //TEMP

int enableUbixFS() {
  //Add UbixFS
  if (!addFs(0,initUbixFS,readUbixFS,writeUbixFS,openFileUbixFS,0x0,0x0,0x0,0x0)) {
    //sysErr(LOG,"Unable To Enable UbixFS");
    return(0);
    }
  //Return
  return(1);
  }
  
void initUbixFS(struct mountPoints *mp) {
  struct ubixFsInfo *fsInfo = 0x0;
  mp->drive->diskLabel = (struct driveDiskLabel *)kmalloc(512,-2);
  mp->drive->read(mp->drive->driveInfoStruct,1,1,mp->drive->diskLabel);
  mp->fsInfo = (struct ubixFsInfo *)kmalloc(sizeof(struct ubixFsInfo),-2);
  fsInfo = mp->fsInfo;
  if ((mp->drive->diskLabel->magicNum == UBIXDISKMAGIC) && (mp->drive->diskLabel->magicNum2 == UBIXDISKMAGIC)) {
    fsInfo->blockAllocationTable = (struct blockAllocationTableEntry *)kmalloc(mp->drive->diskLabel->partitions[mp->partition].pBatSize*512,-2);
    //fsInfo->blockAllocationTable[0].nextBlock = 100;
    fsInfo->batEntries = ((mp->drive->diskLabel->partitions[mp->partition].pBatSize*512)/sizeof(struct blockAllocationTableEntry));
    mp->drive->read(mp->drive->driveInfoStruct,mp->drive->diskLabel->partitions[mp->partition].pOffset,mp->drive->diskLabel->partitions[mp->partition].pBatSize,fsInfo->blockAllocationTable);
    kprintf("UbixFS Initialized\n");
    }
  else {   
    kprintf("Insert System Disk\n");
    initUbixFS(mp);
    }
  //Return
  return;
  }
   
int openFileUbixFS(char *file,fileDescriptor *fd) {
  int x=0;
  struct directoryEntry *dirEntry = (struct directoryEntry *)kmalloc(4096,_current->id);
  struct ubixFsInfo *fsInfo = fd->mp->fsInfo;
  fd->mp->drive->read(fd->mp->drive->driveInfoStruct,(fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[0].realSector),8,dirEntry);
  if (fd->mode == 0) {
    for (x=0;x<(4096/sizeof(struct directoryEntry));x++) {
      if ((int)!kstrcmp(dirEntry[x].fileName,file)) {
        fd->start    = dirEntry[x].startCluster;
        fd->size     = dirEntry[x].size;
        fd->perms    = dirEntry[x].permissions;
        fd->dirBlock = 0x0; //Directory Start Sector
        kfree(dirEntry);
        return((int)1);
        }
      }
    }
  else if (fd->mode == 1) {
    for (x=0;x<(4096/sizeof(struct directoryEntry));x++) {
      if (dirEntry[x].attributes == 0x0) {
        sprintf(dirEntry[x].fileName,file);
        dirEntry[x].size         = 0x0;
        dirEntry[x].startCluster = 0x0;
        fd->size     = 0x0;
        fd->start    = 0x0;
        fd->dirBlock = 0x0;
        fd->mp->drive->write(fd->mp->drive->driveInfoStruct,(fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[0].realSector),8,dirEntry);
       kfree(dirEntry);
       return((int)1);
        }
      }
    }
  kfree(dirEntry);
  return((int)0);
  }

int writeFileByte(int ch,fileDescriptor *fd,long offset) {

  int blockCount = 0x0,batIndex = 0x0,batIndexPrev = fd->start,i = 0x0;
  struct directoryEntry *dirEntry = 0x0;
  struct ubixFsInfo *fsInfo = fd->mp->fsInfo;

  //Find Out How Many Blocks Long This File Is
  blockCount = (offset/4096);
  
  //Find The Block If It Doesn't Exist We Will Have To Allocate One
  for (i=0x0;i<=fd->mp->drive->diskLabel->partitions[fd->mp->partition].pBatSize;i++) {
    batIndex = fsInfo->blockAllocationTable[batIndexPrev].nextBlock;
    if (batIndex == 0x0) {
      break;
      }
    batIndexPrev = batIndex;
    }

  if ((offset%4096 == 0) && (fd->status == fdRead)) {
      fd->status = fdOpen;
      }    

  //If batIndex == 0x0 Then We Must Allocate A New Block
  if (batIndex == 0x0) {
    for (i=1;i < fsInfo->batEntries;i++) {
      if (fsInfo->blockAllocationTable[i].attributes == 0x0) {
        fsInfo->blockAllocationTable[batIndexPrev].nextBlock = i;
        fsInfo->blockAllocationTable[batIndex].nextBlock     = 0x0;
        batIndex  = i;
        fd->start = i;
        break;
        }
      }
    //fd->mp->drive->read(fd->mp->drive->driveInfoStruct,diskLabel->partitions[0].pOffset+blockAllocationTable[batIndex].realSector,8,fd->buffer);
    fd->buffer[offset-(blockCount*4096)] = ch;
    fd->mp->drive->write(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,8,fd->buffer);
    }
  else {
    if (fd->status != fdRead) {    
      fd->mp->drive->read(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,8,fd->buffer);
      fd->status = fdRead;
      }
    fd->buffer[offset-(blockCount*4096)] = ch;
    fd->mp->drive->write(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,8,fd->buffer);
    }    
  if (offset > fd->size) {
    fd->size = offset;
    dirEntry = (struct directoryEntry *)kmalloc(4096,-2);
    fd->mp->drive->read(fd->mp->drive->driveInfoStruct,(fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[fd->dirBlock].realSector),8,dirEntry);
    for (i=0x0;i<(4096/sizeof(struct directoryEntry));i++) {
      if ((int)!kstrcmp(dirEntry[i].fileName,fd->fileName))
        break;
      }  
    dirEntry[i].size = fd->size;
    fd->mp->drive->write(fd->mp->drive->driveInfoStruct,(fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[fd->dirBlock].realSector),8,dirEntry);
    kfree(dirEntry);
    }
  return(ch);
  }

//Verified Functions

/************************************************************************

Function: int readUbixFS(fileDescriptor *fd,char *data,long offset,long size)
Description: Read File Into Data
Notes:

************************************************************************/
int readUbixFS(fileDescriptor *fd,char *data,long offset,long size) {
  int blockCount = 0x0,batIndex = fd->start;
  long i = 0x0;
  struct ubixFsInfo *fsInfo = fd->mp->fsInfo;
  blockCount = ((offset)/4096);
  //Find The Starting Block
  for (i=1;i<=blockCount;i++) {
    batIndex = fsInfo->blockAllocationTable[batIndex].nextBlock;
    if (batIndex == 0x0) {
      //sysErr(log, "Invalid File Offset");
      return(0);
      }
    }
  //If The File Size Is Greater Then The Offset Lets Goto Work
  fd->mp->drive->read(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,blockSize,fd->buffer);
  for (i=0x0;i<size;i++) {
    if (offset > fd->size) {
      //Set File EOF If There Is Nothing To Do
      data[i] = '\0';
      fd->status = fdEof;
      return(size);
      }
    //Copy Data From Buffer To Data
    data[i] = fd->buffer[offset-(blockCount*4096)];
    offset++;
    if (offset%4096 == 0) {
      batIndex = fsInfo->blockAllocationTable[batIndex].nextBlock;
      fd->mp->drive->read(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,blockSize,fd->buffer);
      blockCount++;
      }
    }
  //Return
  return(size);
  }



/************************************************************************

Function: int writeUbixFS(fileDescriptor *fd,char *data,long offset,long size)
Description: Write Data Into File
Notes:

************************************************************************/
int writeUbixFS(fileDescriptor *fd,char *data,long offset,long size) {
  int blockCount = 0x0,batIndex = 0x0,batIndexPrev = fd->start;
  long i = 0x0,x = 0x0;
  struct directoryEntry *dirEntry = 0x0;
  struct ubixFsInfo *fsInfo = fd->mp->fsInfo;
  blockCount = ((offset)/4096);
  if (fd->size != 0) {
    for (i=1;i<=blockCount;i++) {
      batIndex = fsInfo->blockAllocationTable[batIndexPrev].nextBlock;
      if (batIndex == 0x0) {
        //sysErr(log, "Invalid File Offset");
        break;
        }
      batIndexPrev = batIndex;
      }
    }
  if (batIndex != 0x0) {
    fd->mp->drive->read(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,blockSize,fd->buffer);
    }
  else {
    for (i=1;i < fsInfo->batEntries;i++) {
      if (fsInfo->blockAllocationTable[i].attributes == 0x0) {
        fsInfo->blockAllocationTable[i].nextBlock     = 0x0;
        fsInfo->blockAllocationTable[i].attributes    = 0x1;
        batIndex  = i;
        fd->start = i;
        break;
        }
      }
    }
  for (x=0x0;x<size;x++) {
    fd->buffer[offset-(blockCount*4096)] = data[x];
    offset++;
    if (offset%4096 == 0) {
      fd->mp->drive->write(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,blockSize,fd->buffer);
      batIndexPrev = batIndex;
      if (fsInfo->blockAllocationTable[batIndex].nextBlock == 0x0) {
        for (i=1;i < fsInfo->batEntries;i++) {
          if (fsInfo->blockAllocationTable[i].attributes == 0x0) {
            fsInfo->blockAllocationTable[batIndexPrev].nextBlock = i;
            fsInfo->blockAllocationTable[i].attributes    = 0x1;
            fsInfo->blockAllocationTable[i].nextBlock     = 0x0;
            batIndex  = i;
            break;
            }
          }
        }
      else {
        batIndex = fsInfo->blockAllocationTable[batIndex].nextBlock;
        fd->mp->drive->read(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,blockSize,fd->buffer);
        }
      blockCount++;
      }
    }
  fd->mp->drive->write(fd->mp->drive->driveInfoStruct,fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,blockSize,fd->buffer);
  if (offset > fd->size) {
    fd->size = offset;
    dirEntry = (struct directoryEntry *)kmalloc(4096,-2);
    fd->mp->drive->read(fd->mp->drive->driveInfoStruct,(fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[fd->dirBlock].realSector),blockSize,dirEntry);
    for (i=0x0;i<(4096/sizeof(struct directoryEntry));i++) {
      if ((int)!kstrcmp(dirEntry[i].fileName,fd->fileName))
        break;
      }
    dirEntry[i].size = fd->size;
    dirEntry[i].startCluster = fd->start;
    fd->mp->drive->write(fd->mp->drive->driveInfoStruct,(fd->mp->drive->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[fd->dirBlock].realSector),blockSize,dirEntry);
    kfree(dirEntry);
    }
  //Return
  return(size);
  }