// Mgmt
// Copyright (C) James Shubin and the project contributors
// Written by James Shubin <james@shubin.ca> and the project contributors
//
// This program 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 3 of the License, or
// (at your option) any later version.
//
// This program 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 this program.  If not, see <https://www.gnu.org/licenses/>.
//
// Additional permission under GNU GPL version 3 section 7
//
// If you modify this program, or any covered work, by linking or combining it
// with embedded mcl code and modules (and that the embedded mcl code and
// modules which link with this program, contain a copy of their source code in
// the authoritative form) containing parts covered by the terms of any other
// license, the licensors of this program grant you additional permission to
// convey the resulting work. Furthermore, the licensors of this program grant
// the original author, James Shubin, additional permission to update this
// additional permission if he deems it necessary to achieve the goals of this
// additional permission.

package resources

import (
	"context"
	"fmt"

	"github.com/purpleidea/mgmt/engine"
	"github.com/purpleidea/mgmt/engine/traits"
)

func init() {
	// TODO: should this be mgmt:exit ?
	engine.RegisterResource("exit", func() engine.Res { return &ExitRes{} })
}

// ExitRes is a resource that tells mgmt to exit. If you're running as a service
// which automatically restarts on exit, you might cause a loop. Use this only
// if you really know what you're doing.
type ExitRes struct {
	traits.Base // add the base methods without re-implementation

	init *engine.Init

	// Code specifies the exit (status) code to return. For portability, the
	// status code should be in the range [0, 125].
	Code uint8 `lang:"code" yaml:"code"`

	// TODO: add an interrupt flag to exit with interrupt = true ?
}

// Default returns some sensible defaults for this resource.
func (obj *ExitRes) Default() engine.Res {
	return &ExitRes{}
}

// Validate if the params passed in are valid data.
func (obj *ExitRes) Validate() error {
	if obj.Code > 125 {
		return fmt.Errorf("the Code must be in the range [0, 125]")
	}

	return nil
}

// Init runs some startup code for this resource.
func (obj *ExitRes) Init(init *engine.Init) error {
	obj.init = init // save for later

	return nil
}

// Cleanup is run by the engine to clean up after the resource is done.
func (obj *ExitRes) Cleanup() error {
	return nil
}

// Watch is the primary listener for this resource and it outputs events.
func (obj *ExitRes) Watch(ctx context.Context) error {
	if err := obj.init.Event(ctx); err != nil {
		return err
	}

	select {
	case <-ctx.Done(): // closed by the engine to signal shutdown
	}

	return ctx.Err()
}

// CheckApply method for Exit resource. Causes an exit!
func (obj *ExitRes) CheckApply(ctx context.Context, apply bool) (bool, error) {
	if !apply {
		return false, nil
	}

	obj.init.Logf("about to exit with code: %d", obj.Code)
	if err := obj.init.Local.Exit(int(obj.Code)); err != nil {
		return false, err
	}

	return false, nil // state is always okay
}

// Cmp compares two resources and returns an error if they are not equivalent.
func (obj *ExitRes) Cmp(r engine.Res) error {
	// we can only compare ExitRes to others of the same resource kind
	res, ok := r.(*ExitRes)
	if !ok {
		return fmt.Errorf("not a %s", obj.Kind())
	}

	if obj.Code != res.Code {
		return fmt.Errorf("the Code differs")
	}

	return nil
}

// UnmarshalYAML is the custom unmarshal handler for this struct. It is
// primarily useful for setting the defaults.
func (obj *ExitRes) UnmarshalYAML(unmarshal func(interface{}) error) error {
	type rawRes ExitRes // indirection to avoid infinite recursion

	def := obj.Default()      // get the default
	res, ok := def.(*ExitRes) // put in the right format
	if !ok {
		return fmt.Errorf("could not convert to ExitRes")
	}
	raw := rawRes(*res) // convert; the defaults go here

	if err := unmarshal(&raw); err != nil {
		return err
	}

	*obj = ExitRes(raw) // restore from indirection with type conversion!
	return nil
}
