#!/usr/bin/env bash

# Colors
RESET="\e[0m"
GREEN="\e[32m"
RED="\e[91m"

function help()
{
    echo "Help:"
    echo "-----"
    echo ""
    echo "lch [-h] [-v] [-c] [-i] [FILE [FILE...]]"
    echo ""
    echo "Examples:"
    echo "$ lch -h                       - This help"
    echo "$ lch -v                       - Print version"
    echo "$ lch -c                       - Check compression systems"
    echo "$ lch -i                       - Install the compressors dependencies"
    echo "$ lch file.zip                 - Decompress"
    echo "$ lch file.zip /home/file      - Compress"
    echo "$ lch files.zip file1 file2    - Compress multiple"
    echo ""
    echo "Packing/unpacking supported extensions:"
    echo "  7z, bz2, gz, rar, tar, tar.bz2, tbz, tbz2, tb2, tar.gz, tgz, tar.xz, txz, zip"
    echo ""
    echo "Unpacking only supported extensions:"
    echo "  arj, cab, dmg, iso, lzh, lzma, rpm, squashfs, vdi, vhd, vmdk, win, xar, z"
    echo ""
    echo "Run 'man lch' for more info."
    echo ""
}

function check()
{
    local a=false
    echo -e "Verification of compression systems:\n"
    echo -e "Systems\t\t\tStatus"
    echo "----------------------------------"
    for i in "7z" "bzip2" "gzip" "rar" "tar" "unrar" "unzip" "zip"
    do
        wheel true &
        WPID=$!
        if ! [ -x "$(command -v $i)" ]
        then
            echo -e "$i$RED\t\t\tNot Installed$RESET"
            a=true
        else
            echo -e "$i$GREEN\t\t\tInstalled$RESET"
        fi
        disown $WPID
        kill $WPID &> /dev/null
    done

    if $a
    then
        echo -e "\nIn order to use all the extensions install the packages."
        echo -e "Or use 'lch -i' to install all dependences"
    fi
    echo ""
}

function lowercase()
{
    echo "$DEST" | tr 'A-Z' 'a-z'
}

function error_not_install()
{
    echo -e "$@$RED is not installed$RESET, use 'lch -c' to check and 'lch -i' to install."
    exit 0
}

function executer()
{
    wheel true &
    WPID=$!
    if [ -x "$(command -v $1)" ]
    then
        "$@" 1> /dev/null
    else
        error_not_install $1
    fi
    disown $WPID
    kill $WPID &> /dev/null
}

function complete_install(){
    echo -e "$@:$GREEN\t\t\tCompleted$RESET"
}

function failed_install(){
    echo -e "$@:$RED\t\t\tFailed$RESET"
}

function wheel() {
    sp='/-\|'
    while $1; do
        printf '%.1s\b' "$sp"
        sp=${sp#?}${sp%???}
        if [ -x "$(command -v bc)" ]
        then
          sleep $(echo "0.0001*$(grep 'cpu MHz' /proc/cpuinfo | head -n1 | awk '{print $4}')" | bc -l)s
        else
          sleep 0.2s
        fi
    done
}