package main

import (
	"errors"
	"io/ioutil"
	"os"
	"strings"

	"github.com/godbus/dbus"
	"github.com/linuxdeepin/go-lib/dbusutil"
	"github.com/linuxdeepin/go-lib/procfs"
)

const nodeDirectory = "/proc/uos/"
const sysNodeDirectory = "/sys/devices/platform/smartcc/leds/"

func (d *Daemon) getSenderCommand(sender dbus.Sender) string {
	pid, err := d.service.GetConnPID(string(sender))
	if err != nil {
		logger.Warning(err)
		return ""
	}
	proc := procfs.Process(pid)
	exe, err := proc.TrustedExe()
	if err != nil {
		logger.Warning(err)
		return ""
	}
	return exe
}

func (d *Daemon) SetLEDEnabled(sender dbus.Sender, node string, enabled bool) *dbus.Error {
	command := d.getSenderCommand(sender)
	logger.Debugf("[SetLEDEnabled] command: %s node: %s enabled: %v", command, node, enabled)
	if !strings.HasPrefix(command, "/usr/lib/deepin-daemon/dde-session-daemon") {
		return dbusutil.ToError(errors.New("invalid sender"))
	}

	if !strings.HasPrefix(node, nodeDirectory) && !strings.HasPrefix(node, sysNodeDirectory) {
		return dbusutil.ToError(errors.New("invalid node"))
	}

	arg := "0"
	if enabled {
		arg = "1"
	}
	err := ioutil.WriteFile(node, []byte(arg), 0644)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		logger.Warning(err)
		dbusutil.ToError(err)
	}

	return nil
}
