#!/usr/bin/env bash

if [[ -z $YKEDA_AUTOFAN_CONF ]]; then #reread env variables as after upgrade this can be empty
  source /etc/environment
  export $(cat /etc/environment | grep -vE '^$|^#' | cut -d= -f1) #export all variables from file
fi

. colors

MAINTENANCE_SEM_NAME="/tmp/ykeda_autofan_maintenance"
CLI_OUTPUT=/run/hive/ykeda_autofan
YKEDA_PORT=

#flag that the message was sent
unable_to_set_fan_speed=0
#unparsable data
error_in_read_configs=0

check_config() {
  if [ ! -f $YKEDA_AUTOFAN_CONF ]; then
    echo2 "${RED}No config $YKEDA_AUTOFAN_CONF${NOCOLOR}"
  fi
}

check_sem() {
if [[ -f $MAINTENANCE_SEM_NAME ]]; then
  a=0
  let a=`date +%s`-`stat --format='%Y' $MAINTENANCE_SEM_NAME`
  if [[ a -le 60 ]]; then
    #echo2 "Coolbox is in maintenance mode. Command ignored."
    return 1 #coolbox is in maintenance mode
  else
    return 0
  fi
fi
}

get_file_time_diff(){
  local a=999
  [[ -f $CLI_OUTPUT ]] && let a=`date +%s`-`stat --format='%Y' $CLI_OUTPUT`
  echo $a
}

start_listner(){
  stty -F $YKEDA_PORT raw ispeed 9600 ospeed 9600 -ignpar cs8 -cstopb -echo
  sleep 0.2

  screen -dm -c /hive/opt/ykeda/screenrc.ykeda_autofan cat $YKEDA_PORT
  for i in {1..25}; do
    sleep 0.2 #it needs some time? it happens that you'll have "No screen session found" without sleep
    local session_count=`screen -ls ykeda_autofan | grep -c "ykeda_autofan"`
    [[ $session_count -gt 0 ]] && break #echo -e "Found screen miner in $i iterations" &&
    [[ $i -ge 25 ]] && echo -e "${RED}screen miner not found in 25 iterations, check logs and maybe flash drive speed${NOCOLOR}"
  done
}

stop_listner(){
  local screens=(`screen -ls ykeda_autofan | grep -Po "\K[0-9]+(?=\.ykeda_autofan)" | sort --unique`)
  for pid in "${screens[@]}"; do
    timeout 1 screen -S $pid.ykeda_autofan -X quit
  done

  #removing listner output
  rm -f $CLI_OUTPUT
#  rm -f ${CLI_OUTPUT}_50
}

send_request(){
  check_sem
  [[ $? -ne 0 ]] && return 1 #coolbox is in maintenance mode

  #check coolbox listner
  local session_count=`screen -ls ykeda_autofan | grep -c "ykeda_autofan"`
  if [[ $session_count -eq 0 ]]; then #starting coolbox listner
    start_listner
  fi

  if [[ `get_file_time_diff` -gt 30 ]]; then
    stop_listner
    start_listner
  fi

  echo -n $1 > $YKEDA_PORT
  sleep 2

  if [[ -f ${CLI_OUTPUT} ]]; then
    local rtn=`tail -1 ${CLI_OUTPUT}`
    echo "$rtn"
  fi
}

get_stats(){
#  cache disabled becouse now there are several commands

  #read config
  if [[ -f $YKEDA_AUTOFAN_CONF ]]; then #in case serial verification error no conf will be received
    source $YKEDA_AUTOFAN_CONF
  fi

  [[ $AUTO_ENABLED -eq 0 ]] && FAN_MODE=1 || FAN_MODE=2

  temp_array=
  mtemp_array=
  #check $GPU_STATS_JSON and do nothing while not exist
  if [ -f $GPU_STATS_JSON ]; then
    temp_array=`cat $GPU_STATS_JSON | tail -1 | jq -c ".temp"`
    mtemp_array=`cat $GPU_STATS_JSON | tail -1 | jq -c ".mtemp"`

    local cpu_indexes_array=`cat $GPU_DETECT_JSON | jq -c '[ . | to_entries[] | select(.value.brand == "cpu") | .key ]'` #'

    #remove Internal Gpus
    if [[ $cpu_indexes_array != '[]' && ! -z $cpu_indexes_array ]]; then
      temp_array=$(jq -c "del(.$cpu_indexes_array)" <<< $temp_array) #"
      if [[ mtemp_array != 'null' ]]; then
        mtemp_array=$(jq -c "del(.$cpu_indexes_array)" <<< $mtemp_array) #"
      fi
    fi
  fi
  temp_array=${temp_array//\"}
  mtemp_array=${mtemp_array//\"}

  [[ -z $TARGET_TEMP ]] && TARGET_TEMP=60
  [[ -z $TARGET_MEM_TEMP ]] && TARGET_MEM_TEMP=90
  [[ -z $MANUAL_FAN ]] && MANUAL_FAN=50
  [[ -z $FAN_MODE ]] && FAN_MODE=1
  [[ -z $MIN_FAN ]] && MIN_FAN=30
  [[ -z $MAX_FAN ]] && MAX_FAN=100

  request_str='{"gpu_temp":'$temp_array',"gpu_mtemp":'$mtemp_array',"target_temp":'$TARGET_TEMP',"target_mtemp":'$TARGET_MEM_TEMP',"manual_fan_speed":'$MANUAL_FAN',"fan_mode":'$FAN_MODE',"min_fan":'$MIN_FAN',"max_fan":'$MAX_FAN'}'

  send_request $request_str
}

get_json(){
  local answer=`get_stats`
  echo $answer | jq '.thermosensors' >> /dev/null 2>&1
  if [[ $? -eq 0 ]] && [[ $answer =~ "thermosensors" ]]; then
    echo "$answer" | jq -c '.'
  fi

  #echo '{"casefan": [55,55,0,550], "thermosensors": [23,32,350]}'
}

diagnostic(){
  local answer=`send_request '{"diagnostic"}'`
  echo $answer | jq '.message' >> /dev/null 2>&1
  if [[ $? -eq 0 ]] && [[ $answer =~ *message* ]]; then
    echo "$answer"
  fi
}

fan_check(){
  local answer=`send_request '{"fan_check"}'`
  echo $answer | jq '.message' >> /dev/null 2>&1
  if [[ $? -eq 0 ]] && [[ $answer =~ "fan check" ]]; then
    echo "$answer" | jq -r '.message'
  fi
}

msg(){
  local answer=`send_request '{"message":"'$1'"}'`
  echo "$answer" | jq '.message' >> /dev/null 2>&1
  if [[ $? -eq 0 ]] && [[ $answer =~ "message" ]]; then
    echo "$answer" | jq -r '.message'
  fi
}

if [[ `lsusb -v -d 10c4:ea60 | grep iSerial | awk '{print $3}'` == 'ykeda_autofan' ]]; then
  YKEDA_PORT=/dev/ttyUSB0
fi

if [[ `lsusb -v -d 10c4:ea70 | grep iSerial | awk '{print $3}'` == 'ykeda_autofan' ]]; then
  YKEDA_PORT=/dev/ttyUSB1
fi

if [[ -n $YKEDA_PORT ]]; then
  if [[ $1 == "--get_json" ]]; then
    echo `get_json`
  elif [[ $1 == "--diagnostic" ]]; then
    echo `diagnostic`
  elif [[ $1 == "--fan_check" ]]; then
    echo `fan_check`
  elif [[ $1 == "--msg" ]]; then
    echo `msg $2`
  else
    echo "Error: wrong command."
    exit 1
  fi
else
  if [[ $1 == "--get_json" ]]; then
    echo "{}"
  else
    echo "No Ykeda Autofan found"
  fi
fi
