diff --git a/cmd/dwelling-upload-clear/main.go b/cmd/dwelling-upload-clear/main.go index 0943d8e..7d094f2 100644 --- a/cmd/dwelling-upload-clear/main.go +++ b/cmd/dwelling-upload-clear/main.go @@ -2,16 +2,21 @@ package main import ( "dwelling-upload/internal/configuration" + "dwelling-upload/pkg/logging" "dwelling-upload/pkg/utils" "flag" "io/ioutil" "log" "os" + "os/user" "path" + "strconv" + "syscall" "time" ) var configPath *string = flag.String("conf", "config.yaml", "path to configuration file") +var logToStdout *bool = flag.Bool("log-stdout", false, "write logs to stdout") func main() { flag.Parse() @@ -20,11 +25,43 @@ func main() { if err != nil { log.Fatalln(err) } - _ = config + + // Substitute user to the one in config + dwu, err := user.Lookup(config.User) + if err != nil { + log.Fatalln(err) + } + + dwuid, err := strconv.Atoi(dwu.Uid) + if err != nil { + log.Fatalln(err) + } + + if os.Getuid() != dwuid { + if err := syscall.Setuid(dwuid); err != nil { + log.Fatalln(err) + } + } + + if *logToStdout { + config.Log.ToStdout = true + } + + logErr, err := logging.NewLogger(config.Log.CleanError, config.Log.ToStdout) + if err != nil { + log.Fatalln("failed to open error logger:", err) + } + defer logErr.Close() + + logClean, err := logging.NewLogger(config.Log.Clean, config.Log.ToStdout) + if err != nil { + log.Fatalln("failed to open error logger:", err) + } + defer logClean.Close() uploadsDir, err := ioutil.ReadDir(config.Uploads.Directory) if err != nil { - log.Fatalf("failed to open directory %s: %s\n", config.Uploads.Directory, err) + logErr.Fatalf("failed to open directory %s: %s\n", config.Uploads.Directory, err) } var deletedCount int64 = 0 @@ -33,7 +70,7 @@ func main() { for _, entry := range uploadsDir { if time.Duration(entry.ModTime().UTC().Sub(time.Now().UTC()).Hours()) >= time.Duration(config.Uploads.Limits.KeepForHours)*time.Hour { if err := os.Remove(path.Join(config.Uploads.Directory, entry.Name())); err != nil { - log.Fatalln("failed to remove file ", entry.Name(), ": ", err) + logErr.Fatalln("failed to remove file ", entry.Name(), ": ", err) } deletedSize += entry.Size() deletedCount++ @@ -42,5 +79,5 @@ func main() { _, _, cFSz := utils.ConvertFileSize(deletedSize) - log.Println(deletedCount, "file(s) in total of", cFSz, "was removed during this run.") + logClean.Println(deletedCount, "file(s) in total of", cFSz, "was removed during this run.") }