From 4721baa00b8422be7b91f5d5c9a1255869bf18a5 Mon Sep 17 00:00:00 2001
From: Sebastian Frank <sebastian@webmakers.de>
Date: Wed, 22 Dec 2021 10:50:15 +0100
Subject: [PATCH] copy action with chmod

---
 main.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 47 insertions(+), 2 deletions(-)

diff --git a/main.go b/main.go
index 130977e..94fbc15 100644
--- a/main.go
+++ b/main.go
@@ -3,6 +3,7 @@ package main
 import (
 	"bytes"
 	"fmt"
+	"io"
 	"io/ioutil"
 	"log"
 	"net/http"
@@ -31,8 +32,9 @@ type ActionConfig struct {
 	Content *string
 	Header  map[string]string
 
-	// move
-	To *string
+	// move, copy
+	To       *string
+	FileMode *os.FileMode
 
 	// mdir
 	Path *string
@@ -244,6 +246,8 @@ func runAction(action *ActionConfig, eventInfo notify.EventInfo, ctx actionCtx)
 		err = actionHttp(action, eventInfo, ctx)
 	case "move":
 		err = actionMove(action, eventInfo, ctx)
+	case "copy":
+		err = actionCopy(action, eventInfo, ctx)
 	case "mkdir":
 		err = actionMkDir(action, eventInfo, ctx)
 	case "delete":
@@ -379,6 +383,47 @@ func actionMove(action *ActionConfig, eventInfo notify.EventInfo, ctx actionCtx)
 	}
 
 	err = os.Rename(eventInfo.Path(), to)
+	if err != nil {
+		return err
+	}
+
+	if action.FileMode != nil {
+		err = os.Chmod(to, *action.FileMode)
+	}
+	return err
+}
+
+func actionCopy(action *ActionConfig, eventInfo notify.EventInfo, ctx actionCtx) error {
+	if action.To == nil {
+		return fmt.Errorf("missing to: as destination for copy action")
+	}
+
+	to, err := tpl2String(*action.To, action, eventInfo, ctx)
+	if err != nil {
+		return err
+	}
+
+	in, err := os.Open(eventInfo.Path())
+	if err != nil {
+		return err
+	}
+	defer in.Close()
+
+	out, err := os.Create(to)
+	if err != nil {
+		return err
+	}
+	defer out.Close()
+
+	_, err = io.Copy(out, in)
+	if err != nil {
+		return err
+	}
+
+	if action.FileMode != nil {
+		err = os.Chmod(to, *action.FileMode)
+	}
+
 	return err
 }