#!/bin/bash
set -euo pipefail

# Constant definitions
readonly TLP_DIR="/usr/share/tlp/deepin-system-power-control"
readonly TLP_CONFIG="/etc/tlp.d"
readonly VALID_MODES=("performance" "saving" "balance" "lowbat")
readonly VALID_COMMANDS=("set" "init-start")  # Added valid commands

# Color definitions
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly NC='\033[0m'

# Display help message
usage() {
    cat <<EOF
Usage: $0 <command> [options]

Commands:
  set <mode>      Set power mode
    Modes: ${VALID_MODES[*]}
  
  init-start      Directly start TLP service

Examples:
  $0 set performance
  $0 init-start
EOF
}

# Check root privileges
check_root() {
    [[ "$(id -u)" == "0" ]] || {
        echo -e "${RED}Error: Missing root privileges${NC}" >&2
        exit 1
    }
}

# Validate command legality (independent argument logic)
validate_command() {
    local cmd="$1"
    
    # Validate the first argument
    printf '%s\n' "${VALID_COMMANDS[@]}" | grep -qx "$cmd" || {
        echo -e "${RED}Error: Invalid command. Valid commands: ${VALID_COMMANDS[*]}${NC}" >&2
        usage
        exit 1
    }
}

# Validate arguments for 'set' command
validate_set_arguments() {
    local mode="$1"
    
    # Validate mode argument
    printf '%s\n' "${VALID_MODES[@]}" | grep -qx "$mode" || {
        echo -e "${RED}Error: Invalid mode. Valid modes: ${VALID_MODES[*]}${NC}" >&2
        usage
        exit 1
    }
}

# Cleanup old configurations
cleanup_old_configs() {
    echo -e "${YELLOW}Cleaning old configs...${NC}"
    find "${TLP_CONFIG}" -maxdepth 1 -name '*-deepin-system-power-control*.conf' -delete
}

# Apply power mode
apply_mode() {
    local mode="$1"
    local pattern="*${mode}.conf"

    echo -e "${YELLOW}Applying ${mode} configs...${NC}"
    
    # Copy configuration files
    while IFS= read -r -d $'\0' conf; do
        cp -fv "$conf" "${TLP_CONFIG}/" || {
            echo -e "${RED}Error: Failed to copy $conf${NC}" >&2
            exit 1
        }
    done < <(find "${TLP_DIR}" -type f -name "$pattern" -print0)
}

# Directly start TLP service
run_init_start() {
    echo -e "${YELLOW}Starting TLP service...${NC}"
    tlp init start || {
        echo -e "${RED}Error: tlp init failed${NC}" >&2
        exit 1
    }
    echo -e "${GREEN}Success: TLP service started${NC}"
}

# Main function
main() {
    check_root
    validate_command "${1:-}"  # Validate first argument

    case "$1" in
        "set")
            # Validate argument count
            [[ "$#" -ge 2 ]] || { usage; exit 1; }
            validate_set_arguments "$2"
            
            cleanup_old_configs
            apply_mode "$2"
            run_init_start  # Auto-start after applying config
            ;;
        "init-start")
            # Standalone command, no arguments
            [[ "$#" -eq 1 ]] || {
                echo -e "${RED}Error: 'init-start' command takes no arguments${NC}" >&2
                usage
                exit 1
            }
            run_init_start
            ;;
        *)
            usage
            exit 1
            ;;
    esac
}

# Script entry point
main "$@"
