1 /*
2  * Copyright (C) 2015 Alexandros Frantzis
3  * Author: Alexandros Frantzis <alexandros.frantzis@canonical.com>
4  *
5  * This program is free software: you can redistribute it and/or modify it under
6  * the terms of the GNU General Public License as published by the Free Software
7  * Foundation, either version 3 of the License, or (at your option) any later
8  * version. See http://www.gnu.org/copyleft/gpl.html the full text of the
9  * license.
10  */
11 
12 #include <errno.h>
13 #include <fcntl.h>
14 #include <stdio.h>
15 
16 #include "log-file.h"
17 
18 int
log_file_open(const gchar * log_filename,LogMode log_mode)19 log_file_open (const gchar *log_filename, LogMode log_mode)
20 {
21     int open_flags = O_WRONLY | O_CREAT;
22     if (log_mode == LOG_MODE_BACKUP_AND_TRUNCATE)
23     {
24         /* Move old file out of the way */
25         g_autofree gchar *old_filename = NULL;
26 
27         old_filename = g_strdup_printf ("%s.old", log_filename);
28         rename (log_filename, old_filename);
29 
30         open_flags |= O_TRUNC;
31     }
32     else if (log_mode == LOG_MODE_APPEND)
33     {
34         /* Keep appending to it */
35         open_flags |= O_APPEND;
36     }
37     else
38     {
39         g_warning ("Failed to open log file %s: invalid log mode %d specified",
40                    log_filename, log_mode);
41         return -1;
42     }
43 
44     /* Open file and log to it */
45     int log_fd = open (log_filename, open_flags, 0600);
46     if (log_fd < 0)
47         g_warning ("Failed to open log file %s: %s", log_filename, g_strerror (errno));
48 
49     return log_fd;
50 }
51