// --------------------------------------------------------------------
// ipecurl
// --------------------------------------------------------------------
/*

    This file is part of the extensible drawing editor Ipe.
    Copyright (c) 1993-2019 Otfried Cheong

    Ipe is free software; you can redistribute it and/or modify it
    under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    As a special exception, you have permission to link Ipe with the
    CGAL library and distribute executables, as long as you follow the
    requirements of the Gnu General Public License in regard to all of
    the software in the executable aside from CGAL.

    Ipe is distributed in the hope that it will be useful, but WITHOUT
    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
    License for more details.

    You should have received a copy of the GNU General Public License
    along with Ipe; if not, you can find it at
    "http://www.gnu.org/copyleft/gpl.html", or write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

#include <curl/curl.h>
#include <unistd.h>
#include <stdlib.h>

#include "ipebase.h"

using namespace ipe;

#define TEXNAME "ipetemp.tex"
#define PDFNAME "ipetemp.pdf"
#define LOGNAME "ipetemp.log"
#define URLNAME "url.txt"

// --------------------------------------------------------------------

static void usage()
{
  fprintf(stderr,
	  "Usage: ipecurl [ pdflatex | xelatex | lualatex ]\n"
	  "Ipecurl runs a Latex compilation on an cloud service given in 'url.txt'.\n"
	  );
  exit(1);
}

static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
  size_t written = fwrite(ptr, size, nmemb, (FILE *)stream);
  return written;
}

// --------------------------------------------------------------------

int main(int argc, char *argv[])
{
  ipe::Platform::initLib(ipe::IPELIB_VERSION);

  // ensure one arguments
  if (argc != 2)
    usage();

  String command = argv[1];

  if (command != "pdflatex" && command != "xelatex" && command != "lualatex") {
    fprintf(stderr, "Illegal Latex command.\n");
    return -1;
  }

  String url = Platform::readFile(URLNAME);
  if (url.empty() || url.left(4) != "http") {
    fprintf(stderr, "Cannot find url for cloud service in '%s'.\n", URLNAME);
    return -2;
  }

  String tex = Platform::readFile(TEXNAME);

  if (tex.empty()) {
    fprintf(stderr, "Cannot read Latex source from '%s'.\n", TEXNAME);
    return -3;
  }

  FILE * out = fopen(PDFNAME, "wb");
  if (!out) {
    fprintf(stderr, "Cannot open '%s' for writing.\n", PDFNAME);
    return -4;
  }

  CURL *curl = curl_easy_init();

  while (url.right(1) == "\n" || url.right(1) == " " || url.right(1) == "\r")
    url = url.left(url.size() - 1);

  url += "?command=";
  url += command;
  String showUrl = url;
  url += "&text=";
  char * esctex = curl_easy_escape(curl, tex.z(), tex.size());
  url += esctex;
  curl_free(esctex);

  char agent[32];
  sprintf(agent, "ipecurl %d", Platform::libVersion());

  curl_global_init(CURL_GLOBAL_ALL);

  // Switch on full protocol/debug output while testing
  curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L);

  // disable progress meter, set to 0L to enable and disable debug output
  curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);

  curl_easy_setopt(curl, CURLOPT_URL, url.z());

  // TODO: install certificate for the server
  curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);

  curl_easy_setopt(curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP|CURLPROTO_HTTPS);
  curl_easy_setopt(curl, CURLOPT_REDIR_PROTOCOLS,
		   CURLPROTO_HTTP|CURLPROTO_HTTPS);
  curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  curl_easy_setopt(curl, CURLOPT_USERAGENT, agent);
  curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 50L);
  curl_easy_setopt(curl, CURLOPT_POSTREDIR, 7L);
  curl_easy_setopt(curl, CURLOPT_TCP_KEEPALIVE, 1L);
  curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
  curl_easy_setopt(curl, CURLOPT_WRITEDATA, out);
  curl_easy_perform(curl);
  fclose(out);
  curl_easy_cleanup(curl);
  curl_global_cleanup();

  // generate logfile
  FILE *log = Platform::fopen(LOGNAME, "wb");
  fprintf(log, "entering extended mode: using latexonline at '%s'\n", showUrl.z());

  String pdf = Platform::readFile(PDFNAME);
  if (pdf.left(4) != "%PDF") {
    // an error happened during Latex run: pdf is actually a log
    fwrite(pdf.data(), 1, pdf.size(), log);
    unlink(PDFNAME); // kill pdf file
  }
  fclose(log);
  return 0;
}

// --------------------------------------------------------------------
