#!/bin/bash -e
NOT_ROOT=1
NOT_CHECK=2
NOT_FOUND_FILE=3
WRONG_OPTION=4
ABORT=9

# =============================================================================================================
# Do the following on the physical machine with a monitor
# -------------------------------------------------------------------------------------------------------------
# modify /etc/ssh/sshd_config, enable root login, permit password authentication, and restart sshd service
# -------------------------------------------------------------------------------------------------------------
# modify /etc/network/interfaces, using `ip addr` to get netcard name
# -------------------------------------------------------------------------------------------------------------
# DHCP
# auto enp1s0
# allow-hotplug enp1s0
# iface enp1s0 inet dhcp
# -------------------------------------------------------------------------------------------------------------
# Manually set
# auto enp2s0
# allow-hotplug enp2s0
# iface enp2s0 inet static
# address 192.168.123.54
# netmask 255.255.255.0
# gateway 192.168.123.1
# -------------------------------------------------------------------------------------------------------------
# configure wireless, using `ifconfig -a` to get all card names, including usb wireless adapter
# auto wlx90de80ca01ec
# allow-hotplug wlx90de80ca01ec
# iface wlx90de80ca01ec inet dhcp
# wpa-conf /opt/configs/conf/wpa.conf
# wpa_passphrase wifi_name wifi_passwd >> /opt/configs/conf/wpa.conf -- need to modify content, using clear text password
# Firstly, testing wireless when there is a wired network, when everything is OK, then do the following:
# ifdown enp2s0 &&ifdown wlx90de80ca01ec && ifup wlx90de80ca01ec
# Finally, pull out the wired network
# -------------------------------------------------------------------------------------------------------------
# add ssd to fstab
# 	- set disl reserve space: tune2fs -m 0 /dev/sda
# 	- /etc/fstab：UUID=c10abddb-35be-4e8e-92cd-96be8a96cb5f /opt/wd ext4 defaults 0 0
# -------------------------------------------------------------------------------------------------------------
# lack of bluetooth drivers and wireless net card(Intel AX101)drivers -- ibt-0040-1050.sfi
#    cp ibt-0040-0041.sfi ibt-0040-1050.sfi
#    cp ibt-0040-0041.ddc ibt-0040-1050.ddc
# -------------------------------------------------------------------------------------------------------------
# do nothing when closing laptop lid
# Firstly, edit file /etc/systemd/logind.conf
# HandleLidSwitch=ignore
# HandleLidSwitchExternalPower=ignore
# HandleLidSwitchDocked=ignore
# LidSwitchIgnoreInhibited=yes
#
# Candidate: suspend/lock/ignore/poweroff/hibernate
#
# Secondly, reboot the system
# -------------------------------------------------------------------------------------------------------------
# get host local ip when using a new network environment
# ping BeeLink
# -------------------------------------------------------------------------------------------------------------
# x-ui build up
# bash <(curl -Ls https://raw.githubusercontent.com/vaxilu/x-ui/master/install.sh)
# -------------------------------------------------------------------------------------------------------------
# update docker images
# 0. docker-compose down
# 1. docker-compose pull
# 2. docker-compose up -d --remove-orphans
# 3. docker image prune
# -------------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------------------
#
#
#


# =============================================================================================================
# 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 $NOT_ROOT
fi

# =============================================================================================================
# 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 your system???\e[0m"
read -p "Yes/No: " YON
[[ $YON != 'Yes' && $YON != 'YES' && $YON != 'yes' && $YON != 'y' && $YON != 'Y' ]] && exit $NOT_CHECK

# =============================================================================================================
# extract backup files
read -p "Next will extract the backup file to current dir, [(S)kip|(A)bort|(Y)es]: " SAY
if [[ $SAY == 's' || $SAY == 'S' || $SAY == 'skip' || $SAY == 'Skip' || $SAY == 'SKIP' ]]; then
    :
elif [[ $SAY == 'a' || $SAY == 'A' || $SAY == 'abort' || $SAY == 'Abort' || $SAY == 'ABORT' ]]; then
    exit $ABORT
elif [[ $SAY == 'y' || $SAY == 'Y' || $SAY == 'yes' || $SAY == 'Yes' || $SAY == 'YES' ]]; then
    vps=`find . -name VPS*.tar.gz`
    if [[ ! -f flg && $vps != '' ]]; then
        echo -e "\n\e[1;34mExtracting backups to current dir...\e[0m"
        tar -I pixz -xmf VPS*.tar.gz
        touch flg
    elif [[ -f flg ]]; then
        echo -e "\n\e[1;32mAlready extracted, doing nothing.\e[0m"
    else
        echo -e "\n\e[1;31mThere is no backup file right here, plz check.\e[0m"
        exit $NOT_FOUND_FILE
    fi
else
	echo -e "\n\e[1;31mNeed to input correct option, exiting...\e[0m"
	exit $WRONG_OPTION
fi


# =============================================================================================================
# using tsinghua sources
echo -e "\n\e[1;34mUpdating the system...\e[0m"
cat > /etc/apt/sources.list << EOF
deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm main contrib non-free non-free-firmware
deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm main contrib non-free non-free-firmware
deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware
deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-updates main contrib non-free non-free-firmware
deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware
deb-src https://mirrors.tuna.tsinghua.edu.cn/debian/ bookworm-backports main contrib non-free non-free-firmware
deb https://mirrors.tuna.tsinghua.edu.cn/debian-security bookworm-security main contrib non-free non-free-firmware
deb-src https://mirrors.tuna.tsinghua.edu.cn/debian-security bookworm-security main contrib non-free non-free-firmware
EOF
apt update && apt upgrade -y


# =============================================================================================================
# install some frequently used software
echo -e "\n\e[1;34mInstalling some useful 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 \
    socat dos2unix samba libldap2-dev libsasl2-dev smartmontools parted libpcre3 libpcre3-dev openssl \
    libssl-dev zlib1g-dev libgeoip-dev libncurses-dev libpython3-dev fwupd virtualenv wpasupplicant \
    jpegoptim optipng -y

curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && apt-get install -y nodejs
# fwupdmgr get-updates &&  fwupdmgr update

# =============================================================================================================
# restore files
echo -e "\n\e[1;34mRestoring files to /opt && do some configuring...\e[0m\n"
cp -rf VPS/* /opt/
echo 'source /opt/configs/conf/envfile' >> /root/.bashrc
source /root/.bashrc

cp /opt/configs/conf/pip.conf /etc/
cp /opt/configs/conf/sysctl.conf /etc/ && sysctl -p
ln -s /opt/configs/tools/docker-compose /usr/bin/docker-compose
ln -s /opt/scripts/utool/utool.py /usr/local/bin/utool
systemctl set-default multi-user.target
timedatectl set-timezone "Asia/Shanghai"
echo "Asia/Shanghai" > /etc/timezone
hostnamectl set-hostname "BeeLink"
echo 'supersede domain-name-servers 8.8.8.8, 8.8.4.4, 114.114.114.114;' >> /etc/dhcp/dhclient.conf
systemctl restart networking.service

cp -rf /opt/configs/rsa/* /root/.ssh/
cat /root/.ssh/*.pub > /root/.ssh/authorized_keys
chmod 600 /root/.ssh/*

git config --global user.name 'gitea'
git config --global user.email 'mffan0922@163.com'
git config --global init.defaultBranch main
git config --global credential.helper store
git config --global core.filemode false
git config --global apply.whitespace nowarn
git config --global core.editor vim

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

# =============================================================================================================
# bash it installation
cd /opt/configs/tools/ && tar -xzf bash_it.tar.gz
mv bash_it /root/.bash_it && cd /root/
bash .bash_it/install.sh

# =============================================================================================================
# vim installation
cd /opt/configs/tools/ && tar -xzf vim_runtime.tar.gz
mv vim_runtime /root/.vim_runtime && cd /root/
bash .vim_runtime/install_awesome_vimrc.sh
cp /opt/configs/conf/my_configs.vim /root/.vim_runtime/my_configs.vim
# modify /root/.bash_it/themes/brainy/brainy.theme.bash, where 'THEME_SHOW_PYTHON' to true
# modify /root/.bashrc, where change bash_it theme to brainy

# =============================================================================================================
# configure frpc
echo -e "\n\e[1;34mRestore frpc env...\e[0m\n"
cp /opt/apps/frp/frpc/frpc-overseas-free.service /lib/systemd/system/
cp /opt/apps/frp/frpc/frpc-overseas-ssh.service /lib/systemd/system/
cp /opt/apps/frp/frpc/frpc-overseas-gitea.service /lib/systemd/system/
cp /opt/apps/frp/frpc/frpc-bilinat-ssh.service /lib/systemd/system/
systemctl enable frpc-overseas-free.service
systemctl enable frpc-overseas-ssh.service
systemctl enable frpc-overseas-gitea.service
systemctl enable frpc-bilinat-ssh.service
systemctl start frpc-overseas-free.service
systemctl start frpc-overseas-ssh.service
systemctl start frpc-overseas-gitea.service
systemctl start frpc-bilinat-ssh.service

# =============================================================================================================
# get https certificates
echo -e "\n\e[1;34mSetting https...\e[0m\n"
cp /opt/configs/tools/acme.sh-3.0.6.tar.gz /root/ && cd /root/
tar -xzf acme.sh-3.0.6.tar.gz
cd acme.sh-3.0.6/ && bash acme.sh --install -m mffan0922@163.com
alias acme.sh='~/.acme.sh/acme.sh'
cd /root/ && rm -rf acme.sh-3.0.6*
acme.sh  --issue -d 'iced.eu.org' -d '*.iced.eu.org'  --dns dns_cf
acme.sh  --issue -d 'amble.eu.org' -d '*.amble.eu.org'  --dns dns_cf
acme.sh  --issue -d 'erratic.eu.org' -d '*.erratic.eu.org'  --dns dns_cf
acme.sh  --issue -d 'ephemeral.eu.org' -d '*.ephemeral.eu.org'  --dns dns_cf
acme.sh  --issue -d 'rustle.us.eu.org' -d '*.rustle.us.eu.org'  --dns dns_cf
acme.sh  --issue -d 'rustle.uk.eu.org' -d '*.rustle.uk.eu.org'  --dns dns_cf
acme.sh  --issue -d 'rustle.cn.eu.org' -d '*.rustle.cn.eu.org'  --dns dns_cf
acme.sh  --issue -d 'rustle.cc' -d '*.rustle.cc'  --dns dns_ali

# =============================================================================================================
# install nginx
apt install libpcre3 libpcre3-dev openssl libssl-dev zlib1g-dev libgeoip-dev -y
cd /opt/apps/nginx/
./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/apps/nginx/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/domain_confs/ /usr/local/nginx/conf/
cp -rf /opt/configs/nginx/nginx.service /lib/systemd/system/
systemctl enable nginx.service
systemctl start nginx.service

# =============================================================================================================
# install jekyll
echo -e "\n\e[1;34mInstall jekyll blog env...\e[0m\n"
gem sources --add https://mirrors.tuna.tsinghua.edu.cn/rubygems/ --remove https://rubygems.org/
gem sources -l
gem install jekyll jekyll-paginate
jekyll b -s /opt/apps/blog/ -d /opt/websites/blog/

# =============================================================================================================
# configure calibre
echo -e "\n\e[1;34mStarting calibre...\e[0m\n"
cd /opt/apps/calibre/calibre-web-0.6.20/ && rm -rf venv/
virtualenv venv
source venv/bin/activate
pip3 install -r requirements.txt
deactivate
bash /opt/scripts/update/calibre.sh

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

# =============================================================================================================
# install docker
apt install curl vim wget gnupg dpkg apt-transport-https lsb-release ca-certificates
curl -sSL https://download.docker.com/linux/debian/gpg | gpg --dearmor > /usr/share/keyrings/docker-ce.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-ce.gpg] https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/debian $(lsb_release -sc) stable" > /etc/apt/sources.list.d/docker.list
apt update
apt install docker-ce docker-ce-cli containerd.io
cp /opt/configs/conf/daemon.json /etc/docker/
docker network create -d bridge --subnet=10.10.0.0/24  --gateway 10.10.0.1 inner

# docker - v2raya/dashboard/gitea/vaultwarden/mysql/photoprism/chatgpt
# docker-compose pull
# docker-compose up -d

# docker - koel
# docker-compose pull
# docker-compose up -d
# docker exec -it koel bash
# cp .env.example .env
#     - FORCE_HTTPS=true
#     - APP_URL=https://koel.rustl.cc/
#     - database settings
#     - MEDIA_PATH=/opt/apps/localcr/B_koel/local/music
# php artisan koel:init --no-assets
# php artisan koel:admin:change-password
# chown -R www-data:www-data /opt/apps/localcr/B_koel/local/
# php artisan koel:sync
# /app/Models/User.php --> sprintf('https://www.rustle.cc/assets/img/logo.jpg', md5($this->email))

# docker - openwrt
# docker-compose pull
# docker-compose up -d
# docker exec -it openwrt bash
# ip link set enp1s0 promisc on
# ip link set enp2s0 promisc on
# docker exec -it OpenWRT bash
# vim /etc/config/network
#     config interface 'lan'
#         option ifname 'eth0'
#         option proto 'static'
#         option netmask '255.255.255.0'
#         option gateway '192.168.31.1'
#         option ip6assign '60'
#         option dns ' 8.8.8.8 114.114.114.114'
#         option ipaddr '192.168.31.123'
#         option broadcast '192.168.31.255'
# /etc/init.d/network restart
# modify the above according to different situations, and the following is another method to do this
# docker network create -d macvlan --subnet=192.168.31.1/24 --gateway=192.168.31.2  -o parent=enp1s0 net_openwrt
# docker run -d --name openwrt --net net_openwrt --privileged --ip 192.168.183.123 sulinggg/openwrt:x86_64 /sbin/init
# when using openwrt or another ethernet port, keep in mind that need to modify ip addr accordingly

# =============================================================================================================
# configure cloudreve after mysql docker is up
echo -e "\n\e[1;34mRestore cloudreve env...\e[0m\n"
cp /opt/apps/cloudreve/cloudreve.service /lib/systemd/system/
systemctl enable cloudreve.service
systemctl start cloudreve.service

# =============================================================================================================
# configure syncthing
ln -s /opt/apps/syncthing/syncthing /usr/bin/syncthing
cp /opt/apps/syncthing/syncthing@root.service /lib/systemd/system/
systemctl enable syncthing@root.service
systemctl start syncthing@root.service
# edit /root/.config/syncthing/config.xml, and change gui connection address to 0.0.0.0

# =============================================================================================================
# configure samba
cp /opt/configs/conf/smb.conf /etc/samba/
smbpasswd -a root
systemctl restart smbd.service
# On Windows platform, using `net use * /delete` to remove previous connections

# =============================================================================================================
# POST INSTALLATION
echo -e "\n\e[1;34m[POST INSTALLATION] Wait, there is something to do...\e[0m\n"
echo -e "\e[1;32m    1. open v2raya, and pull the docker images"
echo -e "\e[1;32m    2. manually start qbittorrent, and modify password and more"
echo -e "\e[1;32m    3. manually start syncthing, and modify ~/.config/syncthing/config.xml"
echo -e "\e[1;32m    4. manually start cloudreve"
echo -e "\e[1;32m    5. manually start dockers"
echo -e "\e[1;32m    6. manually configure the cron service"
echo -e "\e[1;32m    7. manually configure samba service"
echo -e "\e[1;32m    9. reboot serer, and see if all service function properly"


