package storage

import (
	"github.com/cockroachdb/pebble"
	"log"
)

var db *pebble.DB

func init() {
	newDB, err := pebble.Open("vpn.db", &pebble.Options{})
	if err != nil {
		log.Fatalf("err: %+v", err)
	}
	db = newDB
}

func get(key string) ([]byte, error) {
	value, closer, err := db.Get([]byte(key))
	if err != nil {
		return nil, err
	}
	if err == pebble.ErrNotFound {
		return []byte{}, nil
	}
	newValue := make([]byte, len(value))
	copy(newValue, value)
	if err := closer.Close(); err != nil {
		return nil, err
	}
	return newValue, nil
}

func set(key string, value []byte) error {
	return db.Set([]byte(key), value, pebble.Sync)
}
