nextep: Create data directory only if necessary.
[utils.git] / nextep.c
CommitLineData
b2fa28e3
FT
1#include <stdlib.h>
2#include <stdio.h>
3#include <unistd.h>
4#include <string.h>
5#include <libgen.h>
6#include <errno.h>
7#include <sys/stat.h>
8
f2bcbba7
FT
9static int ensuredir(char *base, char *dir)
10{
11 if(access(dir, X_OK)) {
12 if((mkdir(base, 0777) && (errno != EEXIST)) || mkdir(dir, 0777))
13 return(1);
14 }
15 return(0);
16}
17
b2fa28e3
FT
18static void usage(FILE *out)
19{
20 fprintf(out, "usage: nextep [-h] [-f FILE] [-s SET-VALUE] [DIR]\n");
21}
22
23int main(int argc, char **argv)
24{
25 int c;
26 char buf[1024], dbuf[1024], *p;
27 char *file, *value, *dir;
28 char base[1024], fpath[1024];
29 FILE *fp;
30
31 file = "nextep";
32 value = NULL;
33 while((c = getopt(argc, argv, "hf:s:")) >= 0) {
34 switch(c) {
35 case 'f':
36 file = optarg;
37 break;
38 case 's':
39 value = optarg;
40 break;
41 case 'h':
42 usage(stdout);
43 exit(0);
44 default:
45 usage(stderr);
46 exit(1);
47 }
48 }
49 if(optind < argc) {
50 if(chdir(argv[optind])) {
51 fprintf(stderr, "nextep: %s: %s\n", argv[optind], strerror(errno));
52 exit(1);
53 }
54 optind++;
55 }
56 if(!getcwd(dbuf, sizeof(dbuf))) {
57 fprintf(stderr, "nextep: getcwd: %s\n", strerror(errno));
58 exit(1);
59 }
60 dir = basename(dbuf);
61 if((p = getenv("HOME")) == NULL) {
62 fprintf(stderr, "nextep: $HOME is not set\n");
63 exit(1);
64 }
65 snprintf(buf, sizeof(buf), "%s/.nextep", p);
66 snprintf(base, sizeof(base), "%s/%s", buf, dir);
b2fa28e3
FT
67 snprintf(fpath, sizeof(fpath), "%s/%s", base, file);
68 if(value == NULL) {
69 if((fp = fopen(fpath, "r")) == NULL) {
70 if(errno != ENOENT) {
71 fprintf(stderr, "nextep: %s: %s\n", fpath, strerror(errno));
72 exit(1);
73 }
74 } else {
75 while(fgets(buf, sizeof(buf), fp) != NULL)
76 printf(buf);
77 fclose(fp);
78 }
79 } else if(!*value) {
80 if(unlink(fpath) && (errno != ENOENT)) {
81 fprintf(stderr, "nextep: %s: %s\n", fpath, strerror(errno));
82 exit(1);
83 }
84 } else {
f2bcbba7
FT
85 if(ensuredir(buf, base)) {
86 fprintf(stderr, "nextep: %s: %s\n", base, strerror(errno));
87 exit(1);
88 }
b2fa28e3
FT
89 if((fp = fopen(fpath, "w")) == NULL) {
90 fprintf(stderr, "nextep: %s: %s\n", fpath, strerror(errno));
91 exit(1);
92 }
93 fprintf(fp, "%s\n", value);
94 fclose(fp);
95 }
96 return(0);
97}
98
99/*
100 * Local Variables:
101 * compile-command: "gcc -Wall -g -o nextep nextep.c"
102 * End:
103 */