#!/bin/bash
set -e
Version=2.9

#if (( $EUID != 0 )); then
#   echo -e "$(tput setaf 11)This must be run as root. Try 'sudo $0'.$(tput sgr0)"
#   exit 1
#fi

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_ {
clear
print_centered "$(tput setaf 1)"
print_centered "██████╗ ██╗      █████╗ ██████╗ ███████╗"
print_centered "██╔══██╗██║     ██╔══██╗██╔══██╗██╔════╝"
print_centered "██████╔╝██║     ███████║██║  ██║█████╗  "
print_centered "██╔══██╗██║     ██╔══██║██║  ██║██╔══╝  "
print_centered "██████╔╝███████╗██║  ██║██████╔╝███████╗"
print_centered "╚═════╝ ╚══════╝╚═╝  ╚═╝╚═════╝ ╚══════╝"
print_centered "                                        "
echo -n "$(tput sgr0)$(tput setaf 7)"
print_centered "Server installation script v$Version"
print_centered "Special Dell R640"
echo -n "$(tput sgr0)"
echo -e "\n"
#print_centered "(ne pas activer le login automatique...)"
sleep 3
}


function update_ {
echo -e "$(tput setaf 10)\nLibraries update:$(tput sgr0)"
sudo dnf -y update
sudo dnf install -y epel-release
sudo dnf group install -y "Development Tools"
sudo dnf install -y cmake gmp-devel numactl-devel perl lynx perl-Encode-Detect perl-Time-Piece perl-open perl-encoding perl-Filter
sudo dnf install -y perl-Digest-SHA git htop python-devel gparted
sudo dnf install -y cmake3 libsodium libsodium-static git make cmake gcc gcc-c++ hwloc-devel openssl-devel automake libtool autoconf
sudo dnf install -y msr-tools-1.3-17.el9.x86_64
sudo dnf --enablerepo=crb install -y libstdc++-static
echo -e "\nDone"
}

function tigervnc_ {
echo -e "$(tput setaf 10)\nInstall TigerVnc:$(tput sgr0)"
if [ ! -f /opt/.alreadyvnc ]
then
wget -c http://folivier.homelinux.org/cube/pack/alma.tar.xz
sudo cp -r -f alma.tar.xz /
rm alma.tar.xz
cd /
sudo tar xvfJ alma.tar.xz
sudo rm alma.tar.xz
sudo dnf groupinstall -y "Server with GUI"
sudo systemctl set-default graphical.target
sudo systemctl default
sudo dnf config-manager --set-enabled crb
sudo dnf install -y epel-release
sudo dnf update -y
sudo dnf install -y tigervnc-server
sudo chmod 777 /home/wareck/.vnc
sudo cp /lib/systemd/system/vncserver@.service /etc/systemd/system/vncserver@:1.service
sudo systemctl daemon-reload
sudo systemctl start vncserver@:1
sudo systemctl enable vncserver@:1
sudo touch /opt/.alreadyvnc
fi
sudo firewall-cmd --permanent --add-service=vnc-server
sudo firewall-cmd --reload
sudo firewall-cmd --add-port=5901/tcp --permanent
sudo firewall-cmd --reload
echo -e "\nDone"
}

function chia_ {
echo -e "$(tput setaf 10)\nInstall Chia:$(tput sgr0)"
cd /home/wareck/Build_Cube/other_arch/
cp /home/wareck/Build_Cube/options/chia.sh .
sed -i "s/Gui=Yes/Gui=No/g" chia.sh
sed -i "s/ChiaPos=Yes/ChiaPos=No/g" chia.sh
sed -i "s/Miner=Yes/Miner=No/g" chia.sh
sed -i "s/ChiaService=Yes/ChiaService=No/g" chia.sh
sed -i "s/Miner=Yes/Miner=No/g" chia.sh
sed -i "s/ChiaProxy=Yes/ChiaProxy=No/g" chia.sh
sed -i "s/Toolkit for Chia v$Version/Toolkit for Chia AlmaLinux /g" chia.sh
sed -i "s/sudo apt-get install/#sudo apt-get install/g" chia.sh
sed -i "s/-j 6/-j 32/g" chia.sh
sh chia.sh
rm chia.sh
#cp /home/wareck/Build_Cube/options/flexfarmer.sh .
#sed -i "s/Flexpool mining software/Flexpool mining software AlmaLinux/g" flexfarmer.sh
#sed -i "s/build_service/#build_service/g" flexfarmer.sh
#sed -i "s/function #build_service/function build_service/g" flexfarmer.sh
#./flexfarmer.sh
#rm flexfarmer.sh
echo -e "\nDone"
}

function miner_ {
echo -e "$(tput setaf 10)\nInstall Miners:$(tput sgr0)"
cp /home/wareck/Build_Cube/pack/xmrig.tar.xz /home/wareck/
cd /home/wareck
if ! [ -d miners ]; then mkdir -p miners;fi
cd miners
if ! [ -d xmrig ]
then
git clone https://github.com/xmrig/xmrig.git
echo -e ""
fi
echo -e "$(tput setaf 10)\nUncompress xmr files:$(tput sgr0)"
tar xfJ /home/wareck/xmrig.tar.xz --checkpoint=.100
rm /home/wareck/xmrig.tar.xz
echo "Done."
echo -n -e "\n"
echo -e "$(tput setaf 10)\nBuild xmrig:$(tput sgr0)"
cd xmrig
sed -i "s/kDefaultDonateLevel = 5;/kDefaultDonateLevel = 0;/g" src/donate.h
sed -i "s/kMinimumDonateLevel = 1;/kMinimumDonateLevel = 0;/g" src/donate.h
cd scripts
./build_deps.sh
cd ..
cd build
#rm -r Cm*
cmake .. -DXMRIG_DEPS=scripts/deps
make -j$((`nproc`+1))
cd /home/wareck/miners
wget -c http://folivier.homelinux.org/alma/miners_alma.tar.xz
tar xvfJ miners_alma.tar.xz
sudo rm -r -f miners_alma.tar.xz
sudo rm -r -f xmr-stak-rx
sudo rm -r -f xmrig-upx
#sudo dnf install -y msr-tools-1.3-17.el9.x86_64
echo -e "\nDone."
}

function webmin_ {
echo -e "$(tput setaf 10)\nInstall Webmin:$(tput sgr0)"
cd /tmp/
curl -o setup-repos.sh https://raw.githubusercontent.com/webmin/webmin/master/setup-repos.sh
chmod +x setup-repos.sh
sudo ./setup-repos.sh
sudo dnf install -y webmin
}

function lvm2_ {
echo -e "$(tput setaf 10)\nInstall Lvm2:$(tput sgr0)"
sudo dnf install libaio-devel -y
cd /home/wareck
git clone https://github.com/lvmteam/lvm2.git
cd /home/wareck/lvm2
./configure
sleep 5
make -j$((`nproc`))
sudo make install
sudo ldconfig
echo -e "Done"
}

function wol_ {
echo -e "$(tput setaf 10)\nWake on lan modification:$(tput sgr0)"
iface=$(ip link | awk -F: '$0 !~ "lo|vir|^[^0-9]"{print $2a;getline}')
ether=$(which ethtool)
echo "[Unit]" >>/tmp/wol.service
echo "Description=Enable Wake On Lan" >>/tmp/wol.service
echo "" >>/tmp/wol.service
echo "[Service]" >>/tmp/wol.service
echo "Type=oneshot" >>/tmp/wol.service
echo "ExecStart = $ether --change eno1 wol g" >>/tmp/wol.service
echo "ExecStart = $ether --change eno2 wol g" >>/tmp/wol.service
echo "ExecStart = $ether --change eno3 wol g" >>/tmp/wol.service
echo "ExecStart = $ether --change eno4 wol g" >>/tmp/wol.service
echo "" >>/tmp/wol.service
echo "[Install]" >>/tmp/wol.service
echo "WantedBy=basic.target" >>/tmp/wol.service
sudo cp /tmp/wol.service /etc/systemd/system/wol.service
sudo systemctl daemon-reload
sudo systemctl enable wol.service
sudo systemctl start wol.service
echo -e "\nDone"
}

function drive_ {
echo -e "$(tput setaf 10)\nBuild folder and mount drives:$(tput sgr0)"
if ! [ -r /ramdisk/ ];then sudo mkdir /ramdisk/ ;fi
if ! grep "tmpfs /ramdisk tmpfs defaults,size=110G 0 0" /etc/fstab >/dev/null
then
cp /etc/fstab /tmp/fstab
cat <<'EOF'>> /tmp/fstab
tmpfs /ramdisk tmpfs defaults,size=110G 0 0
UUID=bb011630-398c-4025-bfb6-0fcfbc7c6b7f /raid xfs nofail,defaults,noatime,nodiratime    0    0
UUID=3fb4be86-702c-4af9-9706-da9ac33f6236 /store xfs nofail,defaults,noatime,nodiratime    0    0
EOF
sudo cp /tmp/fstab /etc/fstab
fi
if [ ! -r /raid/ ];then sudo mkdir /raid/;fi
if [ ! -r /store/ ];then sudo mkdir /store/;fi
#sudo mount /raid
#sudo mount /store
#sudo chmod 777 /raid
#sudo chmod 777 /store
echo -e "Done"
}

function crontab_ {
echo -e "$(tput setaf 10)\nInstall crontab:$(tput sgr0)"
if ! sudo grep "uploader_chia.sh" /etc/crontab >/dev/null
then
cp /etc/crontab /tmp/
sudo sh -c "echo '*/15 * * * * wareck /usr/local/bin/uploader_chia.sh'" >>/tmp/crontab
sudo sh -c "echo '@reboot wareck /usr/local/bin/boot_up.sh'" >> /tmp/crontab
sudo cp /tmp/crontab /etc/crontab
fi
if ! [ -f /usr/local/bin/uploader_chia.sh ]
then
wget -c -q http://folivier.homelinux.org/alma/uploader_chia.sh -O /tmp/uploader_chia.sh
sudo cp /tmp/uploader_chia.sh /usr/local/bin/uploader_chia.sh
sudo chmod +x /usr/local/bin/uploader_chia.sh
fi
if ! [ -f /usr/local/bin/boot_up.sh ]
then
wget -c -q http://folivier.homelinux.org/alma/boot_up.sh -O /tmp/boot_up.sh
sudo cp /tmp/boot_up.sh /usr/local/bin/boot_up.sh
sudo chmod +x /usr/local/bin/boot_up.sh
fi
sudo service crond restart
echo "Done."
}

function config_ {
echo -e "$(tput setaf 10)\nTuning:$(tput sgr0)"
sudo sed -i -e "s/# set constantshow/set constantshow/g" /etc/nanorc
if ! sudo grep "wareck" /etc/sudoers >/dev/null
then
sudo sh -c "echo \"wareck ALL=(ALL) NOPASSWD: ALL\" >> /etc/sudoers"
fi
cat <<'EOF'>> /tmp/wakemeup.sh
#!/bin/bash
set -e
if ! [ -x "$(command -v ether-wake)" ];then sudo dnf install etherwake -y;fi
clear
echo -e "$(tput setaf 10)Wake On Lan v1.0:$(tput sgr0)"
PS3="Select : "
items=("Nzxt" "Garage")

select item in "${items[@]}" Quit
    do
      	case $REPLY in
            1) sudo ether-wake -i eno1 E0:D5:5E:2D:9E:CB ; break;;
            2) sudo ether-wake -i eno1 58:11:22:CD:FC:7A ; break;;
            $((${#items[@]}+1))) echo "We're done!"; break 2;;
            *) echo "Ooops - unknown choice $REPLY"; break;
        esac
    done
echo -e ""
EOF
sudo chmod +x /tmp/wakemeup.sh
sudo cp /tmp/wakemeup.sh /usr/local/bin
echo "Done."

git config --global core.editor "nano"
}

function bash_ {
echo -e "$(tput setaf 10)\nInstall script plotter:$(tput sgr0)"
cat <<'EOF'>> /home/wareck/chia/bladebit/build/h9.sh
#!/bin/bash
POOL=a99e72c49c5ed39bf793caab9e074a80dd61011a859e975842874aab47b783f9ce84282febe2ca275c0930149b67990a
FARM=8ba5acd276b45fd0f749ce195dcddcf0e63c3bf2e751e9e273faa0125075c36a11f2ee231e7cf74abed2920be97fc373
OUT=/store/
rm /raid/plotting/*
for i in {1..1}
do
echo "$(tput setaf 10)Build Plot N°$i$(tput sgr0)"
./bladebit -v -t 30 -p $POOL -f $FARM -z 7 diskplot --f1-threads 16 --c-threads 16 --p2-threads 8  --cache 110G -t1 /raid/plotting $OUT
done
#sudo init 0
EOF
chmod +x /home/wareck/chia/bladebit/build/h9.sh
cat <<'EOF'>> /home/wareck/chia/chia-gigahorse/cpu-plotter/linux/x86_64/go.sh
#!/bin/bash
POOL=a99e72c49c5ed39bf793caab9e074a80dd61011a859e975842874aab47b783f9ce84282febe2ca275c0930149b67990a
FARM=8ba5acd276b45fd0f749ce195dcddcf0e63c3bf2e751e9e273faa0125075c36a11f2ee231e7cf74abed2920be97fc373
OUT=/store/
rm /raid/plotting/*
for i in {1..1}
do
echo "$(tput setaf 10)Build Plot N°$i$(tput sgr0)"
./bladebit -v -t 30 -p $POOL -f $FARM -z 7 diskplot --f1-threads 16 --c-threads 16 --p2-threads 8  --cache 110G -t1 /raid/plotting $OUT
done
#sudo init 0
EOF
chmod +x /home/wareck/chia/chia-gigahorse/cpu-plotter/linux/x86_64/go.sh
echo "Done."
}

intro_
update_
lvm2_
drive_
wol_
chia_
miner_
crontab_
bash_
config_
webmin_

echo -e "\n"
echo -e "$(tput setaf 10)VNC install:$(tput sgr0)"
tigervnc_
vncpasswd
echo -e "\nProcess finished !! \nhappy plotting."
