/*
 * Copyright (C) 2026 Fluxer Contributors
 *
 * This file is part of Fluxer.
 *
 * Fluxer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Fluxer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with Fluxer. If not, see <https://www.gnu.org/licenses/>.
 */

package main

import (
	"fmt"
	"os"
	"path/filepath"
	"slices"
)

var allowedChannels = []string{"stable", "canary"}

func parseChannel() string {
	raw := os.Getenv("BUILD_CHANNEL")
	if raw != "" && slices.Contains(allowedChannels, raw) {
		return raw
	}
	return "stable"
}

func main() {
	channel := parseChannel()

	cwd, _ := os.Getwd()
	targetPath := filepath.Join(cwd, "..", "src-electron", "common", "build-channel.ts")

	fileContent := fmt.Sprintf(`/*
 * This file is generated by scripts/cmd/set-build-channel.
 * DO NOT EDIT MANUALLY.
 */

export type BuildChannel = 'stable' | 'canary';

const DEFAULT_BUILD_CHANNEL = '%s' as BuildChannel;

const envChannel = process.env.BUILD_CHANNEL?.toLowerCase();
export const BUILD_CHANNEL = (envChannel === 'canary' ? 'canary' : DEFAULT_BUILD_CHANNEL) as BuildChannel;
export const IS_CANARY = BUILD_CHANNEL === 'canary';
export const CHANNEL_DISPLAY_NAME = BUILD_CHANNEL;
`, channel)

	if err := os.WriteFile(targetPath, []byte(fileContent), 0644); err != nil {
		fmt.Fprintf(os.Stderr, "Error writing file: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("Wrote %s with channel '%s'\n", targetPath, channel)
}
