-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove.c
More file actions
74 lines (60 loc) · 1.89 KB
/
Copy pathremove.c
File metadata and controls
74 lines (60 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include "upac.h"
int upac_remove(const char *pkg_name) {
if (geteuid() != 0) {
fprintf(stderr, "[upac] Must be run as root to remove packages\n");
return -1;
}
upac_db_init();
InstalledPackage pkg;
if (upac_db_find(pkg_name, &pkg) != 0) {
fprintf(stderr, "[upac] Package '%s' is not installed\n", pkg_name);
return -1;
}
printf("[upac] Removing %s-%s-r%d\n", pkg.name, pkg.version, pkg.revision);
char files_list_path[1024];
snprintf(files_list_path, sizeof(files_list_path), UPAC_FILES_DIR "/%s", pkg_name);
FILE *fp = fopen(files_list_path, "r");
if (!fp) {
fprintf(stderr, "[upac] No file list found for %s\n", pkg_name);
upac_db_remove(pkg_name);
printf("[upac] Removed %s from database\n", pkg_name);
return 0;
}
char line[1024];
int files_removed = 0;
while (fgets(line, sizeof(line), fp)) {
line[strcspn(line, "\n")] = '\0';
if (line[0] == '\0') continue;
struct stat st;
if (lstat(line, &st) == 0) {
if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
if (unlink(line) == 0) files_removed++;
}
}
}
fclose(fp);
// Remove empty directories (reverse order)
fp = fopen(files_list_path, "r");
if (fp) {
while (fgets(line, sizeof(line), fp)) {
line[strcspn(line, "\n")] = '\0';
if (line[0] == '\0') continue;
struct stat st;
if (lstat(line, &st) == 0 && S_ISDIR(st.st_mode)) {
rmdir(line);
}
}
fclose(fp);
}
unlink(files_list_path);
upac_db_remove(pkg_name);
printf("[upac] Removed %s (%d files)\n", pkg_name, files_removed);
return 0;
}