/* 
   Clemens Fruhwirth <clemens@endorphin.org>, 2007

   This code binary patches the FAT32/NTFS boot loader to never ever
   use CHS based indexing again. CHS based access is broken when the
   disk geometry for heads and sectors is different from the one
   stored in the BPB. 

   This code is public domain.
*/

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>

int main(int argc, char **argv) {
    int fd=open(argv[1],O_RDWR);
    unsigned char buf[512];
    
    if(fd < -1) {
	perror("Can't open file"); return 1;
    }

    if(read(fd,buf,512) != 512) {
	perror("Can't read file"); return 1;
    }
    
    if(!strncmp(buf+3,"MSWIN4.1",8) && 
       buf[0xE6] == 0x0F &&
       buf[0xE7] == 0x82 &&
       buf[0xE8] == 0x4A &&
       buf[0xE9] == 0x00) {
	printf("FAT32 boot loader detected. Killing CHS code.\n");
	buf[0xE6] = buf[0xE7] = buf[0xE8] = buf[0xE9] = 0x90; // NOP THE CRAP
    } else if(!strncmp(buf+3,"NTFS",4) &&
	      buf[0xD9] == 0x0F &&
	      buf[0xDA] == 0x82 &&
	      buf[0xDB] == 0x3A &&
	      buf[0xDC] == 0x00) {
	    printf("NTFS boot loader detected. Killing CHS code.\n");
	    buf[0xD9] = buf[0xDA] = buf[0xDB] = buf[0xDC] = 0x90; // NOP THE CRAP
    } else {
	fprintf(stderr,"Signature not found. Not an NTFS/FAT32 or already patched.\n");
	return 1;
    }
    lseek(fd,0,SEEK_SET);

    if(write(fd,buf,512) != 512) {
	perror("Can't write file");
	return 1;
    }
    return 0;
}
