#!/bin/bash
set -e
version=1.1
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 9)"
print_centered " _ _ _     _       _   ____          "
print_centered "| | | |___| |_ ___| |_|    \ ___ ___ "
print_centered "| | | | .'|  _|  _|   |  |  | . | . |"
print_centered "|_____|__,|_| |___|_|_|____/|___|_  |"
print_centered "                                |___|"
echo -n "$(tput sgr0)"
print_centered "Watchdog hardware v$version"

if  [ -f /tmp/watchdog.1 ];then rm /tmp/watchdog.1;fi
cat <<'EOF'>> /tmp/watchdog.1
#Watchdog
SUBSYSTEM=="tty", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7523", SYMLINK+="watchdog" , RUN="/usr/local/bin/wd_control.sh"
EOF
if  [ -f /tmp/watchdog.2 ];then rm /tmp/watchdog.2;fi
cat <<'EOF'>> /tmp/watchdog.2
#!/bin/bash
timing=18
stty -F /dev/watchdog ispeed 9600 ospeed 9600 -ignpar cs8 -cstopb -echo
echo -n -e "\x$timing" >/dev/watchdog
EOF

chmod +x /tmp/watchdog.2
sudo mv /tmp/watchdog.2 /usr/local/bin/wd_control.sh
sudo mv /tmp/watchdog.1 /etc/udev/rules.d/10-watchdog.rules

if ! grep "wd_control.sh" /etc/crontab  >/dev/null
then
sudo cp /etc/crontab /tmp/crontab
sudo chmod 777 /tmp/crontab
echo "" >>/tmp/crontab
echo "* * * * * root /usr/local/bin/wd_control.sh" >> /tmp/crontab
sudo chmod 644 /tmp/crontab
sudo mv /tmp/crontab /etc/
fi

sudo /etc/init.d/cron restart >/dev/null
sleep 1
print_centered "Installation Done..."
print_centered ""