#include <phpcpp.h>
#include <string.h>
#include <string>
#include <unistd.h>
#include <errno.h>

//#include <fcntl.h>
//#include <sys/types.h>
//#include <sys/stat.h>
#include <stdio.h>

//#include "crypto.h"
#include "ProtobufLAInitiator.h"
using namespace std;



// #include <unistd.h> 
// based off the example functionreturnvalue.cpp in PHP-CPP 

/**
 *  Namespace to use
 */
//using namespace std; 

#define DECRYPTOR_PORT 3825 
int local_attestation_successful=0;
int __ImageBase=0;

class Mitigator : public Php::Base
{
	private: 
		static std::string mitigator_pubkey_header_value;
		static std::string mitigator_pubkey_header; 
	public:
	// adding to extension throws an error if this method is not public

	static void local_attestation_initiator_wrapper() 
	{
		printf("Hello.\n"); fflush(stdout);
	
		setbuf(stdout,NULL); uint32_t count;
		uint32_t return_sgx; 
		unsigned char* base64_encoded_mitigator_header_and_value = (unsigned char*) malloc(mitigator_pubkey_header.length()+1+216); 
//		unsigned char base64_encoded_mitigator_header[229] ; //216=(ceil(160/3) * 4) + 1 (for null character) + 21 for "Mitigator-Public-Key"
		memcpy(base64_encoded_mitigator_header_and_value, mitigator_pubkey_header.c_str(), mitigator_pubkey_header.length()); 
		return_sgx = local_attestation_initiator(DECRYPTOR_PORT, base64_encoded_mitigator_header_and_value+mitigator_pubkey_header.length());
		if(return_sgx != 0)
		{
			if(return_sgx== 0xFFFFFFFF)
			{
				perror("\nCould not set up the socket: had the following error: "); fflush(stderr);
			}
			else
			{
				printf("\nHad the following error in SGX local attestation: 0x%x", return_sgx);
				fflush(stdout);
			}
		}
		else {
			printf("\nSuccessful LA with port %d.\n", DECRYPTOR_PORT);
			fflush(stdout);
			local_attestation_successful=1; 
			printf("length of string was %d\n", mitigator_pubkey_header.length()); fflush(stdout); 
			mitigator_pubkey_header_value=std::string((char*)base64_encoded_mitigator_header_and_value,mitigator_pubkey_header.length()+216); 
		}

	}


		Mitigator() = default; 
		virtual ~Mitigator() = default;
		// call this function in PHP async or call add_header here. 
		static Php::Value get_mitigator_header() 
		{
			return mitigator_pubkey_header_value; 
		}
		// call this func onRequest 
		static Php::Value php_decrypt_wrapper(Php::Parameters &params   )
		{
			/*
			int counter; 
			unsigned char* plaintext_user_data; 
			unsigned char* ciphertext_user_data;
			unsigned char* base64_encoded_pub_key; 
			Php::Value ciphertext_user_data_obj=params[1]; 
			Php::Value base64_encoded_pub_key_obj=params[0];
			uint32_t ciphertext_length;
			uint32_t plaintext_length;

			ciphertext_length = params[1].size();
			plaintext_user_data = (unsigned char*) malloc(ciphertext_length); 
			// TODO: The arrays returned by the const char* operator in PHP-CPP are highly likely to be null-terminated. 
			ciphertext_user_data = (unsigned char*) static_cast<const char*>(ciphertext_user_data_obj);
                        base64_encoded_pub_key = (unsigned char*) static_cast<const char*>(base64_encoded_pub_key_obj);

			printf("Base64 encoded key:\n");
			for(counter=0; counter < 88; counter++)
				printf("%c ", base64_encoded_pub_key[counter]);
			printf("\n"); fflush(stdout); 

			printf("Ciphertext received:\n");
			for(counter=0 ; counter < ciphertext_length; counter++ )
				printf("0x%02x ", ciphertext_user_data[counter]);
			printf("\n"); fflush(stdout); 

			uint32_t ret_status=decrypt_client_data_through_decryptor(base64_encoded_pub_key, ciphertext_user_data, ciphertext_length, (unsigned char*) plaintext_user_data, &plaintext_length);
			if(ret_status != 0)
			{
				printf("Received error code: 0x%02x\n", ret_status); fflush(stdout);
			}

			printf("Going to return this plaintext:\n");
			for(counter=0;counter<plaintext_length;counter++)
				printf("0x%02x ", plaintext_user_data[counter]);
			fflush(stdout); 

			std::string plaintext_user_data_str = std::string((char*) plaintext_user_data, plaintext_length); 
			// free(plaintext_user_data); // TODO: For some reason, this causes a crash. 
			*/
			return "Miti";//plaintext_user_data_str; plaintext_user_data_obj; // (ciphertext_user_data, ciphertext_length) ; 
		}

};
 
std::string Mitigator::mitigator_pubkey_header_value=std::string("!");
std::string Mitigator::mitigator_pubkey_header=std::string("Mitigator-Public-Key:"); 
extern "C" {	

    // export the "get_module" function that will be called by the Zend engine
    PHPCPP_EXPORT void *get_module()
    {
        // create extension
        static Php::Extension extension("decryptor_la_setup_and_decryption","1.0");
        
        Php::Class<Mitigator> mitigator("Mitigator");
	mitigator.method<&Mitigator::get_mitigator_header>("get_mitigator_header");
//        mitigator.property("mitigator_header", &Mitigator::get_mitigator_header);
	mitigator.method<&Mitigator::local_attestation_initiator_wrapper>("local_attestation_initiator_wrapper"); 
	mitigator.method<&Mitigator::php_decrypt_wrapper>("php_decrypt_wrapper", { Php::ByVal("string", Php::Type::String), Php::ByVal("string", Php::Type::String) }   ); 
        extension.onStartup(&Mitigator::local_attestation_initiator_wrapper);
//	extension.onRequest(&Mitigator::php_decrypt_wrapper); 
        // return the extension module
	extension.add(mitigator); 
        return extension.module();
    }
}
