/* cdrestore.c
Copyright (c) 2000-2012 Craig Condit, Stefan Huelswitt.

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

1. Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer. 
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution. 

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 REGENTS 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.
*/

#define _LARGEFILE64_SOURCE
#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>
#ifndef sun
#include <getopt.h>
#endif
#include <netinet/in.h>

#include "cdbackup.h"
#include "virtual.h"
#include "cdrom.h"
#include "misc.h"
#include "debug.h"
#include "version.h"

/* defaults */
char *prg_name ="cdrestore";
int   cd_track =-1;
char *cd_dev   ="/dev/cdrom";
long  cd_len   =333000; /* blocks */
char *multicmd =0;
int   verbose  =0;
int   force    =0;
int   query    =0;
int   verify   =0;
int   ahead    =0;
int   debug    =0;
int   virtual  =0;
char *virt_name=0;

int tracks;
int disknum;
long long totalSize;
struct header_block headersave;

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

void parse_cmdline(char argc, char *argv[]) 
{
  int i;

  while ((i=getopt(argc,argv,"d:l:c:t:qvVFTDRi:"))>0) {
    switch (i) {
       case 'V': fprintf(stderr,"cdrestore "VERSION" (compiled "__DATE__")\n"
	                        "Copyright (C) 2000-2004\n"
			        "This is free software; see the source for copying conditions.\n"
			        "There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A\n"
			        "PARTICULAR PURPOSE.\n");
	         exit(0);
       case 'c': multicmd=optarg; break;
       case 'd': cd_dev=optarg; break;
       case 'q': query=1; break;
       case 'F': force=1; break;
       case 'R': ahead=1; break;
       case 'T': verify=1; break;
       case 'v': verbose=1; break;
       case 'i': virt_name=optarg; virtual=1; break;
       case 'D': verbose=1; debug=1; 
                 DEBUG("cdrestore: DEBUG output enabled ("VERSION")\n");
                 break;
       case 't': errno=0; cd_track=strtol(optarg,NULL,10);
                 if(errno==ERANGE || cd_track<1) serror("Option -t: invalid track (must be >=1)\n");
	         break;
       case 'l': cd_len=(long)(FlexLen(optarg)/CD_FRAMESIZE);
	         break;
       default:  fprintf(stderr,
                         "Usage: %s [OPTION]...\n"
                         "Reads block input from CD-R(W) and writes it to standard output.\n\n"
                         "  -d DEVICE      DEVICE for CD queries (e.g. /dev/sr0)\n"
                         "  -q             query disk and print TOC only\n"
                         "  -t N           restore from track N\n"
                         "  -l N           set media size\n"
                         "  -c COMMAND     call COMMAND on disk change in multi-disk mode\n"
                         "  -T             don't restore, test data integrity only\n"
                         "  -F             force starting restore in the middle of a multi-disk set\n"
                         "  -R             set the kernel read-ahead to zero during restore\n"
                         "  -i IMAGE       use virtual image IMAGE for operation\n"
                         "  -v             be verbose\n"
                         "  -D             enable DEBUG output\n"
                         "  -V             prints version & exits\n"
                         "\n", prg_name);
                 exit(0);
       }
    }

  if(!query && cd_track<0) /* need track number */
    serror("A track number is required.\n");
}

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

void print_track(int track, char *stamp, char *id, int disk, int startsec, int endsec, char flags)
{
  char timestr[32], size[32], flstr[12];

  snprintf(timestr,sizeof(timestr),"%02d/%02d/%04d %02d:%02d",
    (stamp[4]-'0')*10   + (stamp[5]-'0'), 
    (stamp[6]-'0')*10   + (stamp[7]-'0'),
    (stamp[0]-'0')*1000 + (stamp[1]-'0')*100 + (stamp[2]-'0')*10 + (stamp[3]-'0'),
    (stamp[8]-'0')*10   + (stamp[9]-'0'),
    (stamp[10]-'0')*10  + (stamp[11]-'0'));

  if(startsec>=0) snprintf(size,sizeof(size)," %s:",FlexSize(flstr,((long long)(endsec-startsec+1)*CD_FRAMESIZE)));
  else size[0]=0;
  snprintf(flstr,sizeof(flstr),"%c",flags&F_CRC?'C':'.');

  fprintf(stderr,"Track %02d:%s %s Part %d %s : %s\n", track, size, timestr, disk, flstr, id);
  if(startsec>=0) DEBUG("          Start sector %7d Last sector %7d\n",startsec,endsec);
}

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

int restore(int disktrack)
{
  int result=0, i, bytes;
  long long totalRead=0, startPos;
  struct header_block header;
  char buffer[CD_FRAMESIZE];
  struct data_block *db=(struct data_block *)&buffer[0];

  for(i=tracks-1; i>=0; i--) if(toc[i].track_no==disktrack) break;
  if(i<0) { fprintf(stderr, "%s: Can't find track %d\n", prg_name, disktrack); exit(1); }
  startPos=Vseek(i);

  Vread(buffer); totalRead+=CD_FRAMESIZE;
  memcpy(&header,buffer,sizeof(header));
  if(!strncmp(SHORT_HDR,header.id_str,strlen(SHORT_HDR))) {
    if(verbose) {
      fprintf(stderr,"%s: ", prg_name);
      print_track(disktrack, header.t_stamp, header.vol_id, header.disk_set, -1, -1, header.flags);
      }

    if(disknum==1) {
      if(header.disk_set!=1) {
        if(!force) {
          fprintf(stderr,"%s: This is disk %d of the multi-disk set! Use -F if you really want to start with this disk.\n",prg_name,header.disk_set);
          exit(1);
          }
        fprintf(stderr,"%s: This is disk %d of the multi-disk set, but -F forces me to continue!\n",prg_name,header.disk_set);
        disknum=header.disk_set;
        }
      headersave=header;		/* save header for use with disk 2-n */
      }
    else {
      if(strcmp(header.t_stamp,headersave.t_stamp) || strcmp(header.vol_id,headersave.vol_id)) {
        fprintf(stderr,"%s: This disk belongs to the backup set '%s', but you're restoring set '%s'!\n",prg_name,header.vol_id,headersave.vol_id);
        result=-1;
        }
      else if(header.disk_set!=disknum) {
        fprintf(stderr,"%s: Wrong sequence. This is disk %d, but you need disk %d now!\n",prg_name,header.disk_set,disknum);
        result=-1;
        }
      else if(verbose) fprintf(stderr, "%s: Beginning restore (Disk %d)\n", prg_name,disknum);
      }
    }
  else {
    fprintf(stderr, "%s: Track %02d was not created with 'cdbackup'\n", prg_name,disktrack);
    if(disknum==1) exit(1);
    result=-1;
    }

  while(!result) {
    int size;

    DEBUG("\rReading sector %7ld  ",(long)((startPos+totalRead)/CD_FRAMESIZE));
    Vread(buffer);

    size=ntohs(db->datasize);
    if(size>DATASIZE) {
      if(verbose) fprintf(stderr,"%s: Warning! Bad datasize at %lld\n",prg_name,totalRead);
      size=DATASIZE;
      }

    if(db->flags&F_CRC) {
      int l=crc32(buffer,size+DBSIZE);
      if(*((unsigned long *)(&buffer[CD_FRAMESIZE-4]))!=l) {
        if(verbose) fprintf(stderr,"%s: bad CRC checksum at %lld\n",prg_name,totalRead);
        serror("Bad checksum, block corrupted, restore failed");
        }
      }

    totalRead+=CD_FRAMESIZE;

    if(!verify) {
      bytes=write(1,&buffer[DBSIZE],size);
      if(bytes!=size) error("Write failed (stdout)");
      }

    if(db->status == 1) break; 	  /* end of backup*/
    if(db->status == 2) result=1; /* next disk */
    }
  DEBUG("\n");

  /* print status */
  totalSize+=totalRead;
  if(result>=0 && verbose) {
    char str1[16], str2[16];
    fprintf(stderr, "%s: Restore complete. %s read (%s from this disk)\n",
            prg_name,FlexSize(str1,totalSize),FlexSize(str2,totalRead));
    }

  return(result);
}

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

void print_toc()
{
  int i;

  fprintf(stderr,"Tracks: %d\n",tracks);
  VprintSpace();
  fprintf(stderr,"\n");
  
  for(i=0; i<tracks; i++) {
    if(!toc[i].is_data)
      fprintf(stderr,"Track %02d: Non-data\n",toc[i].track_no);
    else if(toc[i].is_cdbackup)
      print_track(toc[i].track_no,toc[i].t_stamp,toc[i].vol_id,toc[i].disk_set,toc[i].sec_start,toc[i].sec_end,toc[i].flags);
    else
      fprintf(stderr,"Track %02d: Data\n", toc[i].track_no);
    }
}

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

int main(int argc, char *argv[])
{
  parse_cmdline(argc, argv);

  disknum=1; totalSize=0;
  Vopen(1); tracks=VreadToc(query || debug);
  if(query || debug) {
    verbose=1;
    print_toc();
    }
  if(!query) {
    int result;
    if(verify) fprintf(stderr,"%s: Verify mode enabled, no data output!\n",prg_name);
    if(ahead) { VgetAhead(); VsetAhead(0); }
    do {
      result=restore(cd_track);
      if(result) {
        if(result>0) { disknum++; cd_track=1; }
        Vclose();
        if(!VisRegular()) {
          fprintf(stderr,"%s: Next disk needed: disk %d from %s\n",prg_name,disknum,headersave.vol_id);
          diskchange(multicmd,cd_dev);
          }
        else if(result<0) break;
        Vopen(1); tracks=VreadToc(0);
	}
      } while(result);
    if(ahead) VsetAhead(1);
    }
  Vclose();
  return 0;
}
