#!/bin/sh
FLAG_PRINT_HELP=0
FLAG_CLEAN_MODE=0
progname=${0##*/}
dirpath=$(realpath $(dirname $0))
dir_exec_path=$(dirname $(realpath $(dirname $0)))'/libexec'
export PATH=$dirpath:$PATH:/usr/sbin:/sbin:/usr/local/sbin
PATH_LIBEXEC=$dir_exec_path:'/usr/libexec':'/usr/local/libexec':"$HOME"'/.local/libexec':$PATH

WRN_CLEAN_MODE_OBSOLETE(){
    getopt -o h --long help -- "$@" >/dev/null
    if [ $? -ne 0 ]
        then
        echo "Warning: -c or --clean for Clean Mode is obsoleted" >&22
    fi
}

WRN_DEFAULT_NOT_FOUND(){
    echo "Waning: 'default' profile not found, fallback to 'balanced'" >&2
}

#ERR_PROFILE_NOT_FOUND(){
#    echo "Waning: $@ profile not found" >&2
#    exit 1
#}

ERR_NO_WRITE_PERMISSION(){
    echo 'Error: No Write Permission for '"$@" >&2
    echo 'You may need run as root.' >&2
    exit 1
}

ERR_CONFIG_FAULT(){
    echo 'Error: '"$@" >&2
    exit 1
}

ERR_FILE_NOT_FOUND(){
    echo 'Error: File '"$@"' not found' >&2
    exit 1
}

ERR_GET_ACTIVE(){
#echo Error: >&2
    echo 'Error: Can not get current active profile.' >&2
    #echo 'It can be due to setting active profile with Clean Mode on' >&2
    #echo 'Use "$progname get -h" and "$progname set -h" for further information.' >&2
    exit 1
}

ERR_NO_CLEAN_MODE_OPTION(){
    WRN_CLEAN_MODE_OBSOLETE "$@"
    echo 'Error: Clean Mode is not for this subcommand' >&2
    exit 1
}

tlp_multimode_switch(){
    if [ $(id -u) -eq 0 ]
    then
        PATH=$PATH_LIBEXEC tlp-multimode-switch.rb $@
    else
        PATH=$PATH_LIBEXEC tlp-multimode-switch.bin $@
    fi
}

setdefault(){
    case $1 in
        'powersave'|'low'|'power-saver')
            mode='power-saver'
            ;;
        'balance'|'balanced'|'mid'|'middle'|'medium')
            mode='balanced'
            ;;
        'performance'|'high')
            mode='performance'
            ;;
        'default')
            ERR_CONFIG_FAULT 'Can not set default as default'
            ;;
#        *[![:space:]]*)
#            mode="$2"
#            ;;
#        '' | [[:space:]]*)
#            ERR_CONFIG_FAULT 'Configure name not given'
#            ;;
        '')
            ERR_CONFIG_FAULT 'Configure name not given'
            ;;
        *)
            mode="$1"
            ;;
    esac
    if [ -d '/etc/tlp-multimode/'"$mode"  ]
    then
        cd /etc/tlp-multimode/
        if [ ! -w '/etc/tlp-multimode/' ]
        then
            ERR_NO_WRITE_PERMISSION '/etc/tlp-multimode'
        fi
        if [ -e '/etc/tlp-multimode/default' ]
        then
            if [ -w '/etc/tlp-multimode/default' ]
            then
                rm -rf /etc/tlp-multimode/default
            else
                ERR_NO_WRITE_PERMISSION '/etc/tlp-multimode/default'
            fi
        fi
        ln -s "$mode" 'default'
    else
        ERR_CONFIG_FAULT "Configure not found"
    fi
}

getdefault(){
    if [ -e '/etc/tlp-multimode/default' ]
    then
        #echo $(basename $(realpath /etc/tlp-multimode/default))
        if [ -L '/etc/tlp-multimode/default' ]
        then
            echo $(basename $(readlink /etc/tlp-multimode/default))
        else
            echo default
        fi
    else
        ERR_FILE_NOT_FOUND '/etc/tlp-multimode/default'
    fi
}

getactive(){
    tmp_path='/etc/tlp.d/99-tlp-multimode.conf'
    if [ ! -e $tmp_path ]
    then
        ERR_FILE_NOT_FOUND $tmp_path
        exit 1
    fi
    while [ -L $tmp_path ]
    do
        tmp_path=$(readlink "$tmp_path")
    done
    tmp_path=$(dirname "$tmp_path")
    while true
    do
        case x"$tmp_path" in
         *'active')
            tmp_path=$(readlink $tmp_path)
        ;;
        *)
            break
        ;;
    esac
    done
    if [ x"$tmp_path" == 'x/etc/tlp.d/99-tlp-multimode.conf' ]
    then
        unset tmp_path
        ERR_GET_ACTIVE
    else
        echo $(basename $tmp_path)
        unset tmp_path
    fi
}

setactive(){
    if [ x"$1" == xdefault ]
    then
        shift
        setactive_target=$(getdefault 2>/dev/null)
        if [ $? -ne 0 ]
        then
            WRN_DEFAULT_NOT_FOUND
            setactive_target='balanced'
        fi
        set -- $setactive_target $@
    fi
    if [ -d "/etc/tlp-multimode/""$setactive_target" ]
    then
        export PATH=$PATH:$PATH_LIBEXEC
        if [ $(id -u) -eq 0 ]
        then
            tlp-multimode-switch.rb $1
        else
            tlp-multimode-switch.bin $1
        fi
    else
        ERR_FILE_NOT_FOUND "/etc/tlp-multimode/""$setactive_target"
        exit 1
    fi
}

init(){
    if [ -e '/etc/tlp.d/99-tlp-multimode.conf' ]
    then
        rm -rf '/etc/tlp.d/99-tlp-multimode.conf'
    elif [ -L '/etc/tlp.d/99-tlp-multimode.conf' ]
    then
        rm -rf '/etc/tlp.d/99-tlp-multimode.conf'
    fi
    if [ -e '/run/tlp-multimode' ]
    then
        rm -rf '/run/tlp-multimode'
    elif [ -L '/run/tlp-multimode' ]
    then
        rm -rf '/run/tlp-multimode'
    fi
    mkdir -p '/run/tlp-multimode'
    ln -s '/run/tlp-multimode/active/tlp.conf' '/run/tlp-multimode/tlp.conf'
    ln -s '/run/tlp-multimode/tlp.conf' '/etc/tlp.d/99-tlp-multimode.conf'
    if [ -d '/etc/tlp-multimode/default' ]
    then
        setactive default
    else
        setactive balanced
    fi
}

print_global_help() {
    cat >&2 <<EOF
Usage: $progname <subcommand> [options]

Subcommands:
  get            Show current active profile
  set            Set active profile
  getdefault     Show current default profile
  setdefault     Set default profile, need root permission
  switch         Alias for Subcommands set
  help           Show this help page

Use "$progname <subcommand> -h" for subcommand help.
EOF
}

print_getdefault_help() {
    cat >&2 <<EOF
Uasge: $progname getdefault
  to get current default profile

EOF
}

print_setdefault_help() {
    cat >&2 <<EOF
Uasge: $progname setdefault <profile>
  Preset Profiles:
    power-saver
      alias: powersave | low
    balanced
      alias: balance | mid | middle | medium
    performance
      alias: high

  You can also use other custom profiles.
  But do not use profile naming:
    default, powersave, balance, low, mid, high, medium, middle

EOF
}

print_set_help() {
    cat >&2 <<EOF
Usage: $progname set <profile>
  Preset Profiles:
    power-saver
      alias: powersave | low
    balanced
      alias: balance | mid | middle | medium
    performance
      alias: high
    default
      this profile will be use if no profile name given

  You can also use other custom profiles.
  Use "$progname setdefault -h" for further information.

Options:
  -c, --clean       Obsolete
  -h, --help        Show this help page

EOF
}

print_switch_help(){
    print_set_help
}

print_get_help() {
    cat >&2 <<EOF
Uasge: $progname get
  to get current active profile

EOF
}

if [ $# -eq 0 ]; then
    print_global_help
    exit 0
fi
getopt -o hc --long help --long clean --long clean-config --long clean-profile -- "$@" >/dev/null
if [ $? -ne 0 ]
then
    print_global_help
    exit 1
fi
OPTIONS_GETOPT=$(getopt -o hc --long help --long clean --long clean-config --long clean-profile -- "$@"| sed 's/ -- .*//' | sed 's/^-- .*//' | sed 's/ --$//')
SUBCOMMAND_GETOPT=$(getopt -o hc --long help --long clean --long clean-config --long clean-profile -- "$@"|awk -F '-- ' '{print $2}')
eval set -- $SUBCOMMAND_GETOPT

for OPTION_GETOPT in $OPTIONS_GETOPT
do
    case $OPTION_GETOPT in
        -c | --clean | --clean-config | --clean-profile)
        FLAG_CLEAN_MODE=1
        ;;
        -h|--help)
        FLAG_PRINT_HELP=1
        ;;
    esac
done
if [ $FLAG_PRINT_HELP -eq 1 ]
then
    WRN_CLEAN_MODE_OBSOLETE
fi

while [ $# -ne 0 ]
do
    if  [ $1 == '-'* ]
    then
        shift
    else
        break
    fi
done
case $1 in
    getdefault|get-default)
        if [ $FLAG_PRINT_HELP -eq 1 ]
        then
            print_getdefault_help
            exit 0
#        elif [ $FLAG_CLEAN_MODE -eq 1 ]
#        then
#            ERR_NO_CLEAN_MODE_OPTION $OPTIONS_GETOPT
        else
            getdefault
            exit 0
        fi
        ;;

    setdefault|set-default)
        if [ $FLAG_PRINT_HELP -eq 1 ]
        then
            print_setdefault_help
            exit 0
#        elif [ $FLAG_CLEAN_MODE -eq 1 ]
#        then
#            ERR_NO_CLEAN_MODE_OPTION $OPTIONS_GETOPT
        else
            shift
            setdefault $@
            getdefault
            exit 0
        fi
        ;;

    get|getactive|get-active)
        if [ $FLAG_PRINT_HELP -eq 1 ]
        then
            print_get_help
            exit 0
#        elif [ $FLAG_CLEAN_MODE -eq 1 ]
#        then
#            ERR_NO_CLEAN_MODE_OPTION $OPTIONS_GETOPT
        else
            getactive
            exit 0
        fi
        ;;

    set|setactive|set-active|switch)
        if [ $FLAG_PRINT_HELP -eq 1 ]
        then
            print_set_help
            exit 0
#        elif [ $FLAG_CLEAN_MODE -eq 1 ]
#        then
#            WRN_CLEAN_MODE_OBSOLETE $@
#            shift
#            tlp_multimode_switch $@
#            exit 0
        else
            shift
            echo going to activate profile $@
            setactive $@
            exit 0
        fi
        ;;

    help|h|'')
        print_global_help
        exit 0
        ;;
    *)
        if [ $FLAG_PRINT_HELP -eq 1 ]
        then
            print_global_help
            exit 0
        else
            init
            exit 0
        fi
        ;;
esac
exit 0
