// deployer BashManager implementation
// Copyright (C) 2024 Jean-Cloud
// GNU General Public License v3

#include <iostream>
#include "BashManager.h"

int BashManager::Execute(string command)
{
    FILE * p = popen(command.c_str(),"r"); 
    if( p == NULL)
    {
        cerr << "Error executing " << command << endl;
        return -1;
    }
    pclose(p);
    return 0;
}

string BashManager::ExecuteAndReadResult(string command)
{
    string result="";
    char lineBuffer [4095]={0}; //4095 is the maximum length of a shell line
    FILE * p = popen(command.c_str(),"r"); 
    if( p == nullptr)
    {
        cerr << "Error executing "<< command << endl;
    }
    while(fgets(lineBuffer,sizeof(lineBuffer),p)){
        result += lineBuffer;
        //removing newline character
        if (!result.empty() && result[result.length()-1] == '\n') {
            result.erase(result.length()-1);
        }
    }
    pclose(p);
    return result;
}
