#include <libgen.h>
#include "actions.h"
#include "dblayer.h"
#include "queries.h"
#include "ckerrlog.h"
int edit_get_prime_config_from_program(DB *db, char *pName, char *ret, int *secret) {
int pid = get_program_id(db, pName);
/* error */
if (pid == -2) {
return -1;
}
/* program exists */
if (pid > -1) {
char path[STR_M] = "";
if (program_has_primary_config(db, pid, path, secret) == 1) {
if (!str_is_empty(path)) {
if (ret) {
str_make_ck_config_name(ret, path, pName);
}
return 0;
}
}
}
/* No prime config found */
return -1;
}
int edit_get_config(DB *db, const char *pName, char *ret, const char *cName, int *sec) {
int pid = get_program_id(db, pName);
/* error */
if (pid == -2) {
return -1;
}
/* program exists */
if (pid > -1) {
sqlite3_stmt *stmt;
int rc;
char selection[STR_M] = COL_CONFIG_PATH;
strcat(selection, ", ");
strcat(selection, COL_CONFIG_SECRET);
char condition[STR_M] = TBL_PROGRAM;
strcat(condition, ".");
strcat(condition, COL_PROGRAM_ID);
char sql[STR_L] = "";
dbh_form_query_select_from_joined_eq(sql, selection, condition);
rc = sqlite3_prepare_v2(db->ptr, sql, -1, &stmt, 0);
sqlite3_bind_int(stmt, 1, pid);
if (rc != SQLITE_OK) {
return -2;
}
int flag = -1;
while (sqlite3_step(stmt) == SQLITE_ROW) {
char confName[STR_M] = "";
if (cName) {
char *tmp = strdup((char *)sqlite3_column_text(stmt, 0));
if (strcmp(cName, basename(tmp)) == 0) {
flag = 0;
str_make_ck_config_name(confName, (char *)sqlite3_column_text(stmt, 0), pName);
strcpy(ret, confName);
if (sec) {
*sec = sqlite3_column_int(stmt, 1);
}
}
free(tmp);
break;
}
else {
/* Since we are here, it means there is only 1 config for the selected program */
flag = 0;
str_make_ck_config_name(confName, (char *)sqlite3_column_text(stmt, 0), pName);
strcpy(ret, confName);
if (sec) {
*sec = sqlite3_column_int(stmt, 1);
}
break;
}
}
sqlite3_finalize(stmt);
return flag;
}
return -1;
}