/* Undelete.c: A program to recover deleted files.

   This program will scan a disk for the given filename, and copy the file
to another disk if found.  It is NOT case sensitive, and will find all
copies of the file on the disk with the same name.

   When the file is copied, the number of the first block of the file is
appended to the name to keep multiple copies from overwriting each other.

author: James Cooper Jr.
	113-1B Collier Pl.
	Cary, NC  27513

With thanks to:
	Tom Wilcox
	3047 Cameron Way
	Santa Clara, CA 95051

for his fixdisk.c program.  This program is given to the public domain, but
please keep the credits intact.

First Version:	July, 1986	(It works!)
Second Version: March, 1988	(Added ability to specify destination path)
*/

#include <exec/types.h>
#include <exec/nodes.h>
#include <exec/lists.h>
#include <exec/memory.h>
#include <exec/interrupts.h>
#include <exec/ports.h>
#include <exec/libraries.h>
#include <exec/io.h>
#include <exec/tasks.h>
#include <exec/execbase.h>
#include <exec/devices.h>
#include <devices/trackdisk.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>

#include <proto/dos.h>
#include <proto/exec.h>

#define BLOCKSIZE TD_SECTOR

struct MsgPort *diskport;
struct IOExtTD *diskreq;

#define NAMELENGTH 408
#define FILENAME   409
#define TypeDATA    8L

struct DataBlock
{
  ULONG type, key, seqnum, size, next, checksum;
  UBYTE data[BLOCKSIZE-24];
};

struct DataBlock *Data = NULL;

int blocks = 0;

extern struct MsgPort *CreatePort();
extern struct IORequest *CreateExtIO();

ULONG diskChangeCount;

char name[80];
char *dest = "DF1:";

int ReadBlock(ULONG, char *);
void MotorOn();
void MotorOff();
int CopyFile(LONG);
int StrComp(char *, char *);
void Cleanup(int);
void main(int, char **);

int ReadBlock (Block, Kind)
ULONG Block;
char *Kind;
{
   diskreq->iotd_Req.io_Length = BLOCKSIZE;
   diskreq->iotd_Req.io_Data = (APTR) Data;
   diskreq->iotd_Req.io_Command = ETD_READ;
   diskreq->iotd_Count = diskChangeCount;
   diskreq->iotd_Req.io_Offset = BLOCKSIZE*Block;
   DoIO(diskreq);

   if (diskreq->iotd_Req.io_Error != 0) {
     printf("*** Can't read %s from block %ld; error %ld\n",
	     Kind,Block,diskreq->iotd_Req.io_Error);
     return (FALSE);
   }
   return (TRUE);
}

void MotorOn()
{
    /* TURN ON DISK MOTOR ... old motor state is returned in io_Actual */
    diskreq->iotd_Req.io_Length = 1;  /* 1 => motor is to be turned on */
    diskreq->iotd_Req.io_Command = TD_MOTOR;   /* operate on the motor */
    DoIO(diskreq);
}

void MotorOff()
{
    diskreq->iotd_Req.io_Length = 0; /* 0 => motor is to be turned off */
    diskreq->iotd_Req.io_Command = TD_MOTOR;   /* operate on the motor */
    DoIO(diskreq);
}

int CopyFile(FirstBlock)
LONG FirstBlock;
{
   FILE *file;
   LONG block = FirstBlock;

   printf ("\n\n");

   sprintf (name, "%s%s.%ld", dest, &Data->data [FILENAME], block);
   printf ("Writing file %s\n", name);

   if ((file = fopen (name, "w")) == NULL)
   {
       printf ("Cannot open %s\n\n", name);
       return (0);
   }

   for (block = FirstBlock; block != 0; block = Data->next)
   {
     if (!ReadBlock (block, "file data")) break;

     if (fwrite (Data->data, Data->size, 1, file) != 1)
	printf ("*** Can't write data block %ld from disk block %ld\n",
	Data->seqnum, block);
     blocks = blocks-1;
   }

   if (block==0) { printf ("File %s is complete\n\n", name); }
   else printf ("File %s has been truncated\n\n", name);

   fclose (file);
}

int StrComp(str1, str2)
char *str1, *str2;
{
   int index = 0;

   while (1)
   {
      if (str1[index] == 0 && str2[index] == 0) return(0);
      if (toupper(str1[index]) != toupper(str2[index])) return(-1);
      index++;
   }
}

void Cleanup(code)
int code;
{
  MotorOff();
  if (diskreq) {
    CloseDevice(diskreq);
    DeleteExtIO(diskreq, sizeof(struct IOExtTD));
  }
  if (diskport) DeletePort(diskport);
  if (Data) FreeMem(Data,BLOCKSIZE);
  exit(code);
}

void main(argc, argv)
int argc;
char **argv;
{
  LONG block;
  char *lookedfor;

  if ((argc < 2) || (argv[1][0] == '?')) {
    printf("Usage: Undelete <filename> [<destination path>]\n");
    printf("(default destination path is 'DF1:')\n");
    exit(0);
  }

  lookedfor = argv[1];
  if (argv[2]) {
    if (argv[2][strlen(argv[2])-1] != '/' &&
	argv[2][strlen(argv[2])-1] != ':') {
      printf("%s is an invalid path!  (Must end with ':' or '/')\n",argv[2]);
      exit(10);
    }
    dest = argv[2];
  }

  if ((Data = (struct DataBlock *)AllocMem(BLOCKSIZE,MEMF_CHIP)) == NULL)
    exit(11);

  if ((diskport = CreatePort(0,0)) == 0) Cleanup(12);    /* error */

  /* make an io request block for communicating with the disk */
  diskreq = (struct IOExtTD *)CreateExtIO(diskport,sizeof(struct IOExtTD));

  if (diskreq == 0) Cleanup(13);

  /* open the device for access, unit 0 is builtin drive */
  if (OpenDevice(TD_NAME,0,diskreq,0)) Cleanup(14);

  printf ("Put disk with deleted file in INTERNAL drive.\n");
  printf ("(Cancel the requester if the disk is unreadable.)\n");
  printf ("Press RETURN to begin.\n");

  getchar();

  /* now get the disk change value */
  diskreq->iotd_Req.io_Command = TD_CHANGENUM;
  DoIO(diskreq);
  diskChangeCount = diskreq->iotd_Req.io_Actual;

  printf("Scanning disk for %s...\n", lookedfor);

  for (block = 0; block < 1760; block++) {
    if (ReadBlock(block, "information") && Data->type == TypeDATA) {
      blocks++;
      if (Data->seqnum == 1) {
	if (ReadBlock(Data->key, "file header")) {
	  Data->data [FILENAME + Data->data [NAMELENGTH]] = 0;
	  sprintf (name, "%s", &Data->data [FILENAME]);
	} else
	  name[0] = 0;
	printf("Name = %s\x9bK\r", name);
	if (StrComp(name, lookedfor) == 0) CopyFile (block);
      }
    }
  }
  printf ("\n\nAll disk blocks have been scanned.\n");
  Cleanup(0);
}
