#!/bin/bash
LOGFILE=$HOME/log/sway.log

## helpers
function _log() {
  mkdir -p $(dirname $LOGFILE)
  echo $(date) $* | tee -a $LOGFILE
}

function _check_app() {
  which $1 &> /dev/null
  if [ $? -ne 0 ]; then
    _log _check_app: ERROR missing app \"$1\"
    exit 1
  fi
}

function _check_inhibit() {
  if [ -e $1 ]; then
    _log _check_inhibit: INFO found inhibit file $1
    exit 1
  fi
}

function _check_running() {
  pgrep $1
  ret=$?
  if [ $ret -eq 0 ]; then
    _log _check_running: INFO already running $1
    exit 1
  fi
}

function _set_inhibit() {
  file=$1
  action=$2
  case "$action" in
    0|off)
      rm -f $file
      _log _set_inhibit: INFO inhibit disabled
      ;;
    1|on)
      touch $file
      _log _set_inhibit: INFO inhibit enabled
      ;;
    *)
      status=0
      if [ -f $file ]; then
        status=1
      fi
      _log _set_inhibit: INFO inhibit status: $status
      ;;
  esac
}

function getProgressString() {
  ITEMS="$1" # The total number of items(the width of the bar)
  FILLED_ITEM="$2" # The look of a filled item
  NOT_FILLED_ITEM="$3" # The look of a not filled item
  STATUS="$4" # The current progress status in percent

  # calculate how many items need to be filled and not filled
  FILLED_ITEMS=$(echo "((${ITEMS} * ${STATUS})/100 + 0.5) / 1" | bc)
  NOT_FILLED_ITEMS=$(echo "$ITEMS - $FILLED_ITEMS" | bc)

  # Assemble the bar string
  msg=$(printf "%${FILLED_ITEMS}s" | sed "s| |${FILLED_ITEM}|g")
  msg=${msg}$(printf "%${NOT_FILLED_ITEMS}s" | sed "s| |${NOT_FILLED_ITEM}|g")
  echo "$msg"
}

