/*****************************************************************************************
 Copyright (c) 2002-2004 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$

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

#include <ubixfs/ubixfs.h>
#include <vfs/file.h>
#include <vfs/mount.h>
#include <sys/video.h>
#include <sys/device.h>
#include <ubixos/types.h>
#include <ubixos/sched.h>
#include <ubixos/kpanic.h>
#include <ubixos/exec.h>
#include <lib/kmalloc.h>
#include <lib/string.h>
#include <lib/kprintf.h>
#include <assert.h>
#include <vmm/paging.h>

int 
ubixfs_init() {

  struct fileSystem ubixFileSystem = 
   {NULL,                         /* prev        */
    NULL,                         /* next        */
    (void *)initUbixFS,           /* vfsInitFS   */
    (void *)readUbixFS,           /* vfsRead     */
    (void *)writeUbixFS,          /* vfsWrite    */
    (void *)openFileUbixFS,       /* vfsOpenFile */
    (void *)ubixFSUnlink,         /* vfsUnlink   */
    (void *)ubixFSmkDir,          /* vfsMakeDir  */
    NULL,                         /* vfsRemDir   */
    NULL,                         /* vfsSync     */
    0                             /* vfsType     */
   }; /* ubixFileSystem */

  /* Add UbixFS */
/* mji
 * if (vfsRegisterFS(0, initUbixFS, readUbixFS, writeUbixFS, openFileUbixFS,
 *                   ubixFSUnlink, ubixFSmkDir, 0x0, 0x0) != 0x0) { 
 */
   if (vfsRegisterFS(ubixFileSystem) != 0x0) {
    kpanic("Unable To Enable UbixFS");
    return(0x1);
    }

  /* Start Up The UbixFS Thread Which Will Manage All The Mounted 
   *  UbixFS Partitions 
   */
  execThread(ubixFS_Thread,(uInt32)(kmalloc(0x2000)+0x2000),0x0);
  /* Return */
  return(0x0);
  }
  
void 
initUbixFS(struct mountPoints *mp) {
  struct ubixFSInfo *fsInfo = 0x0;
  int size;

  assert(mp);
  assert(mp->diskLabel);
  assert(mp->diskLabel->partitions);

  mp->fsInfo = (struct ubixFSInfo *)kmalloc(sizeof(struct ubixFSInfo));
  
  fsInfo = mp->fsInfo;
  fsInfo->rootDir = 0x0;
  //mp->diskLabel->partitions[mp->partition].pOffset -= 63;
  if ((mp->diskLabel->magicNum == UBIXDISKMAGIC) && 
      (mp->diskLabel->magicNum2 == UBIXDISKMAGIC)) {
    size = mp->diskLabel->partitions[mp->partition].pBatSize * 512;
    fsInfo->blockAllocationTable = (struct blockAllocationTableEntry *)kmalloc(size);

    /* fsInfo->blockAllocationTable[0].nextBlock = 100; */
    size = (mp->diskLabel->partitions[mp->partition].pBatSize*512) / sizeof(struct blockAllocationTableEntry);
    fsInfo->batEntries = size;

    assert(mp->device->devInfo->read);

    mp->device->devInfo->read(mp->device->devInfo->info, 
                             fsInfo->blockAllocationTable,
                             mp->diskLabel->partitions[mp->partition].pOffset,
                             mp->diskLabel->partitions[mp->partition].pBatSize);
    //UBU dircache the ubixfs fs info struct fsInfo ->(pointer to) your rootdir thing like fsInfo->rootDirCache=ubifs_dirCacheNode(blah);
    kprintf("  Offset: [%i], Partition: [%i]\n",
            mp->diskLabel->partitions[mp->partition].pOffset,mp->partition);
    kprintf("UbixFS Initialized\n");
    }
  else {   
    kprintf("Insert System Disk!\n");
    while (1);
    initUbixFS(mp);
    }
  /* Return */
  return;
  }
   
int 
openFileUbixFS(char *file, fileDescriptor *fd) {
  int x = 0;
/*mji  long offsets, size; */
  struct directoryEntry *dirEntry = (struct directoryEntry *)kmalloc(0x4000);
  struct ubixFSInfo *fsInfo = fd->mp->fsInfo;
  
  assert(fd);
  assert(fd->mp);
  assert(fd->mp->device);
  assert(fd->mp->device->devInfo);
  assert(fd->mp->device->devInfo->read);

  if (file[0] == '/' && file[1] != '\0') file++;

  fd->mp->device->devInfo->read(fd->mp->device->devInfo->info,
                                dirEntry, 
                                (fd->mp->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[fsInfo->rootDir].realSector),(0x4000/512));
  if ((fd->mode & fileRead) == fileRead) {
    for (x=0;x<(0x4000/sizeof(struct directoryEntry));x++) {
      if ((int)!strcmp(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 & fileWrite) == fileWrite) {
    for (x=0;x<(0x4000/sizeof(struct directoryEntry));x++) {
      if (!strcmp(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(0x1);
        } 
      if (dirEntry[x].attributes == 0x0) {
        sprintf(dirEntry[x].fileName,file);
        dirEntry[x].size         = 0x0;
        dirEntry[x].startCluster = getFreeBlocks(1,fd);
        dirEntry[x].attributes   = typeFile;
        dirEntry[x].permissions  = 3754;
        fd->size       = 0x0;
        fd->start      = dirEntry[x].startCluster;
        fd->dirBlock   = 0x0;
        fd->mp->device->devInfo->write(fd->mp->device->devInfo->info,dirEntry,(fd->mp->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[fsInfo->rootDir].realSector),8);
       kfree(dirEntry);
       return(0x1);
        }
      }
    }
  kfree(dirEntry);
  return(0);
  }

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

  int blockCount = 0x0,batIndex = 0x0,batIndexPrev = 0x0,i = 0x0;
  struct directoryEntry *dirEntry = 0x0;
  struct ubixFSInfo *fsInfo = NULL;

  assert(fd);
  assert(fd->mp);
  assert(fd->mp->diskLabel);

  batIndexPrev = fd->start;
  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->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     = -1;
        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->device->devInfo->write(fd->mp->device->devInfo->info,fd->buffer,fd->mp->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,8);
    }
  else {
    if (fd->status != fdRead) {    
      fd->mp->device->devInfo->read(fd->mp->device->devInfo->info,fd->buffer,fd->mp->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,8);
      fd->status = fdRead;
      }
    fd->buffer[offset-(blockCount*4096)] = ch;
    fd->mp->device->devInfo->write(fd->mp->device->devInfo->info,fd->buffer,fd->mp->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,8);
    }    
  if (offset > fd->size) {
    fd->size = offset;
    dirEntry = (struct directoryEntry *)kmalloc(4096);
    fd->mp->device->devInfo->read(fd->mp->device->devInfo->info,dirEntry,(fd->mp->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[fd->dirBlock].realSector),8);
    for (i=0x0;i<(4096/sizeof(struct directoryEntry));i++) {
      if ((int)!strcmp(dirEntry[i].fileName,fd->fileName))
        break;
      }  
    dirEntry[i].size = fd->size;
    fd->mp->device->devInfo->write(fd->mp->device->devInfo->info,dirEntry,(fd->mp->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[fd->dirBlock].realSector),8);
    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;
  int batIndex; 
  long i = 0x0;
  struct ubixFSInfo *fsInfo = NULL;

  assert(fd);
  assert(fd->mp);
  assert(fd->mp->fsInfo);

  fsInfo = fd->mp->fsInfo;
  batIndex = fd->start;

  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->device->devInfo->read(fd->mp->device->devInfo->info,fd->buffer,fd->mp->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,blockSize);
  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 && offset != size) {
      batIndex = fsInfo->blockAllocationTable[batIndex].nextBlock;
      fd->mp->device->devInfo->read(fd->mp->device->devInfo->info,fd->buffer,fd->mp->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[batIndex].realSector,blockSize);
      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) {
  uInt32 blockOffset    = 0x0;
  uInt32 blockIndex;
  uInt32 blockIndexPrev;
  uInt32 i              = 0x0;
  struct ubixFSInfo *fsInfo = NULL;
  struct directoryEntry *dirEntry = 0x0;

  assert(fd);
  assert(fd->mp);
  assert(fd->mp->fsInfo);
  assert(fd->mp->device);
  assert(fd->mp->device->devInfo);

  blockIndex = blockIndexPrev = fd->start;
  fsInfo = fd->mp->fsInfo;

  blockOffset = (offset/0x1000);

  if (fd->size != 0x0) {
    for (i = 0x0;i < blockOffset;i++) {
      blockIndex = fsInfo->blockAllocationTable[blockIndexPrev].nextBlock;
        if (blockIndex == EOBC) {
          blockIndex = getFreeBlocks(1,fd);
          fsInfo->blockAllocationTable[blockIndexPrev].nextBlock = blockIndex;
          fsInfo->blockAllocationTable[blockIndex].nextBlock = EOBC;
          break;
          }
        blockIndexPrev = blockIndex;
      }
    }

  fd->mp->device->devInfo->read(fd->mp->device->devInfo->info,fd->buffer,fd->mp->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[blockIndex].realSector,blockSize);
  for (i = 0x0;i < size;i++) {

    fd->buffer[(offset- (blockOffset *0x1000))] = data[i];
    offset++;

    if (offset%4096 == 0x0) {
      blockOffset++;
      fd->mp->device->devInfo->write(fd->mp->device->devInfo->info,fd->buffer,fd->mp->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[blockIndex].realSector,blockSize);
 
      if (fsInfo->blockAllocationTable[blockIndex].nextBlock == EOBC) {
        blockIndexPrev = blockIndex;
        blockIndex = getFreeBlocks(1,fd);
        fsInfo->blockAllocationTable[blockIndexPrev].nextBlock = blockIndex;
        fsInfo->blockAllocationTable[blockIndex].nextBlock     = EOBC;
        }
      else {
        blockIndex = fsInfo->blockAllocationTable[blockIndex].nextBlock;
        fd->mp->device->devInfo->read(fd->mp->device->devInfo->info,fd->buffer,fd->mp->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[blockIndex].realSector,blockSize);
        }
      }
    }
  fd->mp->device->devInfo->write(fd->mp->device->devInfo->info,fd->buffer,fd->mp->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[blockIndex].realSector,blockSize);

  if (offset > fd->size) {
    fd->size = offset;
    dirEntry = (struct directoryEntry *)kmalloc(4096);
    fd->mp->device->devInfo->read(fd->mp->device->devInfo->info,dirEntry,(fd->mp->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[fd->dirBlock].realSector),blockSize);
    for (i=0x0;i<(4096/sizeof(struct directoryEntry));i++) {
      if ((int)!strcmp(dirEntry[i].fileName,fd->fileName))
        break;
      }
    dirEntry[i].size = fd->size;
    dirEntry[i].startCluster = fd->start;
    fd->mp->device->devInfo->write(fd->mp->device->devInfo->info,dirEntry,(fd->mp->diskLabel->partitions[fd->mp->partition].pOffset+fsInfo->blockAllocationTable[fd->dirBlock].realSector),blockSize);
    kfree(dirEntry);
    }
  /* Return */
  return(size);
  }

void 
ubixFSUnlink(char *path,struct mountPoints *mp) {
  int x=0;
  struct directoryEntry *dirEntry = (struct directoryEntry *)kmalloc(0x1000);
  struct ubixFSInfo *fsInfo = mp->fsInfo;
  
  mp->device->devInfo->read(mp->device->devInfo->info,dirEntry,(mp->diskLabel->partitions[mp->partition].pOffset+fsInfo->blockAllocationTable[fsInfo->rootDir].realSector),8);

  for (x=0;x<(4096/sizeof(struct directoryEntry));x++) {
    if ((int)!strcmp(dirEntry[x].fileName,path)) {
      dirEntry[x].attributes |= typeDeleted;
      dirEntry[x].fileName[0] = '?';
      mp->device->devInfo->write(mp->device->devInfo->info,dirEntry,(mp->diskLabel->partitions[mp->partition].pOffset+fsInfo->blockAllocationTable[fsInfo->rootDir].realSector),8);
      return;
      }
    }
  kprintf("File Not Found\n");
  return;
  }

/***
 $Log$
 Revision 1.19  2004/07/20 18:09:37  flameshadow
 add: directory caching related stuff

 Revision 1.18  2004/07/17 03:21:34  flameshadow
 chg: cleaned up code; added assert() statements

 Revision 1.15  2004/07/14 12:21:49  reddawg
 ubixfs: enableUbixFs to ubixfs_init
 Changed Startup Routines

 Revision 1.14  2004/06/28 23:12:58  reddawg
 file format now container:/path/to/file

 Revision 1.13  2004/06/28 18:12:44  reddawg
 We need these files

 Revision 1.12  2004/06/28 11:57:58  reddawg
 Fixing Up Filesystem

 Revision 1.10  2004/06/04 13:20:22  reddawg
 ubixFSmkDir(): played with it a bit to see if it still worked

 Revision 1.9  2004/06/04 10:19:42  reddawg
 notes: we compile again, thank g-d anyways i was about to cry

 Revision 1.8  2004/06/01 00:04:53  reddawg
 Try now mark

 Revision 1.7  2004/05/19 15:20:06  reddawg
 Fixed reference problems due to changes in drive subsystem

 Revision 1.6  2004/05/19 04:07:43  reddawg
 kmalloc(size,pid) no more it is no kmalloc(size); the way it should of been

 Revision 1.5  2004/04/29 15:45:19  reddawg
 Fixed some bugs so now the automade images will work correctly

 Revision 1.4  2004/04/28 21:10:40  reddawg
 Lots Of changes to make it work with existing os

 Revision 1.3  2004/04/28 13:33:09  reddawg
 Overhaul to ubixfs and boot loader and MBR to work well with our schema
 now BAT and dir and file entries are all offset 64Sectors from the start of the partition

 Revision 1.2  2004/04/28 02:22:55  reddawg
 This is a fiarly large commit but we are starting to use new driver model
 all around

 Revision 1.1.1.1  2004/04/15 12:07:08  reddawg
 UbixOS v1.0

 Revision 1.31  2004/04/13 16:36:34  reddawg
 Changed our copyright, it is all now under a BSD-Style license

 END
 ***/

