
// This is a modification od imap-ssl.c file
#include<string>
#include<iostream>
std::size_t writeCallback(char *contents, size_t size, size_t nmemb, void *userp)
{
        ((std::string*)userp)->append(contents,size * nmemb);
        return size * nmemb;
}

// This version is UB, because this overload of append expects null-terinated
// string -- there is however no other option to chceck the content of 
// contents buffer, beyond size * nmemb bytes, 
// and it is this overload that seems to produce expected reponse to fetch request
// below 
std::size_t writeCallback_UB(char *contents, size_t size, size_t nmemb, void *userp)
{
        ((std::string*)userp)->append(contents);
        return size * nmemb;
}


#include <stdio.h>
#include <curl/curl.h>

int main(void)
{
//  std::cout << curl_version() << std::endl;
  CURL *curl;
  CURLcode res = CURLE_OK;

  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_USERNAME, "...");
    curl_easy_setopt(curl, CURLOPT_PASSWORD, "...");

    curl_easy_setopt(curl, CURLOPT_URL,
                     "imaps://poczta.interia.pl:993");
 
//    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

   std::string readBuffer;

   curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback_UB);
   curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);


    res = curl_easy_perform(curl);

    if(res != CURLE_OK){
      std::cerr << "curl_easy_perform() failed: " 
                << curl_easy_strerror(res) << std::endl ;
      curl_easy_cleanup(curl);
      return EXIT_FAILURE;
    }


    std::cout << "[Buffer:] "  << std::endl;
    std::cerr << readBuffer  << std::endl;


    // clear the buffer:
    readBuffer.clear();
   
    std::cout << "\n\n[Now custom request:]\n\n" << std::endl;
   
    curl_easy_setopt( curl, CURLOPT_CUSTOMREQUEST,
                      R"(SELECT "INBOX")"
                    );

    res = curl_easy_perform(curl);

    std::cout << "[Buffer:] "  << std::endl;
    std::cerr << readBuffer  << std::endl;

    if(res != CURLE_OK){
      std::cerr << "curl_easy_perform() failed: " 
                << curl_easy_strerror(res) << std::endl ;
      curl_easy_cleanup(curl);
      return EXIT_FAILURE;
    }
    
    std::cout << "[Now CURLOPT_CUSTOMREQUEST]: "  << std::endl;
    readBuffer.clear();
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST,
                     R"(fetch 1 rfc822)"
                    );

    res = curl_easy_perform(curl);

    if(res != CURLE_OK){
      std::cerr << "curl_easy_perform() failed: " 
                << curl_easy_strerror(res) << std::endl ;
      curl_easy_cleanup(curl);
      return EXIT_FAILURE;
    }


    std::cout << "[Buffer :]" << readBuffer <<std::endl;
       
    /* Always cleanup */
    curl_easy_cleanup(curl);
  }

  return (int)res;
}
