#include <fstream.h>
#include <iostream.h>
#include <stdio.h>
#include <hpcxx_rts.h>
#include "ClientServerAttach.h"

void serverAllowAttach(const char *urlName) {
  // output the information that the client will use to attach
  // and then do the attach

  int portNumber = hpcxx_allowAttach(0,NULL,NULL);
  if(portNumber == -1) {
    cout << __FILE__ << " Line : " << __LINE__  << 
      "hpcxx_allowAttach failed." << endl << flush;
    exit(1);
  }
  char hostName[MAXHOSTNAMELEN];
  char domainName[64];
  gethostname(hostName,MAXHOSTNAMELEN);
  getdomainname(domainName,64);

  fstream urlOut(urlName, ios::out);

  if (urlOut.fail()) {
    cout << __FILE__ << " Line : " << __LINE__ << "urlOut failed" << 
      endl << flush;
    exit(1);

  }

  urlOut << hostName << "." << domainName << " " << portNumber << endl;
  urlOut.close();

}

HPCxx_ContextID *clientAttach(const char *urlName) {

  // get the url, read host and port, attach

  FILE *fp = NULL;

  if ((fp = fopen(urlName, "r")) == (FILE *) NULL) {
    cout << __FILE__ << " Line : " << __LINE__ << 
      "client failed to open url file" << endl << flush;
    exit(1);
  }

  char hostName[MAXHOSTNAMELEN+64];
  int port;

  fscanf(fp,"%s %d\n",hostName,&port);
  fclose(fp);

  cout << "client: hostName: " << hostName << endl << flush;
  cout << " port: " << port << endl << flush;

  return(hpcxx_grabContext(hostName,port));

}

