#!/usr/bin/python3

# cpupower-gui.in
#
# Copyright 2019-2020 Evangelos Rigas
#
# 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 <http://www.gnu.org/licenses/>.

import argparse
import gettext
import os
import signal
import sys

VERSION = "0.9.1"
pkgdatadir = "/usr/share/cpupower-gui"
localedir = "/usr/share/locale"

sys.path.insert(1, pkgdatadir)

from cpupower_gui.config import CpuPowerConfig
from cpupower_gui.helper import (
    apply_balanced,
    apply_configuration,
    apply_cpu_profile,
    apply_energy_preference,
    apply_performance,
)
from cpupower_gui.utils import (
    cpus_available,
    is_energy_pref_avail,
    parse_core_list,
    read_available_energy_prefs,
    read_energy_pref,
)

signal.signal(signal.SIGINT, signal.SIG_DFL)
gettext.install("cpupower-gui", localedir)

CPUS = cpus_available()
ENERGY_PREF_AVAIL = is_energy_pref_avail(0)

# Add argparse options
parser = argparse.ArgumentParser(
    prog="cpupower-gui",
    description="cpupower-gui - Set the scaling frequencies and governor of a CPU",
    formatter_class=argparse.RawDescriptionHelpFormatter,
)

parser.add_argument(
    "--version", action="version", version="%(prog)s {}".format(VERSION)
)

cmd_group = parser.add_mutually_exclusive_group()

cmd_group.add_argument(
    "-l",
    "--list-profiles",
    action="store_true",
    help="List available cpupower profiles",
)

cmd_group.add_argument(
    "--apply-config",
    action="store_true",
    help="Apply cpupower configuration",
)
cmd_group.add_argument(
    "--apply-profile",
    type=str,
    metavar="PROFILE",
    help="Apply a cpupower profile",
)

parser.add_argument(
    "-b",
    "--balanced",
    action="store_true",
    help="Change governor to balanced",
)
parser.add_argument(
    "-p",
    "--performance",
    action="store_true",
    help="Change governor to performance",
)

parser.add_argument(
    "--gapplication-service",
    action="store_true",
    help="Start gui from gapplication",
)


if ENERGY_PREF_AVAIL:
    # Enable flags if hardware is compatible
    parser.add_argument(
        "--energy-performance-preference",
        type=str,
        choices=read_available_energy_prefs(0),
        help="Set a global energy profile",
    )
    cmd_group.add_argument(
        "--list-energy-preferences",
        type=str,
        nargs="?",
        metavar="LIST OF CPUS",
        const="{}-{}".format(CPUS[0], CPUS[-1]),
        help="List available energy performance preferences (Default: all cpus) ",
    )

if __name__ == "__main__":
    args = parser.parse_args()
    conf = CpuPowerConfig()

    if args.balanced:
        apply_balanced()
        sys.exit(0)

    if args.performance:
        apply_performance()
        sys.exit(0)

    if args.list_profiles:  # List profiles
        profiles = conf.profiles
        if profiles:
            print("The available profiles are:")
            for prof in profiles:
                print("\t- {}".format(prof))
            sys.exit(0)

        print("No profiles were found!")
        sys.exit(0)

    if args.apply_profile:
        prof = args.apply_profile
        if prof in conf.profiles:
            print("Applying profile: ", prof)
            apply_cpu_profile(conf.get_profile(prof))
            sys.exit(0)
        else:
            print("Profile not found!")
            sys.exit(1)

    if args.apply_config:
        print("Applying configuration... ")
        ret = apply_configuration(conf)
        sys.exit(ret)

    if ENERGY_PREF_AVAIL:
        if args.energy_performance_preference:
            pref = args.energy_performance_preference
            print("Setting energy performance preference to: ", pref)
            apply_energy_preference(pref)
            sys.exit(0)

        if args.list_energy_preferences is not None:
            cpus = parse_core_list(args.list_energy_preferences)
            print("The available energy performance preferences are:")
            for cpu in cpus:
                prefs = read_available_energy_prefs(cpu)
                current_pref = read_energy_pref(cpu)
                print("CPU {}:".format(cpu))
                if prefs:
                    for pref in prefs:
                        if pref == current_pref:
                            print("\t- {} (Current)".format(pref))
                        else:
                            print("\t- {}".format(pref))
                else:
                    print("No prefereneces were found!")
            sys.exit(0)

    import gi
    from gi.repository import Gio

    resource = Gio.Resource.load(os.path.join(pkgdatadir, "cpupower-gui.gresource"))
    resource._register()

    from cpupower_gui import main

    sys.exit(main.main(VERSION))


# vim:set filetype=python shiftwidth=4 softtabstop=4 expandtab:
