/*
  cc -g -c isofs_wrap.c
*/

/*
  libisofs related functions of libisoburn.

  Copyright 2007 Vreixo Formoso Lopes <metalpain2002@yahoo.es>
                 Thomas Schmitt <scdbackup@gmx.net>
*/

#include <stdlib.h>
#include <string.h>
#include <assert.h>

#include <libburn/libburn.h>

/* >>> NG */
#include <libisofs/nglibisofs.h>

#include "isoburn.h"
#include "libisoburn.h"

#define BP(a,b) [(b) - (a) + 1]

struct ecma119_pri_vol_desc
{
	uint8_t vol_desc_type		BP(1, 1);
	uint8_t std_identifier		BP(2, 6);
	uint8_t vol_desc_version	BP(7, 7);
	uint8_t unused1			BP(8, 8);
	uint8_t system_id		BP(9, 40);
	uint8_t volume_id		BP(41, 72);
	uint8_t unused2			BP(73, 80);
	uint8_t vol_space_size		BP(81, 88);
	uint8_t unused3			BP(89, 120);
	uint8_t vol_set_size		BP(121, 124);
	uint8_t vol_seq_number		BP(125, 128);
	uint8_t block_size		BP(129, 132);
	uint8_t path_table_size		BP(133, 140);
	uint8_t l_path_table_pos	BP(141, 144);
	uint8_t opt_l_path_table_pos	BP(145, 148);
	uint8_t m_path_table_pos	BP(149, 152);
	uint8_t opt_m_path_table_pos	BP(153, 156);
	uint8_t root_dir_record		BP(157, 190);
	uint8_t	vol_set_id		BP(191, 318);
	uint8_t publisher_id		BP(319, 446);
	uint8_t data_prep_id		BP(447, 574);
	uint8_t application_id		BP(575, 702);
	uint8_t copyright_file_id	BP(703, 739);
	uint8_t abstract_file_id	BP(740, 776);
	uint8_t bibliographic_file_id	BP(777, 813);
	uint8_t vol_creation_time	BP(814, 830);
	uint8_t vol_modification_time	BP(831, 847);
	uint8_t vol_expiration_time	BP(848, 864);
	uint8_t vol_effective_time	BP(865, 881);
	uint8_t file_structure_version	BP(882, 882);
	uint8_t reserved1		BP(883, 883);
	uint8_t app_use			BP(884, 1395);
	uint8_t reserved2		BP(1396, 2048);
};

static
uint32_t iso_read_lsb(const uint8_t *buf, int bytes)
{
	int i;
	uint32_t ret = 0;

	for (i=0; i<bytes; i++) {
		ret += ((uint32_t) buf[i]) << (i*8);
	}
	return ret;
}


/* API function. See libisoburn.h
*/
IsoImage *isoburn_get_attached_image(struct burn_drive *d)
{
 int ret;
 struct isoburn *o= NULL;
 ret = isoburn_find_emulator(&o, d, 0);
 if (ret < 0)
   return NULL;
  
 if (o == NULL) {
   return NULL;
 }
 iso_image_ref(o->image);
 return o->image;
}


/* API function. See libisoburn.h
*/
int isoburn_read_image(struct burn_drive *d,
                       struct isoburn_read_opts *read_opts, 
                       IsoImage **image)
{
 int ret;
 struct iso_read_opts ropts;
 struct iso_read_image_features features;
 enum burn_disc_status status= BURN_DISC_BLANK;
 IsoDataSource *ds= NULL;
 struct isoburn *o= NULL;

 if(read_opts==NULL) {

   /* >>> program error */;

   return(-1);
 }
 if(d != NULL) {
   ret = isoburn_find_emulator(&o, d, 0);
   if (ret < 0)
     return 0;
  
   if (o == NULL) {
     return -1;
   }
   status = isoburn_disc_get_status(d);
 }
 if (d == NULL || status == BURN_DISC_BLANK || read_opts->pretend_blank) {
   
   /*
    * Blank disc, we create a new image without files.
    */
   
   if (d == NULL) {
     /* New empty image without relation to a drive */
     if (image==NULL)
       return -1;
     /* create a new image */
     ret = iso_image_new("ISOIMAGE", image);
     if (ret < 0)
       return ret;
   } else {
     /* Blank new image for the drive */
     iso_image_unref(o->image);
     ret = iso_image_new("ISOIMAGE", &o->image);
     if (ret < 0)
       return ret;
     if (image) {
       *image = o->image;
       iso_image_ref(*image); /*protects object from premature free*/
     }
   }
   return 1;
 }
 
 if (status != BURN_DISC_APPENDABLE && status != BURN_DISC_FULL) {
   /* incorrect disc status */
   return -4;	
 }
 
 memset((char *) &ropts, 0, sizeof(ropts));

 ret = isoburn_disc_get_msc1(d, (int*) &ropts.block);
 if (ret < 0)
   return -2;
 ropts.norock = read_opts->norock;
 ropts.nojoliet = read_opts->nojoliet;
 ropts.preferjoliet = read_opts->preferjoliet;
 ropts.mode = read_opts->mode;
 ropts.uid = read_opts->uid;
 ropts.gid = read_opts->gid;
 ropts.input_charset = read_opts->input_charset;

 /* create the data source */
 ds = isoburn_data_source_new(d);
 ret = iso_image_import(o->image, ds, &ropts, &features);
 iso_data_source_unref(ds);
 if (ret < 0)
   return ret;

 if (image) {
   *image = o->image;
   iso_image_ref(*image); /*protects object from premature free*/
 }

 read_opts->hasRR = features.hasRR;
 read_opts->hasJoliet = features.hasJoliet;
 read_opts->size = features.size;
 return 1;
}


/* API function. See libisoburn.h
*/
int isoburn_attach_image(struct burn_drive *d, IsoImage *image)
{
 int ret;
 struct isoburn *o;

 if (image == NULL)
   return -1;
 ret = isoburn_find_emulator(&o, d, 0);
 if (ret < 0)
   return 0;
 if (o == NULL)
   return -1;
 if(o->image != NULL)
   iso_image_unref(o->image);
 o->image = image;
 return(1);
}


/* API function. See libisoburn.h
*/
int isoburn_activate_session(struct burn_drive *drive)
{
 int ret;
 struct isoburn *o;

 ret = isoburn_find_emulator(&o, drive, 0);
 if (ret < 0)
   return -1;

 if (o->emulation_mode != 1)
   return 1; /* don't need to activate session */
 
 if (o->fabricated_disc_status != BURN_DISC_APPENDABLE)
   return 1;
 
 ret = burn_random_access_write(drive, 0, (char*)o->target_iso_head, 
                                32*2048, 1);

 return ret;
}


/** Initialize the emulation of multi-session on random access media.
    The need for emulation is confirmed already.
    @param o A freshly created isoburn object. isoburn_create_data_source() was
             already called, nevertheless.
    @return <=0 error , 1 = success
*/
int isoburn_start_emulation(struct isoburn *o, int flag)
{
 int ret, i;
 off_t data_count;
 struct burn_drive *drive;
 struct ecma119_pri_vol_desc *pvm;
 
 assert(o);

 drive= o->drive;

 /* we can assume 0 as start block for image */
 /* TODO what about ms? where we validate valid iso image in ms disc? */
 ret = burn_read_data(drive, (off_t) 0, (char*)o->target_iso_head, 
                      sizeof(o->target_iso_head), &data_count, 1);

 /* an error means an empty disc */
 if (ret <= 0) {
   o->fabricated_disc_status= BURN_DISC_BLANK;
   return 1;
 }

 /* check first 64K. If 0's, the disc is treated as a blank disc, and thus
    overwritten without extra check. */
 i = sizeof(o->target_iso_head);
 while (i && !o->target_iso_head[i-1]) 
   --i;

 if (!i) {
   o->fabricated_disc_status= BURN_DISC_BLANK;
   return 1;
 }

 pvm = (struct ecma119_pri_vol_desc *)(o->target_iso_head + 16 * 2048);

 if (!strncmp((char*)pvm->std_identifier, "CD001", 5)) {
   off_t size;

   /* sanity check */
   if (pvm->vol_desc_type[0] != 1 || pvm->vol_desc_version[0] != 1 
       || pvm->file_structure_version[0] != 1 ) {
     /* TODO for now I treat this as a full disc */
     o->fabricated_disc_status= BURN_DISC_FULL;
     return 1;
   }

   /* ok, PVM found, set size */
   size = (off_t) iso_read_lsb(pvm->vol_space_size, 4);
   size *= (off_t) 2048; /* block size in bytes */
   isoburn_set_start_byte(o, size, 0);
   o->fabricated_disc_status= BURN_DISC_APPENDABLE;
 } else if (!strncmp((char*)pvm->std_identifier, "CDXX1", 5)) {

   /* empty image */
   isoburn_set_start_byte(o, (off_t) 0, 0);
   o->fabricated_disc_status= BURN_DISC_BLANK;
 } else {
   /* treat any disc in an unknown format as full */
   o->fabricated_disc_status= BURN_DISC_FULL;
 }
 return 1;
}


/** Alters and writes the first 64 kB of a "media" to invalidate
    an ISO image. (It shall stay restorable by skilled humans, though).
    The result shall especially keep libisoburn from accepting the media
    image as ISO filesystem.
    @param o A fully activated isoburn object. isoburn_start_emulation()
             was already called.
    @return <=0 error , 1 = success
*/
int isoburn_invalidate_iso(struct isoburn *o, int flag)
{
 /* 
  * replace CD001 with CDXX1 in PVM.
  * I think this is enought for invalidating an iso image
  */
 strncpy((char*)o->target_iso_head + 16 * 2048 + 1, "CDXX1", 5);
 return isoburn_activate_session(o->drive);
}