templatefile/pkg/templater/repo-apk.go

100 lines
1.7 KiB
Go
Raw Normal View History

2022-06-27 15:58:37 +02:00
package templater
import (
2022-06-29 16:18:28 +02:00
"bufio"
2022-06-27 15:58:37 +02:00
"fmt"
"io/ioutil"
"os"
"strings"
"forge.cadoles.com/pcaseiro/templatefile/pkg/utils"
)
2022-06-29 16:18:28 +02:00
var APKConfigFile = "/etc/apk/repositories"
2022-06-27 15:58:37 +02:00
type APKRepository struct {
2022-06-29 16:18:28 +02:00
Repository
}
func (hr *APKRepository) urlIsPresent() (bool, error) {
f, err := os.Open(APKConfigFile)
if err != nil {
return false, err
}
defer f.Close()
// Splits on newlines by default.
scanner := bufio.NewScanner(f)
line := 1
for scanner.Scan() {
2022-06-29 16:26:06 +02:00
fmt.Printf("DBG:%s:%s:\n", scanner.Text(), hr.URL)
2022-06-29 16:18:28 +02:00
if strings.Contains(scanner.Text(), hr.URL) {
return true, nil
}
line++
}
2022-06-29 16:27:21 +02:00
fmt.Printf("END\n")
2022-06-29 16:18:28 +02:00
if err := scanner.Err(); err != nil {
return false, err
}
return false, nil
2022-06-27 15:58:37 +02:00
}
func (hr *APKRepository) Add() error {
2022-06-29 16:18:28 +02:00
URLIsPresent, err := hr.urlIsPresent()
2022-06-27 15:58:37 +02:00
if err != nil {
return err
}
2022-06-29 16:18:28 +02:00
if URLIsPresent {
2022-06-29 16:24:31 +02:00
fmt.Printf("DEBUG %v\n", URLIsPresent)
2022-06-29 16:18:28 +02:00
return nil
} else {
2022-06-29 16:24:31 +02:00
data := fmt.Sprintf("%s\n", hr.URL)
2022-06-29 16:21:56 +02:00
fmt.Printf("DEBUG %v", data)
2022-06-29 16:24:04 +02:00
file, err := os.OpenFile(APKConfigFile, os.O_APPEND|os.O_WRONLY, 0644)
2022-06-29 16:18:28 +02:00
if err != nil {
return err
}
defer file.Close()
if _, err := file.WriteString(data); err != nil {
return err
}
return nil
2022-06-27 15:58:37 +02:00
}
2022-06-29 16:18:28 +02:00
2022-06-27 15:58:37 +02:00
}
func (hr *APKRepository) Update() error {
if _, stdErr, err := utils.RunSystemCommand("apk", "update"); err != nil {
return fmt.Errorf("%s [%s]", stdErr, err)
}
return nil
}
func (hr *APKRepository) Delete() error {
fileBytes, err := ioutil.ReadFile("/etc/apk/repositories")
if err != nil {
return err
}
lines := strings.Split(string(fileBytes), "\n")
2022-06-29 12:13:32 +02:00
for _, line := range lines {
fmt.Println(line)
2022-06-27 15:58:37 +02:00
}
return nil
}
2022-06-29 16:18:28 +02:00
2022-06-27 15:58:37 +02:00
func (hr *APKRepository) Manage() error {
if hr.Enabled {
return hr.Add()
} else {
return hr.Delete()
}
}