#!/bin/bash
set -e
function print_centered {
     [[ $# == 0 ]] && return 1

     declare -i TERM_COLS="$(tput cols)"
     declare -i str_len="${#1}"
     [[ $str_len -ge $TERM_COLS ]] && {
          echo "$1";
          return 0;
     }

     declare -i filler_len="$(( (TERM_COLS - str_len) / 2 ))"
     [[ $# -ge 2 ]] && ch="${2:0:1}" || ch=" "
     filler=""
     for (( i = 0; i < filler_len; i++ )); do
          filler="${filler}${ch}"
     done

     printf "%s%s%s" "$filler" "$1" "$filler"
     [[ $(( (TERM_COLS - str_len) % 2 )) -ne 0 ]] && printf "%s" "${ch}"
     printf "\n"

     return 0
}

print_centered "$(tput setaf 10)"
print_centered " _____ _         ___                       "
print_centered "|   __| |___ _ _|  _|___ ___ _____ ___ ___ "
print_centered "|   __| | -_|_'_|  _| .'|  _|     | -_|  _|"
print_centered "|__|  |_|___|_,_|_| |__,|_| |_|_|_|___|_|  "
print_centered "                                           "
echo -n "$(tput setaf 7)"
print_centered "Flexpool mining software"

function build_service {
cat <<'EOF'>> /tmp/flexfarmer
#!/bin/sh -e
### BEGIN INIT INFO
# Provides:          flexfarmer
# Required-Start:    networking
# Default-Start:     3 4 5
# Default-Stop:      0 6
### END INIT INFO
case "$1" in
        start)
        cd /home/wareck/miners/flexfarmer/
        su wareck -c "screen -dmS flexfarmer /home/wareck/miners/flexfarmer/flexfarmer -c /home/wareck/miners/flexfarmer/config.yml"
        ;;
        stop)
        sudo killall -9 flexfarmer |true
        ;;
        *)
        echo "Usage: /etc/init.d/flexfarmer {start|stop}"
        exit 1
        ;;
esac
exit 0
EOF
chmod +x /tmp/flexfarmer
sudo cp /tmp/flexfarmer /etc/init.d/flexfarmer
sudo update-rc.d flexfarmer defaults
print_centered "Build Service     : [ OK ]"
rm /tmp/flexfarmer
}

function install_ {
wget -c -q http://folivier.homelinux.org/cube/pack/flexfarmer.tar.xz
tar xfJ flexfarmer.tar.xz
if [ -d /home/wareck/miners/flexfarmer ];then sudo rm -r -f /home/wareck/miners/flexfarmer ;fi
sudo cp -r -f flexfarmer /home/wareck/miners/
sudo rm -r -f flexfarmer flexfarmer.tar.xz
print_centered "Install software  : [ OK ]"
}

echo ""
install_
build_service
echo ""
