// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

// generated by github.com/apache/opendal-go-services

package oss

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"sync"

	"github.com/klauspost/compress/zstd"
)

var Scheme = scheme{once: &sync.Once{}}

type scheme struct {
	once *sync.Once
}

func (scheme) Name() string {
	return "oss"
}

func (s scheme) Path() string {
	return path
}

func (s scheme) LoadOnce() error {
	var err error
	s.once.Do(func() {
		err = load()
		if err != nil {
			err = fmt.Errorf("opendal/services/oss: %s", err)
		}
	})
	return err
}

var path string

func load() error {
	data, err := decompressLib(libopendalZst)
	if err != nil {
		return err
	}
	path, err = writeTempExec("libopendal_c*.so", data)
	if err != nil {
		return err
	}
	return nil
}

func writeTempExec(pattern string, binary []byte) (path string, err error) {
	f, err := os.CreateTemp("", pattern)
	if err != nil {
		err = fmt.Errorf("cannot create temp file: %s", err)
		return
	}
	defer f.Close()
	_, err = f.Write(binary)
	if err != nil {
		err = fmt.Errorf("cannot write binary: %s", err)
		return
	}
	err = f.Chmod(os.ModePerm)
	if err != nil {
		err = fmt.Errorf("cannot chmod: %s", err)
		return
	}
	path = f.Name()
	return
}

func decompressLib(raw []byte) (data []byte, err error) {
	decoder, err := zstd.NewReader(bytes.NewReader(raw))
	if err != nil {
		err = fmt.Errorf("cannot create zstd reader: %s", err)
		return
	}
	defer decoder.Close()
	data, err = io.ReadAll(decoder)
	if err != nil {
		err = fmt.Errorf("cannot reading decompressed data: %s", err)
	}
	return
}
