86 lines
1.9 KiB
Go
86 lines
1.9 KiB
Go
package oplcli
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"log/slog"
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
)
|
|
|
|
type FileMode int
|
|
|
|
const (
|
|
ModeOverride FileMode = iota
|
|
ModeAppend
|
|
ModeOnlyCreate
|
|
)
|
|
|
|
func downloadCfgForGame(gameID string, output string, mode FileMode) error {
|
|
url := getDownloadURLFromGithub(gameID)
|
|
|
|
filePath := path.Join(output, fmt.Sprintf("%s.cfg", gameID))
|
|
|
|
file, err := openFileBasedOnMode(filePath, mode)
|
|
if err != nil {
|
|
slog.Error("Failed to open cfg file", "file", filePath, "gameID", gameID, "err", err)
|
|
return err
|
|
}
|
|
defer file.Close()
|
|
|
|
resp, err := http.Get(url)
|
|
if err != nil {
|
|
slog.Error("Failed to download cfg file", "file", filePath, "gameID", gameID, "err", err)
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
_, err = io.Copy(file, resp.Body)
|
|
if err != nil {
|
|
slog.Error("Failed to write cfg file", "file", filePath, "gameID", gameID, "err", err)
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func openFileBasedOnMode(filePath string, mode FileMode) (*os.File, error) {
|
|
_, err := os.Stat(filePath)
|
|
if err != nil {
|
|
if err != os.ErrNotExist {
|
|
file, err := os.Create(filePath)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return file, nil
|
|
}
|
|
}
|
|
|
|
if mode == ModeOverride {
|
|
file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return file, nil
|
|
}
|
|
|
|
if mode == ModeAppend {
|
|
file, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return file, nil
|
|
}
|
|
|
|
return nil, fmt.Errorf("File already exists")
|
|
|
|
}
|
|
|
|
func getDownloadURLFromGithub(gameID string) string {
|
|
// const baseURL = "https://raw.githubusercontent.com/VTSTech/PS2-OPL-CFG/refs/heads/master/CFG/" // This one is more basic
|
|
const baseURL = "https://raw.githubusercontent.com/Tom-Bruise/PS2-OPL-CFG-Database/refs/heads/master/CFG_en/" // This one contains descriptions and more
|
|
|
|
return fmt.Sprintf("%s/%s.cfg", baseURL, gameID)
|
|
}
|