findconfig.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <libmegapixels.h>
  4. #ifndef SYSCONFDIR
  5. #define SYSCONFDIR "/etc"
  6. #endif
  7. #ifndef DATADIR
  8. #define DATADIR "/usr/share"
  9. #endif
  10. static int
  11. find_device_by_model(char *conffile, char *model, int print)
  12. {
  13. // Check config/%model.conf in the current working directory
  14. sprintf(conffile, "config/%s.conf", model);
  15. if (print) {
  16. printf("- %s\n", conffile);
  17. }
  18. if (access(conffile, F_OK) != -1) {
  19. return 1;
  20. }
  21. // Check user overridden /etc/megapixels/config/%model.conf
  22. sprintf(conffile, "%s/megapixels/config/%s.conf", SYSCONFDIR, model);
  23. if (print) {
  24. printf("- %s\n", conffile);
  25. }
  26. if (access(conffile, F_OK) != -1) {
  27. return 1;
  28. }
  29. // Check packaged /usr/share/megapixels/config/%model.conf
  30. sprintf(conffile, "%s/megapixels/config/%s.conf", DATADIR, model);
  31. if (print) {
  32. printf("- %s\n", conffile);
  33. }
  34. if (access(conffile, F_OK) != -1) {
  35. return 1;
  36. }
  37. if (print) {
  38. printf("no config for '%s'\n", model);
  39. }
  40. return 0;
  41. }
  42. int
  43. libmegapixels_find_config_verbose(char *configfile, int print)
  44. {
  45. char model[512];
  46. FILE *fp;
  47. if (access("/proc/device-tree/compatible", F_OK) == -1) {
  48. return 0;
  49. }
  50. fp = fopen("/proc/device-tree/compatible", "r");
  51. char *modelptr = model;
  52. while (1) {
  53. int c = fgetc(fp);
  54. if (c == EOF) {
  55. return 0;
  56. }
  57. *(modelptr++) = (char) c;
  58. if (c == 0) {
  59. if (find_device_by_model(configfile, model, print)) {
  60. return 1;
  61. }
  62. modelptr = model;
  63. }
  64. }
  65. }
  66. int
  67. libmegapixels_find_config(char *configfile)
  68. {
  69. return libmegapixels_find_config_verbose(configfile, 0);
  70. }