#!/bin/bash

cputmp=$(( $(cat /sys/class/thermal/thermal_zone0/temp)/100 ));cputmp=$(echo "$cputmp" | sed 's/./&./2')
alias temp='echo -e "GPU: $( sudo vcgencmd measure_temp | cut -d'=' -f2)";echo -e "CPU: $(echo -e $cputmp )\x27C"'

alias volts='echo "$(vcgencmd measure_volts | cut -d= -f2)"'

alias txt='sudo nano'
alias run='sudo bash'
alias dump='sudo tee'
alias ll='ls -la --color=always'
alias ss='sudo du -sh ./* | sort -hr'
alias wget='wget --no-check-certificate'

alias py='sudo python3'
alias autostart='sudo nano /opt/retropie/configs/all/autostart.sh'
alias retroarch='/opt/retropie/emulators/retroarch/bin/retroarch'
alias myip='hostname -I | cut -d" " -f1'
alias reload='clear && source /home/pi/.bashrc'
alias aliases='alias && cat /home/pi/.bash_aliases | grep -vi "^[#]" | grep -v aliases | grep "()" | cut -d" " -f1'
alias alias-edit='sudo nano /home/pi/.bash_aliases'
alias lsdev='ls -l --color=always /dev/ | cut -c 49- | less -R'
alias teensytest='evtest /dev/input/by-id/usb-Teensyduino_Serial_Keyboard_Mouse_Joystick_1008140-if02-event-kbd'
alias triggers='sudo nano /etc/triggerhappy/triggers.d/teensy.conf'

alias decolor.styles='sed -E "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})*)?[m,K,H,f,J]//gm"'
alias decolor.reset='sed -E "s/\x1B\([A-Z]{1}(\x1B\[[m,K,H,f,J])?//gm"'
alias decolor='decolor.styles | decolor.reset'

alias scan_coin='sudo scanmem -p `pidof retroarch` -c"option region_scan_level 3;reset"'


doc() {
  [ "${#}" -lt 1 ] && return
  local doc_dir="/home/pi/ADMIN/DOCS"
  local args="${@}"
  local action=''
  local cmd=''
  local name=''

  if [[ ${#} -lt 2 ]]; then
    case "${1,,}" in
      'list'|'view'|'help'|'l'|'v'|'h'|'-l'|'-v'|'-h'|'--l'|'--v'|'--h')
        find "$doc_dir" -type f -name "*.doc" | sort | awk -F'\\/' '{print $NF}' | less -XKEFR
        return
        ;;
      *)
        action='write'
        name="${1}"
        [ -f "$doc_dir/$name.doc" ] && action='read' || action='write'
        ;;
    esac
  else
    name="${2}"; action='write'

    case "${1,,}" in
      'read'|'r'|'-r'|'--r')
	 [ -f "$doc_dir/$name.doc" ] && action='read' || action='write';;
      'write'|'w'|'-w'|'--w'|'man')
	 action='write' ;;
      *) ;;
    esac
  fi

  echo -e "action: $action, name: $name"

  if [[ $action == 'read' ]]; then
    echo -e "found doc file!\n"
  else
    echo -e "writing doc file..\n"
    cmd="PAGER='cat' man $name"
    rc=$(sudo -- bash -c "$cmd &>/dev/null"; echo $?)
    [[ $rc -lt 1 ]] && sudo -- bash -c "$cmd 2>&1 | sudo tee $doc_dir/$name.doc" &>/dev/null \
    || { echo "man page not found for $name"; return; }
  fi

  #[ -f "$doc_dir/$name.doc" ] &&[ "$action" == "read" ] && [ $force -gt 0 ] && action='write'

  echo -e "Read '$doc_dir/$name.doc' ? (Y/n)" && read -srN1 choice
  case $choice in [yY]) sudo -- bash -c "cat $doc_dir/$name.doc | less -XKEFR" ;; esac
}


elapsed() {
  s=$(( $(date +%s%N) / 1000 )); s=${s:6}
  [[ "$@" == "set" ]] && export ns=$s

  env_ns=$(( $(env | grep ns | grep -oe '[^=]*$') ))
  val=$( echo $(( s - ns )) | sed 's/-//g')

  echo $(( val / 1000 ))
}

ns() {
  local arg="${@}"
  local ns=$(( $(date +%s%N) / 1000 )); ns=${ns:6}
  #local env_ns=0

  if [[ "${arg:0:1}" == '-' ]]; then
    arg=$(echo "$arg" | sed 's/-//g' | tr '[:upper:]' '[:lower:]')
    [ $arg == "set" ] || [ $arg == "reset" ] && export env_ns=$ns
    env | grep env_ns | grep -oe '[^=]*$' # REM
  fi
  #if [ $(env | grep ns | grep -c -oe '[^=]*$') ]; then
  env | grep ns | grep -oe '[^=]*$' # REM
  #local env_ns=$(env | grep ns | grep -oe '[^=]*$') ADD
  #[[ $env_ns > 0 ]] && echo "env_ns: $env_ns" #ADD
  #[ $(env | grep -c -m1 ns=) -gt 0 ] && ns=$((
  echo "ns: $ns"
  #fi
}

key() {
  [ "${#}" -lt 1 ] && return

  local device='/dev/input/by-id/usb-Teensyduino_Serial_Keyboard_Mouse_Joystick_1008140-if02-event-kbd'
  local data_path='/home/pi/ADMIN/FILES'
  local arg=$(echo "$@" | tr '[:lower:]' '[:upper:]')

  if [[ "${arg:0:2}" == '-H' ]] || [[ "${arg:0:3}" == '--H' ]]; then
    cat "$data_path/KEY_NAMES.doc" | less -EKRX
  else
    [[ $(echo "$arg" | grep -co --color=never "KEY_") -gt 0 ]] && arg=$(echo "$arg" | awk -F'KEY_' '{print $2}')
    code="KEY_${arg}"

    if [[ $(grep -c -m1 "$code" "$data_path/KEY_NAMES.lst") -gt 0 ]]; then
      echo -e "pressing \x27$code\x27"
      (timeout 2 /usr/bin/evtest "$device" |& grep -P "(?=.*($code))(?=.*Event:)" 2>&1 & PID=$!)
      sudo -- bash -c "evemu-event $device --type EV_KEY --code $code --value 1 --sync; evemu-event $device --type EV_KEY --code $code --value 0 --sync"
      wait $PID
    else
      echo "key '$arg' not found.."
    fi
  fi
}

joy() {
  #sudo -- bash -c 'evemu-event /dev/input/event9 --type EV_ABS --code ABS_Y --value 255 --sync; evemu-event /dev/input/event9 --type EV_ABS --code ABS_Y --value 127 --sync'

  local device='/dev/input/by-id/usb-SHANWAN_Skyuan_F16-event-joystick'
  local type=
  local code=
  local val_high=
  local val_low=

  [ "${#}" -lt 1 ] && return
  arg="${@}"
  case $arg in
   'UP'|'up'|'U'|'u')
     type='EV_ABS'; code='ABS_Y'; val_high='255'; val_low='127'
     ;;
   'DOWN'|'down'|'D'|'d')
     type='EV_ABS'; code='ABS_Y'; val_high='0'; val_low='127'
     ;;
   'LEFT'|'left'|'L'|'l')
     type='EV_ABS'; code='ABS_X'; val_high='255'; val_low='128'
     ;;
   'RIGHT'|'right'|'R'|'r')
     type='EV_ABS'; code='ABS_X'; val_high='0'; val_low='128'
     ;;
   'A'|'a'|'1'|'thumb'|'THUMB'|'BTN'|'btn')
     type='EV_KEY'; code='BTN_THUMB'; val_high='1'; val_low='0'
     ;;
   'B'|'b'|'2'|'trigger'|'TRIGGER')
     type='EV_KEY'; code='BTN_TRIGGER'; val_high='1'; val_low='0'
     ;;
   *)
     return
     ;;
  esac

  sudo -- bash -c "evemu-event $device --type $type --code $code --value $val_high --sync; evemu-event $device --type $type --code $code --value $val_low --sync "
}

ev() {
  key=${1:-'ENTER'}
  dev=${2:-'1'}
  type=${3:-'KEY'}

  echo "1: $key, 2: $dev, 3: $type"

  key="${type}_${key}"; key=$(echo "${key}" | tr '[:lower:]' '[:upper:]')
  type="EV_${type}"; type=$(echo "${type}" | tr '[:lower:]' '[:upper:]')
  dev="/dev/input/event${dev}"

  echo "key: $key, dev: $dev, type: $type"

  cmd=
  for i in {1..0}; do
    cmd+="evemu-event $dev --type $type --code $key --value $i --sync;"
  done

  sudo -- bash -c "$cmd"

  #'

  #echo "event$dev"; echo "EV_$type"; echo "$type $key"
  #echo "/dev/input/event$dev --type EV_$type --code $type_$key"
  #sudo -- bash -c ' \
  #  evemu-event "/dev/input/event$dev" --type "EV_$type" --code "$type_$key" --value 1 --sync; 
  #  evemu-event "/dev/input/event$dev" --type "EV_$type" --code "$type_$key" --value 0 --sync
  #'
}


blank() {
  tty=$(tty)

  local arg=${1}
  arg=$(echo "$arg" | sed -e "s/ \+//g")

  [[ "${arg:0:2}" == "--" ]] && arg="${arg:2}"
  [[ "${arg:0:1}" == "-" ]] && arg="${arg:1}"

  arg=$(echo "$arg" | tr '[:upper:]' '[:lower:]')

  case $arg in
   '1'|'on'|'true'|'enabled')
     [[ $tty == /dev/tty* ]] && setterm --blank force || sudo setterm --blank force --term linux </dev/tty1
     ;;
   '0'|'off'|'false'|'disabled')
    [[ $tty == /dev/tty* ]] && setterm --blank poke   || sudo setterm --blank poke --term linux </dev/tty1
     ;;
  esac

}

findstr() {
  [ "${#}" -lt 1 ] && return
  local str=${1}
  local dir=${2:-'/home/pi/'}
  grep -lR "$str" "$dir" | sort -u
}

mem() {
  cat /proc/meminfo
}

hex() {
  printf "%02x\n" "${1}" | tr '[[:lower:]]' '[[:upper:]]'

}

config() {
  sudo bash /home/pi/ADMIN/CMD/CONFIG/CONFIG.sh "$@"
}

checkvolts() {
  STATUS=$(vcgencmd get_throttled | sed -n 's|^throttled=\(.*\)|\1|p')
  echo "$STATUS"
  if [[ ${STATUS} -ne 0 ]]; then
    echo ""
    if [ $((${STATUS} & 0x00001)) -ne 0 ]; then
      echo "Power is currently Under Voltage"
    elif [ $((${STATUS} & 0x10000)) -ne 0 ]; then
      echo "Power has previously been Under Voltage"
    fi
    if [ $((${STATUS} & 0x00002)) -ne 0 ]; then
      echo "ARM Frequency is currently Capped"
    elif [ $((${STATUS} & 0x20000)) -ne 0 ]; then
      echo "ARM Frequency has previously been Capped"
    fi
    if [ $((${STATUS} & 0x00004)) -ne 0 ]; then
      echo "CPU is currently Throttled"
    elif [ $((${STATUS} & 0x40000)) -ne 0 ]; then
      echo "CPU has previously been Throttled"
    fi
    if [ $((${STATUS} & 0x00008)) -ne 0 ]; then
      echo "Currently at Soft Temperature Limit"
    elif [ $((${STATUS} & 0x80000)) -ne 0 ]; then
      echo "Previously at Soft Temperature Limit"
    fi
    echo ""
  fi
}

joytest() {
  local arg=${1:-8}
  local del=${2:-1}
  while true; do clear && evdev-joystick --s "/dev/input/event$arg"; sleep "$del"; done
}

joy2key() {
  if [[ ${#} -gt 0 ]]; then
    local arg=$(echo "${1}" | tr '[:lower:]' '[:upper:]')
    bash /home/pi/ADMIN/CMD/joy2key/joy2key.sh "$arg"
  else
    echo -e "\nPlease provide argument!\n[ start | stop ]\n"
  fi
}

vkdump() {
  if [[ ! ${1} == help ]]; then
    event=$(while read -r line; do
      [ "$(echo $line | grep -c Virtual)" -gt 0 ] \
      && echo "$line" | grep "Virtual Keyboard" | cut -d: -f1
    done< <(sudo timeout 1 evtest 2>&1))

    while true; do
      clear
      echo -e "Virtual Keyboard: $event\n"
      echo -e " Type your octal code now.\n i.e. \x27\\\033\x27 without apostrophes.\n"
      echo -n " > "

      read -r str

      timeout 2 evtest "$event" | grep -A100 --line-buffered Testing &

      printf "$str" > /tmp/vkbdd.fifo
      sleep 1
      printf "\n"
      echo -e "\nPress ENTER to continue."
      read -sr dummy
    done
  else
    clear
    printf "\n OCTAL CODES:\n\n \
    '\\\015' : ENTER \n \
    '\\\040' : SPACE \n \
    '\\\033' : ESC \n \
    '\\\210' : BACKSPACE \n \
    '\\\212' : F1 \n \
    '\\\216' : F5 \n \
    '\\\010' : R_ALT \n\n"
  fi
}

dump_coin() {
  sudo bash /home/pi/CAFCA/cmd/DUMP.sh "$@"
}

txtf() {
  local file=
  local arg=

  declare -A txtfiles=( \
    [asoundrc]='/home/pi/.asoundrc' \
    [autostart]='/opt/retropie/configs/all/autostart.sh' \
    [backup]='/home/pi/ADMIN/CMD/BACKUP/backup.sh' \
    [boot]='/boot/boot.sh' \
    [bootlog]='/boot/boot.log' \
    [cafca]='/home/pi/CAFCA/CAFCA.sh' \
    [cafca_log]='/home/pi/CAFCA/log/CAFCA.log' \
    [cafca_states]='/home/pi/CAFCA/data/.states' \
    [cafca_settings]='/home/pi/CAFCA/data/.settings' \
    [cmdline]='/boot/cmdline.txt' \
    [config]='/boot/config.txt' \
    [emulationstation]='/opt/retropie/supplementary/emulationstation/emulationstation.sh' \
    [es_log]='/home/pi/ADMIN/.log/es.log'
    [es-end]='/home/pi/ADMIN/CMD/ES/es-onend.sh' \
    [es-start]='/home/pi/ADMIN/CMD/ES/es-onstart.sh' \
    [es_settings]='/home/pi/.emulationstation/es_settings.cfg' \
    [es_systems]='/home/pi/.emulationstation/es_systems.cfg' \
    [serial]='/home/pi/ADMIN/CMD/SERIAL/SERIAL.sh' \
    [serial_log]='/home/pi/ADMIN/.log/serial.log' \
    [pyserial]='/home/pi/ADMIN/CMD/PYTHON/SERIAL/serial_daemon.py' \
    [pyserial_log]='/home/pi/ADMIN/.log/serialpy.log' \
    [runcmd-start]='/opt/retropie/configs/all/runcommand-onstart.sh' \
    [runcmd-end]='/opt/retropie/configs/all/runcommand-onend.sh' \
    [settings]='/home/pi/ADMIN/.sys/.settings' \
    [sleep]='/home/pi/ADMIN/CMD/SLEEP/SLEEP.sh' \
    [states]='/home/pi/ADMIN/.sys/.states' \
    [thd_coin]='/home/pi/ADMIN/CMD/THD/TEENSY_COIN.sh' \
    [thd_conf]='/etc/triggerhappy/triggers.d/teensy.conf' \
    [thd_rst]='/home/pi/ADMIN/CMD/THD/TEENSY_RST.sh' \
  )

  if [ "${#}" -lt 1 ]; then
    clear
    for i in "${!txtfiles[@]}"; do
      echo -e "\x27$i\x27: ${txtfiles[$i]}"
    done
    sleep 1
    echo " "
    for i in "${!txtfiles[@]}"; do
      [ ! -f "${txtfiles[$i]}" ] && echo "${txtfiles[$i]} not found!"
    done
  else
    clear

    if [ "${#}" -gt 1 ]; then
      arg="${1}"
      file="${2}"
      echo -e " Press any key to run\n ${txtfiles[$file]}"
      read -srN1
      clear
      [[ $arg == run ]] && sudo bash "${txtfiles[$file]}"
    else
      file="${1}"
      echo -e " Press any key to edit\n ${txtfiles[$file]}"
      read -srN1
      sudo nano "${txtfiles[$file]}"
    fi
  fi
}

compare() {
  [ "${#}" -lt 2 ] && return

  local file1=${1}
  local file2=${2}
  local arg_str=${*}
  local new_str=

  file1_str=$(echo "$file1" | sed 's|/home/pi|~|')
  file2_str=$(echo "$file2" | sed 's|/home/pi|~|')

  new_str=$(echo "$file1_str $file2_str" | sed 's|/home/pi|~|g')

  if [[ ${#new_str} < $(tput cols) ]]; then
    new_str="$new_str"
  else
    file1_str=$(echo "$file1" | sed 's/[^/]*\//..\//g; s/[^/]\+//')
    file2_str=$(echo "$file2" | sed 's/[^/]*\//..\//g; s/[^/]\+//')
    new_str=$(echo "$file1_str $file2_str" | sed 's|/home/pi|~|g')
  fi

  clear
  echo ""
  echo -e "\n$new_str\n"

  local width=$(tput cols)
  diff -sy --width=55 "$file1" "$file2"

}

pkgdump() {
  [ "${#}" -lt 1 ] && return

  if [[ ${1} == "--installed" ]] \
  || [[ ${1} == "-installed" ]] \
  || [[ ${1} == "installed" ]] \
  || [[ ${1} == "--i" ]] \
  || [[ ${1} == "-i" ]] \
  || [[ ${1} == "i" ]]; then
    sudo apt list --installed \
    | awk '{$1=$1;print" "$0}' \
    | cut -d[ -f1 | cut -c -56 \
    | sudo tee /home/pi/ADMIN/.log/apt.list 2>&1
    sleep 2
    echo -e "\n SUCCES writing list to \x27/home/pi/ADMIN/.log/apt.list\x27\n"
  fi
}


curs() {
  local arg=${1}
  arg=$(echo "$arg" | sed -e "s/ \+//g")

  [[ "${arg:0:2}" == "--" ]] && arg="${arg:2}"
  [[ "${arg:0:1}" == "-" ]] && arg="${arg:1}"

  arg=$(echo "$arg" | tr '[:upper:]' '[:lower:]')

  case $arg in
   '1'|'on'|'true'|'yes'|'enabled')
     setterm --cursor on
     ;;
   '0'|'off'|'false'|'no'|'disabled')
     setterm --cursor off
     ;;
  esac
}


lsusr() {
  local stdoutput=$(sudo w)

  clear
  echo "$stdoutput" | awk '{$1=$1;print}' | \
  awk '{
   if(NR==1){
     split($0,users,",");
     print "\n"users[2]":\n"
   }else if(NR>2) {
     print " "$2"\t"$3
   }
  }'
}

backup() {
  local backup_dir='/home/pi/ADMIN/.backup'
  local script_dir='/home/pi/ADMIN/CMD/BACKUP'

  if [[ "${#}" < 1 ]]; then
    clear
    sudo bash "$script_dir/backup.sh"

  elif [[ "${1}" == list ]]; then
    sudo 7z l "$backup_dir/BACKUP.zip" | awk '{print $6}' | tail -n +16
  fi
}

pids() {
  if [[ $1 == -v ]]; then
    ps -ef | grep -v grep | grep -i "${@:2}"
  elif [[ $1 == kill ]]; then
    while read -r line; do echo "killing pid $line"; sudo kill -9 "$line"; done< <(ps -ef | grep -v grep | grep -i "${@:2}" | awk '{print $2}')
  else
    ps -ef | grep -v grep | grep -i "${@}" | awk '{print $2}'
  fi
}


kill() {
 arg=${@}
 sudo kill -9 "$arg"
}


CRT() {
 local arg=${1:-'CONF'}
 arg=$(echo $arg | tr '[:lower:]' '[:upper:]')
 [ "$#" -lt 1 ] && return || echo "$arg"

 if [[ $arg == CONF ]]; then
   python3 "/opt/retropie/configs/all/CRT/config/Configuration Utility.py"

 elif [[ $arg == UTILITY ]]; then
   sudo nano /opt/retropie/configs/all/CRT/bin/ScreenUtilityFiles/config_files/utility.cfg

 elif [[ $arg == BGM ]]; then
   sudo nano /opt/retropie/configs/all/CRT/bin/ScreenUtilityFiles/bin/service_bgm/bgm.py

 fi
}

send() {
  [ ${#} -lt 1 ] && return
  /usr/bin/printf "$*" > /tmp/vkbdd.fifo
}

serial() {
  echo -e "$@" > /tmp/serial.fifo
  #[ -c /dev/ttyACM0 ] && printf "$@" > /tmp/serial.fifo
}

#pyserial() {
#  [ -c /dev/ttyACM0 ] && printf "$@" > /tmp/pyserial.fifo
#}

server() {
  sudo sshpass -p $(echo YTJKY3V6S05hNjdOV1U5NlZKeGEK | base64 -d) sftp dogenigt@data.dogenigt.dk
}

upload() {
  expect /home/pi/ADMIN/CMD/FTP/sftp-upload.exp "$@"
}

exists() {
  [ -f "$@" ] && echo -e "\nfile \x27$@\x27 exists!\n" || echo -e "\nfile doesn't exist.\n"
}

play() {
  SDL_AUDIODRIVER='alsa' AUDIODEV='hw:1,0'
  ffplay -nodisp -autoexit -loglevel quiet "$@"
}

mod() {
  local path=
  [[ ${1} == ADMIN ]] && sudo chmod -R 775 /home/pi/ADMIN
}

tab() {
  local first=${1}
  local args="${*}"

  stdout="$(eval $args)"
  echo "$stdout" | awk '{print "  "$0}'
}


img() {
  tty=$(tty)

  if [[ $tty == /dev/tty* ]]; then
    sudo fbi -t 0 --once --noverbose "$@"
  elif [[ $tty == /dev/pts* ]]; then
    sudo fbi -T 1 -d /dev/fb0 --once --noverbose "$@"
  fi
  reset
}


press() {
  [ $# -lt 1 ] && return
  local key=${1}
  key=$(echo $key | tr '[:upper:]' '[:lower:]')

  case $key in
    [aA-zZ])
      /usr/bin/printf $key > /tmp/vkbdd.fifo
      ;;
    [0-9])
      /usr/bin/printf $key > /tmp/vkbdd.fifo
      ;;
    'esc')
      /usr/bin/printf '\033' > /tmp/vkbdd.fifo
      ;;
    'f4')
      /usr/bin/printf '\215' > /tmp/vkbdd.fifo
      ;;
    *)
      ;;
  esac
}


clocks() {
  printf "\nCLOCKS:\n\n"
  for src in arm core gpu emmc uart v3d h264 isp pwm vec pixel dpi hdmi; do
    echo -e "$src: $(vcgencmd measure_clock $src)" | \
    awk -v OFS=\n -F':|=' '{
      name = $1;
      val = $3;
      val /= 1000;
      unit=" hz"

      unit=(val >= 10000 ? "Mhz" : (val >= 100 ? "Khz" : " hz" ))
      val >= 10000 ? val /= 1000 : val=val;

      cmd = "echo \"" val "\" | sed \x27s/./&./4\x27";
      cmd | getline val_form;
      close(cmd);

      printf "%s\t%8.2f %s\n", name, val_form, unit

    }'
  done
  printf "\n\n"
}

psef() {
  [ $# ] && arg="$1"
  clear
  case $arg in
    [rR])
      _psf | cut -c -56 | tail -n 999 | tac | head -n -2 | less -EKRX
      ;;
    [sS])
      _psf | awk '{$2=$3="";print first" "$0}' | sed 's/ \+/ /g' | awk '{first=$1;$1="";printf "%4d%s\n",first,$0}' | tail -n +4 | cut -c -56 | less -EKRX
      ;;
    *)
      _psf | cut -c -56 | less -EKRX
      ;;
  esac
}


_psf() {
  printf "\n" && ps -ef | \
  awk '{$1=$1;print}' | \
  awk -F' ' '{
    $3=$4=$6=$7="";
    rest=$0;
    print rest;
  }' | sed -e "s/ \+/ /g" | \
  awk '{
    if (NR == 1){
      print "    "$2"  "$1" "$3" "$4"\n";
    }
    if (NR > 1){
      user=substr($1,0,5);
      printf " %6d %4s", $2, user;
      $1=$2=" ";
      print " "substr($0,5,length($0));
    }
  }'
}


installer() {
  [ ! $# ] && return
  args="${@}"
  arg="$1"
  file="$2"
  logfile="/home/pi/ADMIN/.log/installer.log"
  arc_name='/home/pi/ADMIN/.install/install.zip'
  [ -f $arc_name ] && sudo cp $arc_name "$arc_name.bak"

  echo "args: $args"
  echo "arg: $arg"
  echo "file: $file"

  if [[ $arg == "add" ]]; then
    ( sudo 7z a -r -tzip -p1234 "$arc_name" "$file" && sudo 7z l "$arc_name" 2>&1 )> >(sudo tee $logfile)
  elif [[ $arg == del ]]; then
    ( sudo 7z d -r -p1234 "$arc_name" "$file" && sudo 7z l "$arc_name" 2>&1 )> >(sudo tee $logfile)
  elif [[ $arg == list ]]; then
    sudo 7z l "$arc_name"
  fi
  echo -e "\nDONE!\n\nOutput logged in \x27$logfile\x27"
}

download() {
  local url=${1}
  local dir=${2:-'/home/pi/downloads'}

  valid=$(wget --method=HEAD --no-check-certificate $url 2>&1 | cut -d' ' -f 3 | grep -xcm1 exists.) &>/dev/null

  clear
  echo -e "\nRequesting $url\n"
  sleep 1
  echo -e "\n$(date):\n" | sudo tee ~/ADMIN/log/download.log &>/dev/null
  if ! (( valid )); then
    echo -e "URL Invalid.\n" && return
  else
    echo -n "URL valid." && sleep 1 && echo -e "..downloading to:"
    wget -v --no-check-certificate -P $dir $url 2>&1 \
    | grep --line-buffered -A100 "Length:" \
    | awk '{$1=$1;print}' | cut -d'(' -f1 \
    | awk -vDIR="$dir" -F'\\% ' '{
      if (NR == 2) {
        n=split($0,A,"/");
        lastf = substr(A[n],0,length(A[n])-2);
        delimiter = "\\=";
        print DIR"/"lastf
      } else {
        n=split($2, parts, delimiter);

        if (n >= 2 ) {
          split($0,fields);
          split(fields[1],first,".");
          split(fields[2],second,"\\=");

          print "\nDONE! ("first[1]"in "second[2]")\n"
        }
      } \
    }' 
  fi
}


alias-func() {
  [ $# -gt 0 ] && arg=${1}

  aliasfile='/home/pi/.bash_aliases'
  funcs=$(cat $aliasfile | grep -c "() {")

  declare -a rownums=()
  declare -a names=()
  declare -A entries=()

  empty_row="                                                        "
  tty_height=$(( $(tput lines) - 8 ))
  found_long_lines=0

  clear

  for ((i=1;i<=$funcs;i++)); do
    last_i=$((i - 1))
    grepstr=$(cat $aliasfile | grep -m"$i" "() {" | tail -n -1)

    name=$(echo "$grepstr" | cut -d'(' -f1)
    names["$i"]="$name"

    rownum=$(cat $aliasfile | grep -w -n -m1 "$grepstr" | cut -d: -f1)
    rownums["$i"]="$rownum"

    if [ "$i" -gt 1 ]; then
      lastrow="${rownums[$last_i]}"
      rownums["$last_i"]="$lastrow $rownum"

      skip=0

      [[ $( echo "${names[$last_i]}" | cut -c -1 ) == "_" ]] && skip=1
      [[ $( echo "${names[$last_i]}" | rev | cut -c -1 ) == '$' ]] && skip=1

      [[ $skip == 0 ]] && entries["${names[$last_i]}"]="${rownums[$last_i]}"

    fi
  done

   while true; do

     [ "${#entries[@]}" -gt 24 ] \
     && _list_entries | less -EKR \
     || _list_entries

     tput sc

     if [ ${#arg} -gt 0 ]; then
       entry="$arg"
       arg=
     else
       read -rp "  type entry: " entry
     fi

     if [[ -v entries[$entry] ]]; then
       sleep 0.5
       range="${entries[$entry]}"
       start=$(echo "$range" | cut -d' ' -f1)
       end=$(  echo "$range" | cut -d' ' -f2)

       page=$(cat $aliasfile | \
        awk -v page_start="$start" -v page_end="$end" '{
         if (NR >= page_start && NR < page_end) {
          if (NR == page_start || NR > (page_end)-3) {
            print "  \033[36m"$0"\033[0m"
          }else{
            if (length($0 > 56)) {
              print substr($0, 1, 56);
            } else {
              print "  "$0;
            }
          }
         }
        }')

       clear
       page_len=$(echo "$page" | wc -l)

       if [ "$page_len" -gt "$tty_height" ]; then
         echo "$page" | awk '{print $0}' | less -ERKX
       else
         echo "$page" | awk '{print $0}'
       fi

       long_lines=$(echo "$page" | grep -c ".\{55\}")

       if [ "$long_lines" -gt 0 ]; then
         found_long_lines=1
       fi

     else
       echo -e "\n  entry doesn't exist."
     fi

     echo -e "\n  press any key to return."
     read -srN1 dummy

     if [ "$found_long_lines" -gt 0 ]; then
       echo "$page" | decolor | sudo tee /tmp/alias-func
       clear
       echo -e "\nfound $long_lines long lines\n - read with nano? (Y/n)"

       read -srN1 read_choice
       case $read_choice in
         [yY])
           sudo nano /tmp/alias-func
           clear && sleep 1
           ;;
         *)
           ;;
       esac
     fi

     for ((r=17;r< "$(($(tput lines) - 2))";r++)); do
       tput cup $r 0
       echo "$empty_row"
     done
     tput rc
   done
}

_list_entries() {
   clear
   sleep 1
   echo -e "\n  ~/.bash_aliases functions:"
   echo -e "  ____________________________________________________\n"

   for i in "${!entries[@]}"; do
     val1=$(echo "${entries[$i]}" | cut -d' ' -f1)
     val2=$(echo "${entries[$i]}" | cut -d' ' -f2)
     printf "  %9s\t%4d %4d\n" "$i" "$val1" "$val2"
   done
   echo -e "\npress any key."
   read -srN1 dummy
}

unalias ll

ll() {
  arg=${1:-$PWD}

  [ ! -d $arg ] && arg="$PWD" 
  [ $(ls -l $arg | wc -l) -lt 2 ] && ls -l $arg && return

  clear
  _ll_list "$arg" | less -EKXR

}
_ll_list() {
  local folder="$1"
  local abs_path="$(realpath "$folder")"
  echo -e "$abs_path:\n"
  count=$(ls -l | awk 'NR==1 {print $0"\n"}')

  ls -la --group-directories-first $folder \
  | awk -vdir="$folder" '{

    RESET="\033[0m";RED="\033[31m";RED="\033[31m";CYAN="\033[36m";WHITE="\033[37m";
    BGCOLOR="\033[40m\033[37m";DIRCOLOR="\033[40m\033[36m";ROWCOLOR=WHITE;

    fname=$9;
    sub(".\\/","",fname);
    hidden=substr(fname,0,2);

    user=$3
    user == "root" ? user="su" : user=user;

    type=substr($1,0,2);

    if (type == "l") next;
    type=(type == "d" ? "D" : (hidden == "." ? hidden : type));
    type == "D" ? fname=fname "/" : fname=fname

    if (NF>9){
      for (i=9+1;i<=NF;i++){ fname = fname" "$i }
      fname = "\x27" fname "\x27";
    } else { fname=$9 }

    cmd = "stat -c \x27%a %n\x27 "dir"/"fname;
    cmd | getline statout
    close(cmd);

    split(statout,octal);
    rights=octal[1];

    size=$5;
    if (size >= 1024 * 1024) {
      size /= (1024 * 1024);
      unit="M"
    } else if (size >= 1024) {
      size /= 1024;
      unit="K"
    } else { unit="B" }

    date_str = $6" "$7" "$8;
    cmd = "date -d \"" date_str "\" +%m-%d\ %R";
    cmd | getline date_formatted;
    close(cmd);
    cmd = "date -d \"" time_str "\" +%R";
    cmd | getline time_formatted;
    close(cmd);

    if (NR > 3) {
      type == "D" ? ROWCOLOR=DIRCOLOR : ROWCOLOR=BGCOLOR
      printf "%s %s %s %s %3.0f%s %s %s\n", ROWCOLOR, type, rights, date_formatted, size, unit, fname, RESET
    }
  }'
  echo -e "\n $(find $folder -maxdepth 1 -type f | wc -l) files. - $(find $folder -maxdepth 1 -type d | wc -l) dir(s)\n"
}
