/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include "macro.h"
#include "script.h"
#include <unistd.h>

Function* Context::FindLibrary(const char* name, bool& nameFound, int arity, Value* arg)
{
    char* path = getenv("METVIEW_MACRO_PATH");
    char buf[1024];

    if (!path)
        return 0;

    auto* s = (Script*)Current;
    while (s->Owner())
        s = (Script*)s->Owner();

    while (*path) {
        char* p = path;
        while (*path && (*path != ':'))
            path++;

        char q = *path;
        *path = 0;
        sprintf(buf, "%s/%s", p, name);
        *path = q;

        if (access(buf, R_OK) == 0)  //-- file exists?
        {                            //-- yes but is it of executable type?

            //-- here we rely that 'file' returns word 'executable'
            //-- as part of the reply when target is a real executable

            char checkCmd[1024];
            sprintf(checkCmd, "file %s | grep executable", buf);
            int ret = system(checkCmd);

            if (access(buf, X_OK) == 0 && ret == 0) {
                s->AddExtern(name, buf);  //-- A Fortran extern
            }
            else {
                s->Compile(buf);  //-- A script
            }

            Function* v = ((Context*)s)->FindFunction(name, nameFound, arity, arg);
            if (v)
                return v;
        }

        if (*path)
            path++;
    }

    return 0;
}
