#!/bin/bash

TLP_DIR="/usr/share/tlp/deepin-system-power-control"
TLP_CONFIG="/etc/tlp.d"

if [ "$(id -u)" != "0" ]; then
    echo "Error:missing root privilege"
    exit 1
fi

if [ "$1" != "set" ]; then
    echo "The first parameter must be 'set'"
    exit 1
fi

if [ "$2" != "performance" ] && [ "$2" != "saving" ] && [ "$2" != "balance" ] && [ "$2" != "lowbat" ]; then
    echo "The second parameter must be 'performance' or 'saving' or 'balance' or 'lowbat' "
    exit 1
fi

if [ "$2" == "performance" ]; then

    if ls ${TLP_CONFIG}/*-deepin-system-power-control*.conf 1> /dev/null 2>&1; then
       	rm ${TLP_CONFIG}/*-deepin-system-power-control*.conf
    fi

    for conf in $(find ${TLP_DIR} -type f -name *performance.conf);do
        cp ${conf} ${TLP_CONFIG}/
    done

    if [ $? -ne 0 ]; then
        echo "Copy file failed"
        exit 1
    fi

    tlp init start

    if [ $? -ne 0 ];then
        echo "tlp set failed"
        exit $?
    fi
elif [ "$2" == "saving" ]; then

    if ls ${TLP_CONFIG}/*-deepin-system-power-control*.conf 1> /dev/null 2>&1; then
        rm ${TLP_CONFIG}/*-deepin-system-power-control*.conf
    fi

    for conf in $(find ${TLP_DIR} -type f -name *saving.conf);do
        cp ${conf} ${TLP_CONFIG}/
    done

    if [ $? -ne 0 ]; then
        echo "Copy file failed"
        exit 1
    fi

    tlp init start

    if [ $? -ne 0 ];then
        echo "tlp set failed"
        exit $?
    fi
elif [ "$2" == "balance" ]; then

    if ls ${TLP_CONFIG}/*-deepin-system-power-control*.conf 1> /dev/null 2>&1; then
        rm ${TLP_CONFIG}/*-deepin-system-power-control*.conf
    fi

    for conf in $(find ${TLP_DIR} -type f -name *balance.conf);do
        cp ${conf} ${TLP_CONFIG}/
    done

    if [ $? -ne 0 ]; then
        echo "Copy file failed"
        exit 1
    fi

    tlp init start

    if [ $? -ne 0 ];then
        echo "tlp set failed"
        exit $?
    fi
elif [ "$2" == "lowbat" ]; then

    if ls ${TLP_CONFIG}/*-deepin-system-power-control*.conf 1> /dev/null 2>&1; then
        rm ${TLP_CONFIG}/*-deepin-system-power-control*.conf
    fi

    for conf in $(find ${TLP_DIR} -type f -name *lowbat.conf);do
        cp ${conf} ${TLP_CONFIG}/
    done

    if [ $? -ne 0 ]; then
        echo "Copy file failed"
        exit 1
    fi

    tlp init start

    if [ $? -ne 0 ];then
        echo "tlp set failed"
        exit $?
    fi
fi
