#!/usr/bin/env bash

# well ... it blinks the led
blink_led() {
  for i in $(seq 1 "$1"); do
    echo 0 >/sys/class/leds/led0/brightness
    sleep 0.3
    echo 1 >/sys/class/leds/led0/brightness
    sleep 0.3
  done
  echo 0 >/sys/class/leds/led0/brightness
  sleep 0.3
}

# starts mon0
start_monitor_interface() {
  iw phy phy0 interface add mon0 type monitor && ifconfig mon0 up
}

# stops mon0
stop_monitor_interface() {
  ifconfig mon0 down && iw dev mon0 del
}

# returns 0 if the specificed network interface is up
is_interface_up() {
  if grep -qi 'up' /sys/class/net/$1/operstate; then
    return 0
  fi
  return 1
}

# returns 0 if conditions for AUTO mode are met
is_auto_mode() {
  # check override file first
  if [ -f /root/.pwnagotchi-manual ]; then
    # remove the override file if found
    rm -rf /root/.pwnagotchi-manual
    return 1
  fi

  # check override file first
  if [ -f /root/.pwnagotchi-auto ]; then
    # remove the override file if found
    rm -rf /root/.pwnagotchi-auto
    return 0
  fi

  # if usb0 is up, we're in MANU
  if is_interface_up usb0; then
    return 1
  fi

  # if eth0 is up (for other boards), we're in MANU
  if is_interface_up eth0; then
    return 1
  fi

  # no override, but none of the interfaces is up -> AUTO
  return 0
}

# returns 0 if conditions for AUTO mode are met
is_auto_mode_no_delete() {
  # check override file first
  if [ -f /root/.pwnagotchi-manual ]; then
    return 1
  fi

  # check override file first
  if [ -f /root/.pwnagotchi-auto ]; then
    return 0
  fi

  # if usb0 is up, we're in MANU
  if is_interface_up usb0; then
    return 1
  fi

  # if eth0 is up (for other boards), we're in MANU
  if is_interface_up eth0; then
    return 1
  fi

  # no override, but none of the interfaces is up -> AUTO
  return 0
}