update/backup.go

121 lines
2.4 KiB
Go
Raw Normal View History

2024-09-03 03:38:43 +02:00
package main
import (
"bufio"
"errors"
"fmt"
"io/fs"
"log"
"os"
"os/exec"
"strings"
)
func parseEnvironment(key string) string {
value := os.Getenv(key)
if value == "" {
log.Panicf("%s is not set\n", key)
}
if _, err := os.Stat(value); err != nil {
if errors.Is(err, fs.ErrNotExist) {
log.Panicf("%s does not point to a valid path\n", key)
}
log.Panicf("trying to stat %s produced an unkown error\n", value)
}
return value
}
func parsePacmanConf() string {
var path string
file, err := os.Open("/etc/pacman.conf")
if err != nil {
log.Panicln(err)
}
defer func() {
if err := file.Close(); err != nil {
log.Panicln(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if !strings.Contains(line, "DBPath") {
continue
}
path = strings.TrimSpace(strings.Split(line, "=")[1])
break
}
if _, err := os.Stat(path); err != nil {
if errors.Is(err, fs.ErrNotExist) {
log.Panicln("DBPath in /etc/pacman.conf does not point to a valid path")
}
log.Panicf("trying to stat %s produced an unkown error\n", path)
}
return fmt.Sprintf("%s%s", path, "local")
}
func preBackup() {
pacmanDb := parsePacmanConf()
log.Printf("pacmanDb: %s\n", pacmanDb)
tmpPath := "/tmp/update/pre_backup"
output, err := exec.Command("pacman", "--verbose", "--query").Output()
if err != nil {
log.Panicln(err)
}
err = os.MkdirAll(tmpPath, 0755)
err = os.WriteFile(fmt.Sprintf("%s/%s", tmpPath, "pre_pacman.txt"), output, 0644)
if err != nil {
log.Panicln(err)
}
defer func() {
if r := recover(); r != nil {
err := os.RemoveAll(tmpPath)
if err != nil {
log.Fatal(err)
}
err = CopyDir(pacmanDb, fmt.Sprintf("%s/%s", tmpPath, pacmanDb))
if err != nil {
log.Panicln(err)
}
log.Println("recovered successfully")
}
}()
err = CopyDir(pacmanDb, fmt.Sprintf("%s/%s", tmpPath, pacmanDb))
if err != nil {
log.Panicln(err)
}
}
func postBackup() {
/*
* basic logic for post:
* create new pkg list and delete all lines which are the same as pre
*/
panic("unimplemented")
}
func main() {
// backup_dir := parseEnvironment("UPDATE_BACKUP_DIR")
cmdlineArg := os.Args[1]
log.Printf("cmdlineArg: %s\n", cmdlineArg)
if cmdlineArg == "pre" {
preBackup()
} else if cmdlineArg == "post" {
postBackup()
} else {
log.Panicf("invalid cmdline argument. supplied value was: %s\n", cmdlineArg)
}
}