#include <fstream>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include "md5.h"

using namespace std;
using namespace security_tools;

int find_index(char * buf, size_t size, const char * tag);

int
main(int argc, char ** argv)
{
   if(argc != 2) {
      cerr << "usage: lock <executable-file>" << endl;
      exit(1);
   }
 
   fstream fs(argv[1], ios::in | ios::out | ios::binary);

   bool found = false;
   if(fs) {
      fs.seekg(0L, ios::end);
      size_t len = fs.tellg();
      char * file = new char[len];
      memset(file, 0, len);
      fs.seekg(0L, ios::beg);
      fs.read(file, len);
      const char * start = "$START$";
      const char * end = "$END$";
      string md5;
      compute_md5(argv[1], md5);
      int ptr1 = find_index(file, len, start);
      int ptr2 = find_index(file, len, end);
      if(ptr1 < ptr2 && ptr1 >= 0 && ptr2 >= 0) {
         found = true;
for(int i = ptr1; i <= ptr2; i++) {
cout << "char[" << i << "]=" << file[i] << endl;
}
         memcpy(&file[ptr1+7], md5.c_str(), md5.size());
         fs.seekg(0L, ios::beg);
         fs.write(file, len);
         fs.flush();
      }
      fs.close();
      delete [] file;
   }

   if(!found) {
      cerr << "unable to lock the exe..." << endl;
      exit(1);
   }

   return 0;
}
