/*
 * © Copyright 1996-2012 ECMWF.
 *
 * This software is licensed under the terms of the Apache Licence Version 2.0
 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
 * In applying this licence, ECMWF does not waive the privileges and immunities
 * granted to it by virtue of its status as an intergovernmental organisation nor
 * does it submit to any jurisdiction.
 */

#define eCMarsCertReply dummyType
#include <setjmp.h>
#include <signal.h>
#include "mars.h"
#undef eCMarsCertReply
#ifdef sgi
#include "eccert.h"
#endif

static jmp_buf env;

static void catch_alarm(int sig) {
    longjmp(env, 1);
}

err certify(request* r, request* e, char* data, int length) {
#ifdef sgi
    char buf[1024 * 10];
    int len;
    char* p;
    eCMarsCertReply info;
    XDR x;
    netblk blk;

    if (!r || !e || !data) {
        marslog(LOG_EROR, "Empty request/certificate");
        return -2;
    }

    if (setjmp(env) != 0) {
        marslog(LOG_EROR, "Timeout while certifying request");
        return -2;
    }

    signal(SIGALRM, catch_alarm);
    alarm(60);

    if (length == 0 || data == 0) {
        marslog(LOG_EROR, "Missing authentication info");
        return -2;
    }


    xdrmem_create(&x, buf, sizeof(buf), XDR_ENCODE);
    memset(&blk, 0, sizeof(blk));

    blk.req = r;
    blk.env = e;
    if (!xdr_netblk(&x, &blk)) {
        marslog(LOG_EROR, "Cannot encode request");
        xdr_destroy(&x);
        return -2;
    }

    len = xdr_getpos(&x);
    xdr_destroy(&x);

    p = verify_ecmars_certificate(
        buf, len, data, length, &info);

    if (info.returnCode) {
        marslog(LOG_EROR, "Authentication failed: %s, %d", p, info.returnCode);
        return -2;
    }

    set_value(e, "user", "%s", info.ecuser);
    new_user(info.ecuser);
    print_all_requests(get_environ());
    print_all_requests(r);

    alarm(0);

#endif
    return 0;
}
