aboutsummaryrefslogtreecommitdiff
path: root/app_build/webpull/main.go
blob: 46c90b95efec08af165ba67b556387f640af5c67 (plain) (blame)
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main

import (
	"fmt"
	"errors"
	"io"
	"os/exec"
	"os"
	"log"
	"net/http"
	"strings"
)

func myexec(w io.Writer, main string, params ...string) error {
	cmd := exec.Command(main, params...)
	cmd.Stdout = w
	cmd.Stderr = w
	err := cmd.Run()
	if err != nil {
		fmt.Fprintf(w, "Failed to run: %s %s\n", main, strings.Join(params, " "))
	}
	return err
}

func update(w io.Writer) error {
	fmt.Fprintf(w, "Start update...\n")
	_, err := os.Stat("./.git")
	if err != nil {
		fmt.Fprintf(w, ".git folder does not exist, creating it...\n")
		err := myexec(w, "git", "init")
		if err != nil {
			return err
		}
	}

	err = myexec(w, "git", "remote", "get-url", "origin")
	if err != nil {
		repo, exists := os.LookupEnv("WEBPULL_REPO")
		if !exists {
			fmt.Fprintf(w, "You must define WEBPULL_REPO env variable...\n")
			return errors.New("Missing environment variable WEBPULL_REPO")
		}
		fmt.Fprintf(w, "git remote is not yet set...\n")
		err := myexec(w, "git", "remote", "add", "origin", repo)
		if err != nil {
			return err
		}
	}

	err = myexec(w, "git", "pull", "origin", "master")
	if err != nil {
		fmt.Fprintf(w, "Failed to pull...\n")
		return err
	}

	_, err = os.Stat("./.webpull")
	if err != nil {
		fmt.Fprintf(w, "You must create an executable file named '.webpull' at the root of your repository.\nIf you have nothing to run, just create an empty bash script...\n")
		return err
	}

	err = myexec(w, "./.webpull")
	if err != nil {
		fmt.Fprintf(w, "An error occured during script execution\n")
		return err
	}

	fmt.Fprintf(w, "Success.\n")
	return nil
}

func main() {
	token, exists := os.LookupEnv("WEBPULL_TOKEN")
	if !exists {
		log.Fatal("Environment variable 'WEBPULL_TOKEN' must be defined")
	}

	if update(os.Stdout) != nil {
		log.Fatal("Initial 'update' failed")
	}

	fs := http.FileServer(http.Dir("./static"))
	http.HandleFunc("/update", func(w http.ResponseWriter, r *http.Request) {
		keys, ok := r.URL.Query()["token"]
		if !ok || len(keys[0]) < 1 {
			http.Error(w, "Missing 'token' query parameter", 401)
			return
		}

		if keys[0] != token {
			http.Error(w, "Wrong token", 401)
			return
		}

		update(w)
	})
	http.Handle("/", fs)

	log.Fatal(http.ListenAndServe(":8080", nil))
}