1/*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16package utils
17
18import (
19	"fmt"
20	"github.com/patrickmn/go-cache"
21	"os"
22	"path/filepath"
23	"time"
24)
25
26var runtimeDir = `.fotff`
27
28var runtimeCache = cache.New(24*time.Hour, time.Hour)
29
30func sectionKey(section, key string) string {
31	return fmt.Sprintf("__%s__%s__", section, key)
32}
33
34func init() {
35	if err := os.MkdirAll(runtimeDir, 0750); err != nil {
36		panic(err)
37	}
38	runtimeCache.LoadFile(filepath.Join(runtimeDir, "fotff.cache"))
39}
40
41func CacheGet(section string, k string) (v any, found bool) {
42	return runtimeCache.Get(sectionKey(section, k))
43}
44
45func CacheSet(section string, k string, v any) error {
46	runtimeCache.Set(sectionKey(section, k), v, cache.DefaultExpiration)
47	return runtimeCache.SaveFile(filepath.Join(runtimeDir, "fotff.cache"))
48}
49
50func WriteRuntimeData(name string, data []byte) error {
51	return os.WriteFile(filepath.Join(runtimeDir, name), data, 0640)
52}
53
54func ReadRuntimeData(name string) ([]byte, error) {
55	return os.ReadFile(filepath.Join(runtimeDir, name))
56}
57