package common

/*
 * This file is part of Autogits.
 *
 * Copyright © 2024 SUSE LLC
 *
 * Autogits is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 2 of the License, or (at your option) any later
 * version.
 *
 * Autogits 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * Foobar. If not, see <https://www.gnu.org/licenses/>.
 */

import (
	"errors"
	"fmt"
	"os"
)

const (
	RabbitUserEnv     = "AMQP_USERNAME"
	RabbitPasswordEnv = "AMQP_PASSWORD"
)

var giteaToken string
var obsUser, obsPassword, obsSshkey, obsSshkeyFile string
var rabbitUser, rabbitPassword string

func RequireGiteaSecretToken() error {
	giteaToken = os.Getenv(GiteaTokenEnv)
	if len(giteaToken) < 10 {
		return errors.New(GiteaTokenEnv + " not provided")
	}

	err := os.Setenv(GiteaTokenEnv, "")
	if err != nil {
		return fmt.Errorf("%s: %v", "Cannot reset "+GiteaTokenEnv, err)
	}

	return nil
}

func GetGiteaToken() string {
	return giteaToken
}

func RequireObsSecretToken() error {
	obsUser = os.Getenv(ObsUserEnv)
	obsPassword = os.Getenv(ObsPasswordEnv)
	obsSshkey = os.Getenv(ObsSshkeyEnv)
	obsSshkeyFile = os.Getenv(ObsSshkeyFileEnv)

	if len(obsUser) < 2 {
		return fmt.Errorf("Missing OBS authentication user")
	}
	if len(obsPassword) < 10 && len(obsSshkeyFile) < 2 {
		return fmt.Errorf("Missing OBS authentication, either password or sshkey file need to be set")
	}

	err := os.Setenv(ObsUserEnv, "")
	if err != nil {
		return fmt.Errorf("Cannot reset %s: %v", ObsUserEnv, err)
	}

	err = os.Setenv(ObsPasswordEnv, "")
	if err != nil {
		return fmt.Errorf("Cannot reset %s: %v", ObsPasswordEnv, err)
	}

	return nil
}

func RequireRabbitSecrets() error {
	rabbitUser = os.Getenv(RabbitUserEnv)
	rabbitPassword = os.Getenv(RabbitPasswordEnv)

	if len(rabbitUser) == 0 || len(rabbitPassword) == 0 {
		return fmt.Errorf("Missing RabbitMQ env variables: %s, %s", RabbitUserEnv, RabbitPasswordEnv)
	}
	return nil
}
