#!/bin/bash

# ===========================================================================
# This script must be executed by root privilege
if [[ $(id -u) -ne 0 ]]; then
    echo -e "\e[1;31mThis script MUST be executed with root privilege.\e[0m\n"
	exit 1
fi

# ===========================================================================
# Double check if do run this script
echo -e "\e[1;2;31m[VPS USE ONLY] - Are you sure you want to run this script to re-configure you system???\e[0m"
read -p "Yes/No: " YON
[[ $YON != 'Yes' && $YON != 'YES' && $YON != 'yes' && $YON != 'y' && $YON != 'Y' ]] && exit 2
echo -e "\e[1;2;33m[VPS USE ONLY] - AGAIN, are you sure you want to run this script to re-configure you system???\e[0m"
read -p "Yes/No: " YON
[[ $YON != 'Yes' && $YON != 'YES' && $YON != 'yes' && $YON != 'y' && $YON != 'Y' ]] && exit 3

# ===========================================================================
# extract backup files
vps=`find . -name vps*.tar.xz`
if [[ ! -f flg && $vps != '' ]]; then
    echo -e "\n\e[1;34mExtracting backups to current dir...\e[0m\n"
    tar -I pixz -xmf vps*.xz
    touch flg
elif [[ -f flg ]]; then
    echo -e "\n\e[1;32mAlready extracted, doing nothing.\e[0m\n"
else
    echo -e "\n\e[1;31mThere is no backup file right here, plz check.\e[0m\n"
    exit 4
fi

# ===========================================================================
# sone prerequisites in aspect of path & content
echo -e "\n\e[1;34mPreparing initial env...\e[0m\n"
rm -rf /opt/*
mkdir -p /opt/logs
mkdir -p /opt/logs/rclone
mkdir -p /opt/temp
mkdir -p /opt/webdav/{alist,onedrive,wd}
mkdir -p /root/.pip
cp -rf configs scripts source-code websites /opt/
cp /opt/configs/pip.conf /root/.pip

# ===========================================================================
# set hostame
echo -e "\n\e[1;34mConfig hostname...\e[0m\n"
echo -ne "\e[1;34mPlz specify hostname: \e[0m"
read -t 600 host
hostnamectl set-hostname $host
name=`hostname`
cat /etc/hosts | grep -q $name
[[ $? -ne 0 ]] &&  sed -i "/^127/ s|$| $name|g" /etc/hosts

# ===========================================================================
# config self-defined environment variable and function
echo -e "\n\e[1;34mconfig self-defined environment variable and function...\e[0m\n"
cat /root/.bashrc | grep -q 'toolbox'
[[ $? -ne 0 ]] && echo 'source /opt/scripts/utool/toolbox.sh' >> /root/.bashrc
source /root/.bashrc
chmod +x /opt/scripts/utool/utool.py
rm -rf /usr/local/bin/utool
ln -s /opt/scripts/utool/utool.py /usr/local/bin/utool

# ===========================================================================
# set apt sources
echo -e "\n\e[1;34mConfig apt source list...\e[0m\n"
cat > /etc/apt/sources.list << EOF
deb https://mirrors.tuna.tsinghua.edu.cn/debian/ $(lsb_release -sc) main contrib non-free
deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ $(lsb_release -sc) main contrib non-free
deb https://mirrors.tuna.tsinghua.edu.cn/debian/ $(lsb_release -sc)-updates main contrib non-free
deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ $(lsb_release -sc)-updates main contrib non-free
deb https://mirrors.tuna.tsinghua.edu.cn/debian/ $(lsb_release -sc)-backports main contrib non-free
deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ $(lsb_release -sc)-backports main contrib non-free
deb https://mirrors.tuna.tsinghua.edu.cn/debian-security $(lsb_release -sc)-security main contrib non-free
deb-src https://mirrors.tuna.tsinghua.edu.cn/debian-security $(lsb_release -sc)-security main contrib non-free
EOF
echo -e "\n\e[1;34mUpdating system...\e[0m\n"
apt update && apt upgrade -y

# ===========================================================================
# install some frequently used software
echo -e "\n\e[1;34mInstalling some tools...\e[0m\n"
apt install lrzsz unzip vim gcc g++ make automake curl wget gnupg2 aria2 jq apt-transport-https \
    ca-certificates lsb-release debian-archive-keyring oathtool ufw ruby ruby-dev qbittorrent-nox\
    git shc tmux htop pwgen imagemagick bash-completion dnsutils ghostscript nethogs ffmpeg iftop \
    python3-pip python3-dev golang net-tools ethtool tcpflow lshw rsync parallel rclone pigz pbzip2 \
    pixz neofetch mlocate ncdu dstat fzf tldr nscd inotify-hookable  inotify-tools vsftpd mtr bridge-utils -y

# ===========================================================================
# update pip3 setuptools and install jupyter lab
echo -e "\n\e[1;34mupdate pip3 setuptools and install jupyter lab...\e[0m\n"
pip3 install --upgrade setuptools -i https://pypi.tuna.tsinghua.edu.cn/simple
pip3 install --upgrade pip -i https://pypi.tuna.tsinghua.edu.cn/simple
pip3 install ipython -i https://pypi.tuna.tsinghua.edu.cn/simple
pip3 install jupyterlab -i https://pypi.tuna.tsinghua.edu.cn/simple
# cp /root/.jupyter/jupyter_lab_config.py /root/.jupyter/jupyter_lab_config_origin.py
# cp /opt/configs/jupyter/jupyter_lab_config.py /root/.jupyter/
# nohup jupyter lab --allow-root > /dev/null 2>&1 &

# ===========================================================================
# configure vim
echo -e "\n\e[1;34mConfig vim editor...\e[0m\n"
cd /opt/configs/tools/
[[ -d vim ]] && rm -rf vim
unzip -q vimConfig.zip
cd vim && bash install.sh
cd .. && rm -rf vim

# ===========================================================================
# config ssh git ufw and aria2
echo -e "\n\e[1;34mConfig publickey ssh && git && ufw && aria2...\e[0m\n"
cd /opt/configs/rsa/
cp -f VPS* Github* config /root/.ssh/
cat VPS.pub > /root/.ssh/authorized_keys
echo '' >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/*

git config --global user.name 'mffan0922'
git config --global user.email 'mffan0922@163.com'

# ufw allow 22
# ufw allow 80
# ufw allow 443
ufw disable

cp -rf /opt/configs/aria2/ /etc/
> /etc/aria2/aria2.session

# ===========================================================================
# install nginx
echo -e "\n\e[1;34mInstalling nginx...\e[0m\n"
apt install libpcre3 libpcre3-dev openssl libssl-dev zlib1g-dev libgeoip-dev -y
cd /opt/source-code/nginx-1.22.0/
./configure  --prefix=/usr/local/nginx \
--with-select_module \
--with-poll_module \
--with-threads \
--with-file-aio \
--with-http_ssl_module \
--with-http_v2_module \
--with-http_realip_module \
--with-http_addition_module \
--with-http_geoip_module \
--with-http_sub_module \
--with-http_dav_module \
--with-http_flv_module \
--with-http_mp4_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_auth_request_module \
--with-http_random_index_module \
--with-http_secure_link_module \
--with-http_degradation_module \
--with-http_slice_module \
--with-http_stub_status_module \
--with-mail \
--with-mail_ssl_module \
--with-stream \
--with-stream_ssl_module \
--with-stream_realip_module \
--with-stream_geoip_module \
--with-stream_ssl_preread_module \
--user=www-data \
--group=www-data \
--add-module=/opt/source-code/nginx-1.22.0/modules/headers-more-nginx-module
make -j 4 && make install
[[ -f /usr/sbin/nginx ]] && rm -rf /usr/sbin/nginx
ln -s /usr/local/nginx/sbin/nginx /usr/sbin/nginx
cp -rf /opt/configs/nginx/nginx.conf /usr/local/nginx/conf/
cp -rf /opt/configs/nginx/nginx.service /lib/systemd/system/
systemctl enable nginx.service
systemctl start nginx.service

# ===========================================================================
# get https certificates
echo -e "\n\e[1;34mSetting https...\e[0m\n"
cd /root/ && git clone git@github.com:acmesh-official/acme.sh.git
cd acme.sh && ./acme.sh --install -m  mffan0922@163.com
alias acme.sh=~/.acme.sh/acme.sh
./acme.sh --issue --dns dns_ali -d rustle.cc -d *.rustle.cc
cp /root/.acme.sh/rustle.cc/fullchain.cer /opt/configs/certs/rustle.cc.cer
cp /root/.acme.sh/rustle.cc/rustle.cc.key /opt/configs/certs/

# ===========================================================================
# install jekyll
echo -e "\n\e[1;34mInstall jekyll blog env...\e[0m\n"
gem install jekyll jekyll-paginate

# ===========================================================================
echo -e "\n\e[1;34mInstalling mysql server...\e[0m\n"
cd /opt/configs/mysql/ && dpkg -i mysql-apt-config_0.8.23-1_all.deb
apt update && apt upgrade -y
apt install mysql-server -y
# cp -f /opt/configs/mysql/mysql.cnf /etc/mysql/conf.d/
systemctl restart mysql.service

# ===========================================================================
# install php8.0 for nextcloud
echo -e "\n\e[1;34mInstall php8.0...\e[0m\n"
wget -O /usr/share/keyrings/php-archive-keyring.gpg https://packages.sury.org/php/apt.gpg
echo "deb [signed-by=/usr/share/keyrings/php-archive-keyring.gpg] https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list
apt update && apt upgrade -y
apt install php8.0-fpm php8.0-cli php8.0-mysql php8.0-curl php8.0-gd \
    php8.0-mbstring php8.0-xml php8.0-zip php8.0-imap php8.0-opcache \
    php8.0-soap php8.0-gmp php8.0-bcmath php8.0-intl php8.0-imagick  -y

# ===========================================================================
# configure nextcloud
echo -e "\n\e[1;34mRestore nextcloud env...\e[0m\n"
apt install php8.0-memcache* memcached php8.0-apcu libmagickcore-6.q16-6-extra -y

echo -e "\n\e[1;34mbackup origin php data and restore previous php data...\e[0m\n"
cp -rf /etc/php/ /tmp/
cp -rf /opt/configs/php/8.0/fpm/pool.d/www.conf /etc/php/8.0/fpm/pool.d/www.conf
cp -rf /opt/configs/php/8.0/mods-available/apcu.ini /etc/php/8.0/mods-available/apcu.ini
cp -rf /opt/configs/php/8.0/cli/php.ini /etc/php/8.0/cli/php.ini
cp -rf /opt/configs/php/8.0/fpm/php.ini /etc/php/8.0/fpm/php.ini

# ===========================================================================
# restore mysql data
echo -e "\n\e[1;34mrestore mysql data...\e[0m\n"
cp /opt/configs/mysql/*.gz /root
cd /root && gzip -d sql-*.gz
mysql -uroot < sql-*.sql
rm sql*

# ===========================================================================
# configure frpc
echo -e "\n\e[1;34mRestore frpc env...\e[0m\n"
cp /opt/source-code/frpc/frpc.service /lib/systemd/system/
cp /opt/source-code/frpc/frpc-free.service /lib/systemd/system/
systemctl enable frpc.service
systemctl enable frpc-free.service
systemctl start frpc.service
systemctl start frpc-free.service

# ===========================================================================
# configure cloudreve
echo -e "\n\e[1;34mRestore cloudreve env...\e[0m\n"
cp /opt/source-code/cloudreve/cloudreve.service /lib/systemd/system/
systemctl enable cloudreve.service
systemctl start cloudreve.service

# ===========================================================================
# configure navidrome
echo -e "\n\e[1;34mRestore navidrome env...\e[0m\n"
cp /opt/source-code/navidrome/navidrome.service /lib/systemd/system/
systemctl enable navidrome.service
systemctl start navidrome.service

# ===========================================================================
# configure calibre
echo -e "\n\e[1;34mStarting calibre...\e[0m\n"
nohup /usr/bin/python3 /opt/source-code/calibre-web/cps.py > /dev/null 2>&1 &

# ===========================================================================
# configure blog
echo -e "\n\e[1;34mStarting blog...\e[0m\n"
nohup /usr/bin/ruby2.7 /usr/local/bin/jekyll b -s /opt/source-code/blog/ -d /opt/websites/blog/ --trace --watch --incremental > /dev/null 2>&1 &

# ===========================================================================
# configure alist
echo -e "\n\e[1;34mConfig alist...\e[0m\n"
cp /opt/source-code/alist/alist.service /lib/systemd/system/
systemctl enable alist.service
systemctl start alist.service

# ===========================================================================
# configure rclone
echo -e "\n\e[1;34mConfig rclone...\e[0m\n"
cp -rf /opt/configs/rclone /root/.config/

# ===========================================================================
# install php-8.1 & nodejs 16x
echo -e "\n\e[1;34mInstall php-8.1 & nodejs 16x for monica...\e[0m\n"
apt install -y php8.1 php8.1-bcmath php8.1-curl php8.1-gd php8.1-gmp php8.1-intl \
    php8.1-mbstring php8.1-mysql php8.1-redis php8.1-xml php8.1-zip
curl -sSL https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin/ --filename=composer
curl -fsSL https://deb.nodesource.com/setup_16.x | bash -
apt-get install -y nodejs
npm install --global yarn
cd /opt/source-code/monica/
composer install --no-interaction --no-dev
yarn install
yarn run production
php artisan key:generate
php artisan setup:production -v

# ===========================================================================
echo -e "\n\e[1;34mRemove no longer required packages...\e[0m\n"
apt autoremove -y

# ===========================================================================
echo -e "\n\e[1;34mRestart nginx mariadb php and cloudreve services...\e[0m\n"
systemctl restart nginx.service
systemctl restart mysql.service
systemctl restart cloudreve.service

# ===========================================================================
echo -e "\n\e[1;34mimprove nextcloud performance...\e[0m\n"
chown -R www-data:www-data /opt/websites/
# cd /opt/websites/nextcloud/
# sudo -u www-data php8.0 occ config:app:set files max_chunk_size --value 0
# sudo -u www-data php8.0 occ files:scan --all

# ===========================================================================
echo -e "\n\e[1;34mConfig crontabs and set correct timezone...\e[0m\n"
cp -f /opt/configs/crontabs/* /var/spool/cron/crontabs/
timedatectl set-timezone Asia/Shanghai

# ===========================================================================
echo -e "\n\e[1;31m基本环境已经安装完成，还需要手动配置如下：\e[0m\n"
echo "  1. 查看Homepage/Wiki/Nav站点是否可以正常访问"
echo "  2. 查看blog生成日志是否正常"
echo "  3. 访问nextcloud/cloudreve站点，是否可以正常登陆，并手动优化"
echo "  4. 手动配置Jupyter Lab"
echo "  5. 检查Navidrome是否能正常播放音乐"
echo "  6. 手动运行一次qbittorrent-nox，并配置相关选项"
echo "  7. 需要手动配置koel，并运行"
echo "  8. 检查frp的运行状态"
echo "  9. 直接访问Calibre Web，看是否可以正常访问"
echo "  10. 需要手动配置monica，并运行"
echo "  11. 手动安装jellyfin，因为可能安装包无法下载，需要去腾讯云主机下载传过来再安装"
echo "  12. 访问Alist主页，看是否可以正常访问"
echo "  13. 访问uptime status，看是否可以正常访问"
echo "  14. 手动安装bashit"
echo "  15. 重启系统"


