#!/usr/bin/env bash

. colors

[[ -e /hive/etc/environment && -z $TWEAKERS_CONF ]] && TWEAKERS_CONF="/hive-config/tweakers.json"
TWEAKERS_LOG="/var/log/tweakers.log"

function tweakers_amdmemtweak(){
   local tweak_json=$1
   local length=$(jq '.|length' <<< "$tweak_json")
   local error=0

   for ((i=0; i<$length; i++)); do
      gpuid=$(echo "$tweak_json" | jq -e --raw-output --arg line "$i" '.[$line|tonumber].gpu|tostring')
      if [[ $? -gt 0 ]]; then
         error=1
         continue
      else
         [[ $gpuid != "null" ]] && arg_gpu="--GPU $gpuid" || continue
      fi

      cmdline=`echo "$tweak_json" | jq -e -j --arg line "$i" '.[$line|tonumber] | .params | to_entries|map("--\(.key|ascii_upcase) \(.value|tonumber) ")|.[]'`
      if [[ $? -gt 0 ]]; then
         error=1
         continue
      fi
#      echo amdmemtweak --GPU $gpuid $cmdline
      amdmemtweak $arg_gpu $cmdline | tee -a $TWEAKERS_LOG
#      amdmemtweak --GPU $gpuid $cmdline | tee -a $TWEAKERS_LOG
      if [[ $? -gt 0 ]]; then
         error=1
         continue
      fi
   done
   return $error
}

##############################################################################
# Main
##############################################################################
exitcode=0

if [[ "$1" == "log" ]]; then
    [[ ! -f $TWEAKERS_LOG ]] && echo "${YELLOW}$TWEAKERS_LOG does not exist${NOCOLOR}" && exit 1
    cat $TWEAKERS_LOG 2>/dev/null && echo -e "\n${GRAY}=== $TWEAKERS_LOG === $( stat -c %y $TWEAKERS_LOG )${NOCOLOR}"
    exit $exitcode
fi

[[ ! -e $TWEAKERS_CONF ]] && echo -e "${YELLOW}No tweakers config found${NOCOLOR}" && exit 1

tools_list=($(jq -cr  '. | keys | .[]' $TWEAKERS_CONF 2>&1))
exitcode=$?
[[ "$exitcode" != 0 ]] && exit $exitcode
#[[ "$exitcode" != 0 ]] && echo -e "${YELLOW}Tweakers config has bad format${NOCOLOR}" && exit $exitcode
tools_count=${#tools_list[@]}
[[ $tools_count -eq 0 ]] && echo -e "${YELLOW}No tweakers found in config${NOCOLOR}" && exit

date | tee $TWEAKERS_LOG
echo -e "${NOCOLOR}Found ${GREEN}${#tools_list[@]}${NOCOLOR} tweaker(s) to apply: ${GREEN}${tools_list[*]}${NOCOLOR}\n"

for tweaker_tool in "${tools_list[@]}"; do
   echo -e "${NOCOLOR}Applying tweaker: ${CYAN}$tweaker_tool${NOCOLOR}" | tee -a $TWEAKERS_LOG
   case $tweaker_tool in
      amdmemtweak)
        #echo $(jq -cr  '.amdmemtweak[]' $TWEAKERS_CONF)
        tweakers_amdmemtweak "$(jq -c  '.amdmemtweak' $TWEAKERS_CONF)"
        exitcode=$?
      ;;
   esac
   echo
done

exit $exitcode
