env.go 1.12 KB
package main

import (
	"bytes"
	"fmt"
	"os"
	"regexp"
)

func getEnv(blockn int) (map[string]string, error) {
	m := make(map[string]string)

	f, err := os.Open("/dev/mmcblk3boot1")
	if err != nil {
		return m, err
	}
	defer f.Close()

	b := make([]byte, 512)
	f.ReadAt(b, int64(blockn)*512)

	n := bytes.IndexByte(b, 0)
	s := string(b[:n])

	r := regexp.MustCompile(`(.+?)=(.+)\n`)
	ss := r.FindAllStringSubmatch(s, -1)
	for _, v := range ss {
		if len(v) != 3 {
			continue
		}

		m[v[1]] = v[2]
	}

	return m, nil
}

func setEnv(blockn int, env map[string]string) error {
	err := disableReadOnly()
	if err != nil {
		return err
	}

	f, err := os.OpenFile("/dev/mmcblk3boot1", os.O_RDWR, 0666)
	if err != nil {
		return err
	}
	defer f.Close()

	var s string
	for k, v := range env {
		s += fmt.Sprintf("%s=%s\n", k, v)
	}
	s += "\x00"

	_, err = f.WriteAt([]byte(s), int64(blockn)*512)
	if err != nil {
		return err
	}

	return nil
}

func disableReadOnly() error {
	f, err := os.OpenFile("/sys/block/mmcblk3boot1/force_ro", os.O_RDWR, 0666)
	if err != nil {
		return err
	}
	defer f.Close()

	_, err = f.WriteString("0\n")

	return err
}