aboutsummaryrefslogtreecommitdiff
path: root/cmd/web/main.go
blob: 6db58d97d094d3bceb9a79cac1e232af9cc89625 (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
package main

import (
	"embed"
	"flag"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"strconv"
	"strings"

	"github.com/gorilla/mux"
)

var (
	// Version is overridden by the build script
	Version = "Development"
	// Logger default logging to stderr
	Logger = log.New(os.Stderr, "", log.LstdFlags)
	// Listen address for the webserver
	Listen = ":8899"

	//go:embed static/*
	embeddedStatic embed.FS
	//go:embed templates/index.html
	indexTemplate string
)

func main() {
	fl := flag.NewFlagSet("steam-export", flag.ExitOnError)
	debug := fl.Bool("d", false, "Print line numbers in log")
	fl.StringVar(&Listen, "l", Listen, "What address do we listen on?")
	fl.StringVar(&DefaultLib, "L", DefaultLib, "Full path to default library")
	fl.StringVar(&isLocalCIDR, "t", isLocalCIDR,
		"Trusted CIDRs for additional controls, seperated by commas")
	fl.StringVar(&shareLink, "s", shareLink, "Share link, if blank make an educated guess")
	isDemo := fl.Bool("demo", false,
		"Whether or not to run in demo mode. You probably don't want this on.")
	fl.Parse(os.Args[1:])

	if *debug {
		Logger.SetFlags(log.LstdFlags | log.Llongfile)
	}

	a, err := NewApp(DefaultLib)
	if err != nil {
		Logger.Fatal(err)
	}

	if *isDemo {
		a.Demo = true
	}

	go a.installer()

	r := mux.NewRouter()

	r.Handle("/quit", UnauthorizedIfNotLocal(http.HandlerFunc(HandleQuit)))
	r.Handle("/setLib", UnauthorizedIfNotLocal(http.HandlerFunc(a.HandleSetLib)))
	r.Handle("/delete", UnauthorizedIfNotLocal(http.HandlerFunc(a.HandleDelete)))
	r.Handle("/install", UnauthorizedIfNotLocal(http.HandlerFunc(a.HandleInstall)))
	r.HandleFunc("/steam-export-web.exe", ServeSelf)
	r.HandleFunc("/download/{game}", a.HandleDownload)
	r.Handle("/status", UnauthorizedIfNotLocal(http.HandlerFunc(a.HandleStats)))
	r.PathPrefix("/static").Handler(
		http.FileServer(http.FS(embeddedStatic)))
	r.HandleFunc("/", a.HandleIndex)

	s := http.Server{Handler: r}

	for i := 0; i < 5; i++ {
		l, err := net.Listen("tcp", Listen)

		if err != nil {
			Logger.Printf("Encountered: %s", err)

			parts := strings.Split(Listen, ":")
			port, err := strconv.Atoi(parts[1])
			if err != nil {
				panic(err)
			}
			port++

			Listen = fmt.Sprintf("%s:%d", parts[0], port)

			Logger.Printf("Trying: %s", Listen)
			continue
		}

		startBrowser("http://localhost" + Listen)

		err = s.Serve(l)
		if err != nil {
			panic(err)
		}
	}
}