aboutsummaryrefslogblamecommitdiffstats
path: root/src/init.c
blob: 5f47b33a073b4fb5456ba5cc40bef4b8b6d60b4a (plain) (tree)
1
2
3
4
5
6
7
8
9
10









                                                                                
                    



                     
                                                  










































                                                                                    
                                      









                                               























                                                         
/* init.c - the init action --------------------------------------------*- C -*-
 *
 * This file is part of ck, the config keeper
 *
 * -----------------------------------------------------------------------------
 *
 * Copyright (C) 2018  Anastasis Grammenos
 * GPLv3 (see LICENCE for the full notice)
 *
 * -------------------------------------------------------------------------- */
#include "dblayer.h"
#include "ckerrlog.h"

ERRLOG(init);

static int init_create_config_file(UserOpt *opt) {
  char absVCdir[STR_L] = "";
  if (!util_file_exists(list_get_at(opt->args, 0), absVCdir)) {
    ERR("Version control directory: %s does not exist.", list_get_at(opt->args, 0));
    return 1;
  }

  char absSRdir[STR_L] = "";
  if (!util_file_exists(list_get_at(opt->args, 1), absSRdir)) {
    ERR("Secret directory: %s does not exist.", list_get_at(opt->args, 1));
    return 1;
  }

  if (!util_file_exists(opt->confDir, NULL)) {
    util_mkdir(opt->confDir);
  }

  char confName[STR_L] = "";
  make_config_name(confName, opt->confDir);
  FILE *f;
  if ((f = fopen(confName, "w")) == NULL) {
    return 1;
  }

  char tmp[STR_L] = "";
  strcpy(tmp, "version_control_dir = ");
  strcat(tmp, absVCdir);
  strcat(tmp, "\n");
  fputs(tmp, f);

  strcpy(tmp, "secret_dir = ");
  strcat(tmp, absSRdir);
  strcat(tmp, "\n");
  fputs(tmp, f);

  strcpy(tmp, "home_dir = ");
  strcat(tmp, getenv("HOME"));
  strcat(tmp, "\n");
  fputs(tmp, f);

  fclose(f);
  return 0;
}

static void init_make_tables(DB *db) {
  char sql[STR_L] = "";
  dbh_form_query_make_tables(sql);

  int rc = sqlite3_exec(db->ptr, sql, 0, 0, 0);
  if (rc != SQLITE_OK ) {
    PRINT_ERR("Could not create empty db.");
    db->error = SQL_ERR_SQLITE;
    return;
  }
}

int run_INIT(UserOpt * opt, Conf *conf) {
  UNUSED(conf);
  if (db_exists(opt)) {
    ERR("ck is already initialized in %s", opt->confDir);
    return -1;
  }
  if (init_create_config_file(opt)) {
    sERR("Cound not create config file.");
    return -1;
  }
  DB db;
  if (open_DB(&db, opt)) {
    return -1;
  }
  init_make_tables(&db);
  sqlite3_close(db.ptr);
  hLOG("Initialized empty ckdb.");
  return 0;
}

void print_INIT_help() {
  HELP("ck init VERSION_CONTROL_DIR SECRET_DIR");
}