#!/usr/bin/env bash

if [[ -z $WINDTANK_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/windtank_autofan_maintenance"
CLI_INPUT="/run/hive/fan_controller_req"
CLI_OUTPUT="/run/hive/fan_controller_rsp"
CLI_DELAY=60
RECALLIBRATE_REQ="/run/hive/fan_controller_recallibrate_req"
RECALLIBRATE_RSP="/run/hive/fan_controller_recallibrate_rsp"
RECALLIBRATE_DELAY=600
REPORT_REQ="/run/hive/fan_controller_report_req"
REPORT_RSP="/run/hive/fan_controller_report_rsp"
REPORT_DELAY=1200
KEY_FILE="/hive-config/*.key_slave"
MODEL_FILE="/hive-config/device.wtt"

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

check_config() {
  if [ ! -f $WINDTANK_AUTOFAN_CONF ]; then
    echo2 "${RED}No config $WINDTANK_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
}

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

  echo -n $1 > $CLI_INPUT
  sleep 2

  if [[ `get_file_time_diff` -lt $CLI_DELAY ]]; then
    cat ${CLI_OUTPUT}
  fi

}

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

  #read config
  if [[ -f $WINDTANK_AUTOFAN_CONF ]]; then #in case serial verification error no conf will be received
    source $WINDTANK_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 '.casefan' >> /dev/null 2>&1
  if [[ $? -eq 0 ]] && [[ $answer =~ "casefan" ]]; then
    echo "$answer" | jq -c '.'
  fi

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

diagnostic(){
  [[ -f $REPORT_RSP ]] && rm -f $REPORT_RSP
  touch $REPORT_REQ
  start_time=`date +%s`
  elapsed=0
  while [[ $elapsed -le $REPORT_DELAY ]]; do
    let elapsed=$start_time-`date +%s`
    if [[ -f $REPORT_RSP ]]; then
      cat $REPORT_RSP
      rm -f $REPORT_RSP
      return 0
    fi
    sleep 1
  done
  return 1
}

fan_check(){
  [[ -f $RECALLIBRATE_RSP ]] && rm -f $RECALLIBRATE_RSP
  touch $RECALLIBRATE_REQ
  start_time=`date +%s`
  elapsed=0
  while [[ $elapsed -le $RECALLIBRATE_DELAY ]]; do
    let elapsed=$start_time-`date +%s`
    if [[ -f $RECALLIBRATE_RSP ]]; then
      cat $RECALLIBRATE_RSP
      rm -f $RECALLIBRATE_RSP
      return 0
    fi
    sleep 1
  done
  return 1
}

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
}

check_hw(){
  if ls $KEY_FILE >> /dev/null 2>&1; then
    return 0
  else
    return 1
  fi
}

get_model(){
  if [[ -f $MODEL_FILE ]]; then
    cat $MODEL_FILE
  else
    echo "Unknown model"
  fi
}

if [[ $1 == "--check_hw" ]]; then
  check_hw && exit 0 || exit 1
fi

if check_hw; 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`
  elif [[ $1 == "--model" ]]; then
    echo `get_model`
  else
    echo "Error: wrong command."
    exit 1
  fi
else
  if [[ $1 == "--get_json" ]]; then
    echo "{}"
  else
    echo "No Autofan found"
  fi
fi
