#!/bin/bash

_ifs="${IFS}"

profilelist=()
function load_profiles() {
 IFS=$'\n'
 profilelist=($(find profiles -mindepth 1 -maxdepth 1 -type d))
 IFS="${_ifs}"
}

function switch_profile() {
 local profile_folder="${1}" profile_name="${profile_folder##*/}"
 local resp pid
 
 echo "Should switch to profile '${profile_folder}'."
 
 if speedfan_running; then
  echo -n "Speedfan is currently running. Please close it before the configuration
profile can be switched.
Waiting. Press 'c' to cancel, or 'k' to attempt to kill it . . ."
  while speedfan_running; do
   read -n 1 -s -t 0.25 resp
   
   if [ "${resp}" == "c" ]; then
    break
   elif [ "${resp}" == "k" ]; then
    pid="$(tasklist /fi "imagename eq speedfan.exe" /fo list | egrep "^PID:" | head -n1 | strings | sed -E "s/^PID: +//")"
    echo -n "
Killing process id ${pid}..."
    taskkill /pid "${pid}"
    sleep 1
    if speedfan_running; then
     echo "Unable to stop SpeedFan."
    fi
    break
   fi
  done

  if ! speedfan_running; then
   echo "
Speedfan process interrupted."
  else
   echo "
Cancelling profile update process."
   return 1
  fi
 fi
 
 echo -n "Updating profile: "
 cp "${profile_folder}"/speedfan{params,sens}.cfg .
 echo "done.
   
*** Restart speedfan to apply changes!"
}

function speedfan_running() {
 if [ "$(tasklist /fi "imagename eq speedfan.exe" /fo list | wc -l)" -gt 1 ]; then
  return 0
 else
  return 1
 fi
}

function save_profile() {
 local resp
 
 while true; do
 echo -n "
- Enter new profile name (empty to cancel): "
  read resp
  if [ -z "${resp}" ]; then
   echo "Profile name must not be empty."
   return 0
  elif [ ! -z "${resp//[a-zA-Z0-9_-]}" ]; then
   echo "Invalid profile name: ${resp}"
  else
   break
  fi
 done

 if [ -e "profiles/${resp}" ]; then
  echo "Unable to create profile: file exists."
  return 1
 fi
 
 if ! mkdir "profiles/${resp}" > /dev/null 2>&1; then
  echo "Error creating profile directory. Aborting."
  return 1
 fi
 
 if ! cp speedfan{params,sens}.cfg "profiles/${resp}"/. > /dev/null 2>&1; then
  echo "Error copying settings to profile."
  return 1
 fi
 
 load_profiles
 echo "Created profile: ${resp}."
}

load_profiles

if [ ${#profilelist[@]} -lt 1 ]; then
 echo "No profile to switch to. Create one from the current setup with --create."
 exit 1
fi

while true; do
 echo "Available profiles: "
 prid=1
 for profiledir in "${profilelist[@]}"; do
  echo "${prid}. ${profiledir##*/}"
  prid="$(( 10#${prid} + 1 ))"
  if [ -e "${profiledir}/descript.ion" ]; then
   cat "${profiledir}/descript.ion" | while read line; do
    echo "    ${line}"
   done
  fi
 done

 echo -n "s. Save current SpeedFan settings to a new profile.
q. Quit without changing.

- Choose a profile to switch to: "
 read -n1 resp

 if [ -z "${resp/[0-9]}" ]; then
  echo ""
  switch_profile "${profilelist[resp-1]}"
  exit 0
 elif [ "${resp}" == "s" ]; then
  save_profile
 elif [ "${resp}" == "q" ]; then
  echo "
Exitting without changes."
  exit 0
 fi
done
