#!/bin/bash
set -e
Version=4.1
Cuda=YES
ZFS=YES
Drivers=82

if (( $EUID != 0 )); then
   echo -e "\nThis must be run as root. Try 'sudo bash $0'."
   exit 1
fi
clear

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
}

function intro {
print_centered "$(tput setaf 5)"
print_centered " ██████╗██╗   ██╗██████╗ ███████╗"
print_centered "██╔════╝██║   ██║██╔══██╗██╔════╝"
print_centered "██║     ██║   ██║██████╔╝█████╗  "
print_centered "██║     ██║   ██║██╔══██╗██╔══╝  "
print_centered "╚██████╗╚██████╔╝██████╔╝███████╗"
print_centered " ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝"
echo -n "$(tput setaf 7)"
print_centered "Cube Server installation script v$Version"
sleep 5
}

function update_ {
echo -e "$(tput setaf 10)\nUpdate and install packages:$(tput sgr0)"
sudo apt-get update
sudo apt-get install samba cifs-utils mdadm git build-essential libtool pkg-config automake autoconf ethtool net-tools openvpn filezilla -y
echo -e ""
sudo apt-get install tasksel lzma-dev lzma cmake libuv1-dev libssl-dev msr-tools tightvncserver lm-sensors openssh-server -y
echo -e ""
sudo apt-get install pixz pbzip2 pigz btrfs-progs htop lxde lxde-icon-theme gparted gnome-remote-desktop libcanberra-gtk-module -y
echo -e ""
sudo apt-get install ctorrent libcurl4-openssl-dev bison byacc screen libudev-dev libjansson-dev libncurses5-dev libmicrohttpd-dev curl -y
echo -e ""
sudo apt-get install htop vlc locate -y
if [ $ZFS = "YES" ]
then
sudo apt-get install zfsutils-linux -y
fi
if [ $Cuda = "YES" ]
then
echo -e "$(tput setaf 10)\nInstall Cuda packages:$(tput sgr0)"
sudo apt-get install nvidia-cuda-toolkit -y
echo -e "Done."
fi
}

function decompte {
echo -e "$(tput setaf 10)\nReboot in 10 seconds (CRTL+C to abord):$(tput sgr0)"
for i in {10..1}
do
echo -e -n "$i "
sleep 1
done
echo ""
sudo reboot
}

function nvidia_driver {
if [ ! -f /home/wareck/.pass1 ] && [ ! -f /home/wareck/.pass2 ]
then
echo -e "$(tput setaf 10)\nInstall NVIDIA GT710 Drivers:$(tput sgr0)"
echo -e "Pré-installation..."
echo -e "Relancer l'installation après le reboot !!!"
echo -e ""
sleep 5
fi
if ! [ -f /home/wareck/.pass1 ]
then
	if ! [ -f /etc/modprobe.d/blacklist-nvidia-nouveau.conf ]
	then
		sudo apt-get install build-essential libglvnd-dev -y
		sudo bash -c "echo blacklist nouveau > /etc/modprobe.d/blacklist-nvidia-nouveau.conf"
		sudo bash -c "echo options nouveau modeset=0 >> /etc/modprobe.d/blacklist-nvidia-nouveau.conf"
		sudo update-initramfs -u
		touch /home/wareck/.pass1
		decompte
	fi
	touch ~/.pass1
fi

if ! [ -f /home/wareck/.pass2 ]
then
echo -e "$(tput setaf 10)\nInstall NVIDIA Drivers:$(tput sgr0)"
echo -e "Pré-installation..."
echo -e "Relancer l'installation après le reboot !!!"
echo -e ""
sleep 3
echo -e "$(tput setaf 10)\nInstall NVIDIA GT710 Drivers 470.$Drivers :$(tput sgr0)"
case $Drivers in
74)
	if ! [ -f NVIDIA-Linux-x86_64-470.74.run ]
	then
        	cd /home/wareck/
		echo -e "Download MegaDownload:"
        	git clone https://github.com/wareck/megadown.git
        	sudo cp /home/wareck/megadown/megadown /usr/local/bin/megadown
        	sudo rm -r /home/wareck/megadown
        	cd /home/wareck
		echo -e ""
        	echo -e "Download drivers:"
		megadown https://mega.nz/file/6phmnDwZ#u9HHRmt3AvP-CCqVmgx8q4a5IrO3_uK9HEu-4CLODtQ
        	chmod +X NVIDIA-Linux-x86_64-470.74.run
		sudo bash /home/wareck/NVIDIA-Linux-x86_64-470.74.run
		touch /home/wareck/.pass2
		decompte
	fi
;;
82)
	if ! [ -f NVIDIA-Linux-x86_64-470.82.00.run ]
	then
	        cd /home/wareck/
		echo -e "Download MegaDownload:"
	        git clone https://github.com/wareck/megadown.git
	        sudo cp /home/wareck/megadown/megadown /usr/local/bin/megadown
	        sudo rm -r /home/wareck/megadown
	        cd /home/wareck
                echo -e ""
                echo -e "Download drivers:"
	        megadown https://mega.nz/file/T8gSjQ5I#-Dx3XXMebc9cRu6VsgV4jkzWUcA-66Yxf025nN0TTf8
	        chmod +X NVIDIA-Linux-x86_64-470.82.00.run
	        sudo bash /home/wareck/NVIDIA-Linux-x86_64-470.82.00.run
	        touch /home/wareck/.pass2
	        decompte
	fi
;;
*)
echo -e "$(tput setaf 9)Error driver number ! $(tput sgr0)\n"
exit 0
;;
esac
fi
}

function download_packs {
echo -e "$(tput setaf 10)\nDownload complement packs:$(tput sgr0)"
wget -c -q --show-progress http://folivier.homelinux.org/cube/pack/cgminer.conf -O pack/cgminer.conf
wget -c -q --show-progress http://folivier.homelinux.org/cube/pack/chia-miner.tar.xz -O pack/chia-miner.tar.xz
wget -c -q --show-progress http://folivier.homelinux.org/cube/pack/gerbera.tar.xz -O pack/gerbera.tar.xz
wget -c -q --show-progress http://folivier.homelinux.org/cube/pack/start_cgminer.tar.xz -O pack/start_cgminer.tar.xz
wget -c -q --show-progress http://folivier.homelinux.org/cube/pack/webmin-1.984.tar.xz -O pack/webmin-1.984.tar.xz
wget -c -q --show-progress http://folivier.homelinux.org/cube/pack/xmrig.tar.xz -O pack/xmrig.tar.xz
wget -c -q --show-progress http://folivier.homelinux.org/cube/pack/zfsmanager-0.0.4.wbm.gz -O pack/zfsmanager-0.0.4.wbm.gz
echo -e ""
cp pack/pack1.tar.xz /home/wareck
cp pack/pack2.tar.xz /home/wareck
cp pack/xmrig.tar.xz /home/wareck
cp pack/start_cgminer.tar.xz /home/wareck
if  [ ! -d /home/wareck/webmin-1.984 ]
then
cp pack/webmin-1.984.tar.xz /home/wareck/
cd /home/wareck/
echo -e "$(tput setaf 10)\nWebmin uncompress:$(tput sgr0)"
tar xfJ webmin-1.984.tar.xz --checkpoint=.100
rm webmin-1.984.tar.xz
echo "Done."
echo -n -e "\n"
fi
echo -e "$(tput setaf 10)\nDownloading miners:$(tput sgr0)"
cd /home/wareck
if ! [ -d xmrig ]
then
git clone https://github.com/xmrig/xmrig.git
echo -e ""
fi
if ! [ -d xmr-stak ]
then
git clone https://github.com/fireice-uk/xmr-stak.git
echo -e ""
fi
if ! [ -d xmr-stak-rx ]
then
git clone https://github.com/fireice-uk/xmr-stak.git -b xmr-stak-rx xmr-stak-rx
echo -e ""
fi
if ! [ -d cgminer-gekko ]
then
git clone https://github.com/wareck/cgminer-gekko.git
fi
echo -e ""
}

function build_miners {
cd /home/wareck/
echo -e "$(tput setaf 10)Build Cgminer-gekko:$(tput sgr0)"
if ! [ -d cgminer-gekko ]
then
git clone https://github.com/wareck/cgminer-gekko.git
fi
cd cgminer-gekko
sudo usermod -a -G dialout,plugdev wareck
sudo cp 01-cgminer.rules /etc/udev/rules.d/
CFLAGS="-O2 -march=native" ./autogen.sh
./configure --enable-gekko
make -j4
tar xvfJ /home/wareck/start_cgminer.tar.xz
rm /home/wareck/start_cgminer.tar.xz
cd ..
cat <<'EOF'>> /tmp/cgminer
#!/bin/sh -e
### BEGIN INIT INFO
# Provides:          cgminer
# Required-Start:    networking
# Default-Start:     3 4 5
# Default-Stop:      0 6
### END INIT INFO
cd /home/wareck/cgminer-gekko/
su wareck -c "screen -dmS cgminer /home/wareck/cgminer-gekko/cgminer"
exit 0
EOF
chmod +x /tmp/cgminer
sudo cp /tmp/cgminer /etc/init.d/cgminer
sudo update-rc.d cgminer defaults
echo "Done."

echo -e "$(tput setaf 10)\nUncompress xmr files:$(tput sgr0)"
tar xfJ xmrig.tar.xz --checkpoint=.100
echo "Done."
echo -n -e "\n"
echo -e "$(tput setaf 10)\nBuild xmrig:$(tput sgr0)"
cd xmrig
git pull
sed -i "s/kDefaultDonateLevel = 5;/kDefaultDonateLevel = 0;/g" src/donate.h
sed -i "s/kMinimumDonateLevel = 1;/kMinimumDonateLevel = 0;/g" src/donate.h
wget -c https://download.open-mpi.org/release/hwloc/v2.5/hwloc-2.5.0.tar.bz2
tar xfj hwloc-2.5.0.tar.bz2 --checkpoint=.100
cd hwloc-2.5.0
./configure
make -j4
sudo make install
cd ..
sudo ldconfig
cd build
cmake ..
make -j4
cd ..
cd ..
echo "Done."
echo -e "$(tput setaf 10)\nBuild xmrig-upx:$(tput sgr0)"
cd xmrig-upx
git pull
sed -i "s/kDefaultDonateLevel = 5;/kDefaultDonateLevel = 0;/g" src/donate.h
sed -i "s/kMinimumDonateLevel = 1;/kMinimumDonateLevel = 0;/g" src/donate.h
cd build
cmake .. -DWITH_HTTPD=OFF
make -j4
cd ..
cd ..
echo "Done."
echo -e "$(tput setaf 10)\nBuild xmr-stak-rx:$(tput sgr0)"
cd xmr-stak-rx
git pull
cd build
cmake ..
make -j4
cd ..
cd ..
echo "Done."
echo -e "$(tput setaf 10)\nBuild xmr-stak:$(tput sgr0)"
cd xmr-stak
if ! [ -d build ];then mkdir build ;fi
git pull
cd build
cmake .. -DOpenCL_ENABLE=OFF -DCUDA_ENABLE=OFF
make -j4
cd ..
cd ..
echo "Done."
if [ $Cuda = "Yes" ]
then
echo -e "$(tput setaf 10)\nBuild xmrig-cuda:$(tput sgr0)"
sudo apt-get install git build-essential cmake libuv1-dev nvidia-cuda-dev nvidia-cuda-toolkit libmicrohttpd-dev gcc-8 g++-8
git clone https://github.com/xmrig/xmrig-nvidia.git
cd xmrig-nvidia
mkdir build
cd build
cmake .. -DCMAKE_C_COMPILER=$(which gcc-8) -DCMAKE_CXX_COMPILER=$(which g++-8)
make -j4
fi
}

function configure_ {
echo -e "$(tput setaf 10)\nConfig files:$(tput sgr0)"
cd /home/wareck/
su wareck -c 'gsettings set org.gnome.desktop.background picture-uri /home/wareck/Images/mr-robot-wallpapers.jpg'
su wareck -c 'gsettings set org.gnome.shell.extensions.dash-to-dock dash-max-icon-size 32'
#su wareck -c 'gsettings set org.gnome.shell.extensions.dash-to-dock show-mounts false'
sleep 0.5



sudo rm -r -f /etc/update-motd.d/*
tar xfJ pack1.tar.xz --checkpoint=.10
echo -n -e "\n"
sudo cp /home/wareck/pack2.tar.xz /
cd /
sudo tar xfJ pack2.tar.xz --checkpoint=.10
echo -n -e "\n"
cd /home/wareck
clear
dynmotd
echo "Done."

sudo sed -i -e "s/# set constantshow/set constantshow/g" /etc/nanorc

if ! grep "wareck" /etc/sudoers >/dev/null
then
sudo sh -c "echo \"wareck ALL=(ALL) NOPASSWD: ALL\" >> /etc/sudoers"
fi

echo -e "$(tput setaf 10)\nBuild folder and mount drives:$(tput sgr0)"
if ! [ -r /media/Raid ];then sudo mkdir /media/Raid && cd / & sudo ln -s /media/Raid /Raid ;fi
if ! [ -r /media/Store ];then sudo mkdir /media/Store && cd / & sudo ln -s /media/Store /Store;fi
if ! [ -r /media/Partage ];then sudo mkdir /media/Partage && cd / & sudo ln -s /media/Partage /Partage;fi
if ! [ -r /media/Nas ];then sudo mkdir /media/Nas && cd / & sudo ln -s /media/Nas /Nas;fi
if ! [ -r /media/Chia ];then sudo mkdir /media/Chia && cd / & sudo ln -s /media/Chia /Chia;fi
if ! [ -r /media/nvme ];then sudo mkdir /media/nvme && cd / & sudo ln -s /media/nvme /nvme ;fi


if ! grep "UUID=UUID=1df72b63-fca0-45c6-992c-3e2532d5591a /media/Store ext4" /etc/fstab >/dev/null
then
cp /etc/fstab /tmp/fstab
cat <<"EOF">> /tmp/fstab

#ext4
UUID=1df72b63-fca0-45c6-992c-3e2532d5591a /media/Store ext4
UUID=27821afb-02ed-4b13-8b61-5980787b4ad1 /media/Partage ext4
#btrfs
UUID=3c48d278-076c-4904-a280-4582c6bf8b24 /media/nvme btrfs ssd,nodatacow,discard=async,noatime
EOF
sudo cp /tmp/fstab /etc/fstab
fi
echo "Done."

if [ $ZFS = "YES" ]
then
sudo zpool import Raid
fi

sudo mount /media/Store
sudo mount /media/Partage
sudo chmod 777 /media/Store
sudo chmod 777 /media/Partage
sudo chmod 777 /media/nvme
sudo chmod 777 /media/Nas

echo -e "$(tput setaf 10)\nSensors drivers:$(tput sgr0)"
if ! grep "nct6775" /etc/modules >/dev/null
then
cp /etc/modules /tmp/modules
cat <<"EOF">> /tmp/modules

# Chip drivers
nct6775
EOF
sudo cp /tmp/modules /etc/modules
fi
echo "Done."

echo -e "$(tput setaf 10)\nVnc init:$(tput sgr0)"
sudo update-rc.d vncserver defaults
echo "Done."

echo -e "$(tput setaf 10)\nOpening ports:$(tput sgr0)"
sudo ufw allow 8333 >/dev/null
sudo ufw allow 22 >/dev/null
sudo ufw allow 5900 >/dev/null
sudo ufw allow 10000 >/dev/null
sudo ufw allow 139 >/dev/null
sudo ufw allow 5901 >/dev/null
sudo ufw allow 5902 >/dev/null
sudo ufw allow 445 >/dev/null
echo "Done."

echo -e "$(tput setaf 10)\nBashrc mod:$(tput sgr0)"
if ! grep "#mod for tightvncserver" /home/wareck/.bashrc
then
echo "#mod for tightvncserver" >>/home/wareck/.bashrc
echo "cd ~" >>/home/wareck/.bashrc
fi
echo "Done."

echo -e "$(tput setaf 10)\nDisable IPv6:$(tput sgr0)"
if ! grep "ipv6.disable=1" /etc/default/grub >/dev/null
then
sed -i -e "s/quiet splash/quiet splash ipv6.disable=1/g" /etc/default/grub
sed -i -e "s/GRUB_CMDLINE_LINUX=\"/GRUB_CMDLINE_LINUX=\"ipv6.disable=1/g" /etc/default/grub
sudo update-grub2
fi
sudo chown -R wareck:wareck /home/wareck/xmr*
sudo chown -R wareck:wareck /home/wareck/cgminer*


echo "Done."

}

function printer_ {
echo -e "$(tput setaf 10)\nPrinter Drivers$(tput sgr0)"
if [ ! -d /usr/local/share/foomatic/ ]
then
if [ ! -d /tmp/foomatic-db/ ]
then
cd /tmp/
git clone https://github.com/OpenPrinting/foomatic-db.git
fi
cd /tmp/foomatic-db
if [ ! -d /usr/local/share/foomatic/ ]
then
./make_configure
./configure
sudo make install
fi
echo "Done."
fi
}

function cleaning {
echo -e "$(tput setaf 10)\nCleaning:$(tput sgr0)"
if [ -f /pack2.tar.xz ]; then sudo rm /pack2.tar.xz ;fi
if [ -f /home/wareck/pack1.tar.xz ]; then rm /home/wareck/pack1.tar.xz ;fi
if [ -f /home/wareck/pack2.tar.xz ]; then rm /home/wareck/pack2.tar.xz ;fi
if [ -f /home/wareck/xmrig.tar.xz ]; then rm /home/wareck/xmrig.tar.xz ;fi
if [ -r /home/wareck/Music ]; then sudo rm -r -f /home/wareck/Music ;fi
if [ -r /home/wareck/Public ]; then sudo rm -r -f /home/wareck/Public ;fi
if [ -r /home/wareck/Templates ]; then sudo rm -r -f /home/wareck/Templates ;fi
if [ -r /home/wareck/Vidéos ]; then sudo rm -r -f /home/wareck/Vidéos ;fi
if [ -f /home/wareck/NVIDIA-Linux-x86_64-470.74.run ]; then rm /home/wareck/NVIDIA-Linux-x86_64-470.74.run ;fi
if [ -f /home/wareck/NVIDIA-Linux-x86_64-470.82.00.run ]; then rm /home/wareck/NVIDIA-Linux-x86_64-470.82.00.run ;fi
if [ -f /home/wareck/.pass1 ]; then rm /home/wareck/.pass1 ;fi
if [ -f /home/wareck/.pass2 ]; then rm /home/wareck/.pass2 ;fi
echo "Done."
}

#echo -e "$(tput setaf 10)\nFinalisation:$(tput sgr0)"
#echo "Tightvncserver password:"
#tightvncserver
#echo "Done."

intro
nvidia_driver
update_
download_packs
build_miners
printer_
configure_
cleaning

su wareck -c 'gsettings set org.gnome.shell.extensions.dash-to-dock dash-max-icon-size 32'
sleep 0.5
su wareck -c 'gsettings set org.gnome.desktop.background picture-uri /home/wareck/Images/mr-robot-wallpapers.jpg'
sleep 0.5
#su wareck -c 'gsettings set org.gnome.shell.extensions.dash-to-dock show-mounts false'
#sleep 0.5

echo -e "$(tput setaf 10)\nEnd of script:$(tput sgr0) \n"
echo -e "$(tput setaf 7)Need to install webmin manually (reboot required)$(tput sgr0)"
echo -e "$(tput setaf 7)Need to start tightvncserver manually $(tput sgr0)"
echo -e "$(tput setaf 7)after install webmin, reboot is required for raid drive$(tput sgr0)"
echo -e ""