~whynothugo/sb-backup

sb-backup/main.go -rw-r--r-- 1.1 KiB
01f9297c — Hugo Osvaldo Barrera Include a licence for this project 7 months ago
                                                                                
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
package main

import (
	"fmt"
	"io"
	"os"
	"path"
	"strings"

	"github.com/foxboron/go-uefi/efi"
	"github.com/foxboron/sbctl"
)

func CopyFile(sourcePath string, destPath string) error {
	srcFile, err := os.Open(sourcePath)
	if err != nil {
		return err
	}
	defer srcFile.Close()

	destFile, err := os.Create(destPath)
	if err != nil {
		return err
	}
	defer destFile.Close()

	_, err = io.Copy(destFile, srcFile)
	if err != nil {
		return err
	}

	err = destFile.Sync()
	if err != nil {
		return err
	}

	return nil
}

func GenerateBackupFilename(original string) string {
	extension := path.Ext(original)
	name := strings.TrimSuffix(original, path.Ext(original))

	return fmt.Sprintf("%s_backup%s", name, extension)
}

func main() {
	name, err := efi.GetCurrentlyBootedEntry()

	if err != nil {
		fmt.Printf("Error reading currently booted entry: %v.\n", err)
		os.Exit(1)
	}

	current := fmt.Sprintf("%s/EFI/Linux/%s", sbctl.GetESP(), name)
	backup := GenerateBackupFilename(current)

	fmt.Printf("Backing up: %s -> %s.\n", current, backup)

	err = CopyFile(current, backup)
	if err != nil {
		fmt.Printf("Error creating backup file: %v.\n", err)
		os.Exit(2)
	}
}