Files
cpp-pager/arch-discordbots-service/service/main.cpp
2021-12-24 04:07:44 -06:00

129 lines
2.6 KiB
C++

#include <algorithm>
#include <cctype>
#include <fstream>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <sstream>
#include <string>
#include <sys/stat.h>
#include <unistd.h>
#include <vector>
using namespace std;
class DATA {
public:
string loc = "";
string script = "";
string name = "";
bool disabled = false;
};
static inline void trim(string &s) {
s.erase(s.begin(), find_if(s.begin(), s.end(), [](unsigned char ch) {
return !isspace(ch);
}));
s.erase(find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
return !isspace(ch);
}).base(), s.end());
}
string exec(const char* cmd) {
array<char, 128> buffer;
string result;
unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if (!pipe) {
throw runtime_error("popen() failed!");
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
trim(result);
return result;
}
const int DATALEN = 2;
void splitData(string str, DATA &data) {
stringstream ssin(str);
while (ssin.good()) {
if (data.loc.length() == 0) {
ssin >> data.loc;
continue;
}
if (data.script.length() > 0)
data.loc += " " + data.script;
ssin >> data.script;
}
if (data.loc[0] == '~')
data.loc = getenv("HOME") + data.loc.substr(1);
string cmd = "cd \"" + data.loc + "\" && cut -d \"=\" -f 2 <<< $(npm run env | grep npm_package_name)";
data.name = exec(cmd.c_str());
}
void loadfile(vector<DATA> &scripts) {
ifstream infile("scripts");
string line;
int linenum = 0;
while (getline(infile, line)) {
linenum++;
istringstream iss(line);
string str = iss.str();
if (str.length() == 0)
continue;
DATA data;
if (str[0] == '#') {
data.disabled = true;
str = str.substr(1);
}
splitData(str, data);
if (data.loc.length() == 0 || data.script.length() == 0 || data.name.length() == 0) {
cout << "WARNING: skipping line " << linenum << endl;
continue;
}
scripts.push_back(data);
}
}
int main() {
vector<DATA> scripts;
loadfile(scripts);
for (int i = 0; i < scripts.size(); i++) {
DATA data = scripts.at(i);
}
struct stat sb;
time_t mtime = 0;
while (true) {
stat("scripts", &sb);
if (sb.st_mtime > mtime) {
mtime = sb.st_mtime;
cout << "modified" << endl;
}
sleep(1);
}
return 0;
}