#!/usr/bin/env bash

scriptdir=$(dirname $(realpath $0))
tempdir=$(mktemp -d)

if [[ $(sudo id -u) -ne 0 ]]; then
    echo "Please get sudo access first."
    exit 1
fi

# ============================================================

. $scriptdir/init_user.sh

# ============================================================

configure_tuna() {
    [ $abroad -eq 1 ] && return

    if confirm_action "要切换 Tuna 源吗？" "N"; then
        python3 $scriptdir/files/oh-my-tuna.py
        # 如果 uid 不为 0 则 sudo 再跑一次
        if [[ $EUID -ne 0 ]]; then
            sudo python3 $scriptdir/files/oh-my-tuna.py
        fi
    fi
}

configure_upgrade() {
    if confirm_action "要运行 apt upgrade 吗？" "N"; then
        sudo apt update
        sudo apt upgrade -y
        sudo apt autoremove -y
    fi
}

configure_install_basic() {
    [ "$1" != "noupdate" ] && sudo apt update
    sudo apt install tmux git curl htop net-tools tar unzip -y
    pip3 install trash-cli
}

configure_install_useful() {
    [ "$1" != "noupdate" ] && sudo apt update
    sudo apt install hexyl bat neofetch fd-find fzf tcptraceroute tree -y
}

configure_install_new() {
    [ "$1" != "noupdate" ] && sudo apt update
    sudo apt install pigz -y
    pip3 install speedtest-cli
}

configure_install_eza() {
    if ! command_exists eza; then
        unzip $scriptdir/files/eza_x86_64-unknown-linux-musl.zip -d $tempdir/eza
        sudo cp $tempdir/eza/eza /usr/local/bin/
        rm $tempdir/eza -r
    fi
}

configure_install() {
    if confirm_action "要运行 apt/pip3 install 吗？" "N"; then
        sudo apt update
        configure_install_basic noupdate
        configure_install_useful noupdate
        configure_install_new noupdate
        configure_install_eza noupdate
    fi
}

configure_nano() {
    [ -f ~/.nanorc ] && return

    if confirm_action "要配置 nano 吗？" "Y"; then
        sudo apt install nano -y
        cp $scriptdir/files/.nanorc ~/.nanorc
    fi
}

configure_vim() {
    [ -f ~/.vimrc ] && return

    if confirm_action "要配置 vim 吗？" "Y"; then
        sudo apt install vim -y
        cp $scriptdir/files/.vimrc ~/.vimrc
    fi
}

configure_zsh() {
    [ -f ~/.zshrc ] && return

    if confirm_action "要配置 zsh 吗？" "Y"; then
        sudo apt install zsh -y

        rm ~/.oh-my-zsh -r
        git_clone ohmyzsh/ohmyzsh ~/.oh-my-zsh
        RUNZSH=no ZSH=~/.oh-my-zsh $scriptdir/files/install-ohmyzsh.sh

        git_clone zsh-users/zsh-autosuggestions ~/.oh-my-zsh/custom/plugins/zsh-autosuggestions
        git_clone zsh-users/zsh-syntax-highlighting ~/.oh-my-zsh/custom/plugins/zsh-syntax-highlighting
        git_clone paulirish/git-open ~/.oh-my-zsh/custom/plugins/git-open --norecursive
        sudo apt install autojump -y

        if ! grep -Fxq "source ~/.oh-my-zsh/custom/00-init.zsh" ~/.zshrc; then
            local line_number=$(grep -n "source \$ZSH/oh-my-zsh.sh" ~/.zshrc | cut -d : -f 1)
            sed -i "${line_number}i source ~/.oh-my-zsh/custom/00-init.zsh\n" ~/.zshrc
        fi
        echo -e "\nsource ~/.zsh_user" | sudo tee -a ~/.zshrc >/dev/null

        cp $scriptdir/files/zsh/.zsh_user           ~/.zsh_user
        cp $scriptdir/files/zsh/00-init.zsh         ~/.oh-my-zsh/custom/
        cp $scriptdir/files/zsh/10-theme.zsh        ~/.oh-my-zsh/custom/
        cp $scriptdir/files/zsh/20-function.zsh     ~/.oh-my-zsh/custom/
        cp $scriptdir/files/zsh/50-alias.zsh        ~/.oh-my-zsh/custom/
        cp $scriptdir/files/zsh/80-env.zsh          ~/.oh-my-zsh/custom/
        cp $scriptdir/files/zsh/90-other.zsh        ~/.oh-my-zsh/custom/
        cp $scriptdir/files/zsh/ys-simple.zsh-theme ~/.oh-my-zsh/custom/themes/

        [ $abroad -eq 1 ] && return
        cp $scriptdir/files/zsh/81-proxy.zsh        ~/.oh-my-zsh/custom/
    fi
}

configure_tmux() {
    [ -f ~/.tmux.conf ] && return

    if confirm_action "要配置 tmux 吗？" "Y"; then
        sudo apt install tmux -y

        rm ~/.tmux -r
        git_clone tmux-plugins/tpm ~/.tmux/plugins/tpm --norecursive
        git_clone tmux-plugins/tmux-sensible ~/.tmux/plugins/tmux-sensible
        git_clone tmux-plugins/tmux-yank ~/.tmux/plugins/tmux-yank
        git_clone tmux-plugins/tmux-prefix-highlight ~/.tmux/plugins/tmux-prefix-highlight
        git_clone seebi/tmux-colors-solarized ~/.tmux/plugins/tmux-colors-solarized

        cp $scriptdir/files/.tmux.conf ~/.tmux.conf
        sudo apt install xsel -y # 能够让 tmux 剪切板与 terminal 同步
    fi
}

configure_docker() {
    command_exists docker && return

    if confirm_action "要安装 docker 吗？" "N"; then
        # 卸载旧版本
        sudo apt remove docker docker-engine docker.io
        sudo apt update
        sudo apt install apt-transport-https ca-certificates curl gnupg lsb-release -y
        # 添加软件源的 GPG 密钥，并向 sources.list 中添加 Docker 软件源
        if [ $abroad -eq 1 ]; then
            curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
            echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
        else
            curl -fsSL https://mirrors.aliyun.com/docker-ce/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
            echo "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://mirrors.aliyun.com/docker-ce/linux/ubuntu $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
        fi
        sudo apt-get update
        sudo apt-get install docker-ce docker-ce-cli containerd.io -y
        sudo systemctl enable docker
        sudo systemctl start docker
        sudo pip3 install docker-compose
    fi
}

configure_yarn() {
    echo "Incomplete"; return

    curl -fsSL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo gpg --dearmor -o /usr/share/keyrings/yarn.gpg
    echo "deb [signed-by=/usr/share/keyrings/yarn.gpg] https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list > /dev/null
}

configure_mongodb() {
    echo "Incomplete"; return

    version=7.0
    curl -fsSL https://pgp.mongodb.com/server-$version.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-$version.gpg
    echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/mongodb-server-$version.gpg] https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/$version multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-$version.list > /dev/null
}

configure_nginx() {
    echo "Incomplete"; return

    curl -fsSL https://nginx.org/keys/nginx_signing.key | sudo gpg --dearmor -o /usr/share/keyrings/nginx.gpg
    echo "deb [signed-by=/usr/share/keyrings/nginx.gpg] https://nginx.org/packages/ubuntu/ $(lsb_release -cs) nginx" | sudo tee /etc/apt/sources.list.d/nginx.list > /dev/null
    echo "deb-src [signed-by=/usr/share/keyrings/nginx.gpg] https://nginx.org/packages/ubuntu/ $(lsb_release -cs) nginx" | sudo tee -a /etc/apt/sources.list.d/nginx.list > /dev/null
}

configure_fail2ban() {
    [ -f /etc/fail2ban/jail.local ] && return

    if confirm_action "要配置 fail2ban 吗？" "N"; then
        sudo apt install fail2ban
        sudo mkdir -p /etc/fail2ban
        sudo cp $scriptdir/files/jail.local /etc/fail2ban/jail.local
        sudo systemctl start fail2ban
        sudo systemctl enable fail2ban
        sudo fail2ban-client status sshd
    fi
}

configure_iptables() {
    [ -f /etc/network/if-pre-up.d/iptables-load ] && return

    if confirm_action "要配置 iptables 吗？" "N"; then
        sudo cp $scriptdir/files/iptables-load /etc/network/if-pre-up.d/iptables-load
        sudo chmod +x /etc/network/if-pre-up.d/iptables-load
        sudo sh /etc/network/if-pre-up.d/iptables-load
    fi
}

configure_hostname() {
    if confirm_action "要修改 hostname 吗？" "N"; then
        read -p "hostname: " new_hostname
        echo $new_hostname | sudo tee /etc/hostname >/dev/null
    fi
}

configure_timedate() {
    [[ $(timedatectl | grep "Time zone" | awk '{print $3}') == "Asia/Shanghai" ]] && return

    if confirm_action "要修改 时区 吗？" "N"; then
        sudo timedatectl set-timezone Asia/Shanghai
    fi
}

configure_bootinfo() {
    [ -d /etc/update-motd.d/disable ] && return

    if confirm_action "要修改 启动信息 吗？" "Y"; then
        sudo mkdir /etc/update-motd.d/disable
        sudo mv /etc/update-motd.d/10-help-text /etc/update-motd.d/disable/
        sudo mv /etc/update-motd.d/50-motd-news /etc/update-motd.d/disable/
        # sudo mv /etc/update-motd.d/88-esm-announce /etc/update-motd.d/disable/
        if [ -d /usr/lib/python3/dist-packages/landscape/sysinfo ]; then
            sudo sed -i 's/"Network"/"Network_Simple"/g' /usr/lib/python3/dist-packages/landscape/sysinfo/deployment.py
            sudo cp $scriptdir/files/sysinfo_network_simple.py /usr/lib/python3/dist-packages/landscape/sysinfo/network_simple.py
        fi
    fi
}

configure_oomkiller() {
    [ -f /etc/default/earlyoom ] && return

    if confirm_action "要启用 earlyoom 吗？" "Y"; then
        sudo apt install earlyoom -y
        sudo cp $scriptdir/files/earlyoom.conf /etc/default/earlyoom
        sudo systemctl restart earlyoom
    fi
}

configure_proxychains() {
    [ -f /etc/proxychains4.conf ] && return

    if confirm_action "要配置 proxychains 吗？" "N"; then
        sudo apt install proxychains4 -y
        sudo cp $scriptdir/files/proxychains4.conf /etc/proxychains4.conf
    fi
}

configure_nodejs() {
    [ -f /usr/local/bin/node ] && return

    if confirm_action "要安装 nodejs 吗？" "Y"; then
        local version="v20.10.0"
        local tarname="node-$version-linux-x64"
        wget https://nodejs.org/dist/$version/$tarname.tar.xz -O $tempdir/$tarname.tar.xz
        tar -xf $tempdir/$tarname.tar.xz -C $tempdir
        sudo cp $tempdir/$tarname/bin/node /usr/local/bin/node
        sudo cp $tempdir/$tarname/bin/npm /usr/local/bin/npm
        rm $tempdir/$tarname.tar.xz
        rm $tempdir/$tarname -r
    fi
}

# ============================================================

configure_swap() {
    # Input the swap size
    read -p "Swap size (MB): " swap_size
    # Create a virtual memory file
    sudo dd if=/dev/zero of=/mnt/swap bs=1M count=$swap_size
    sudo chmod 0600 /mnt/swap
    sudo mkswap /mnt/swap
    sudo swapon /mnt/swap
    # Write auto mount parameters
    if ! grep -q swap /etc/fstab; then
        echo "/mnt/swap swap swap defaults 0 0" | sudo tee -a /etc/fstab >/dev/null
    fi
    # Set virtual memory usage
    if ! grep -q swappiness /etc/sysctl.conf; then
        echo "vm.swappiness = 10" | sudo tee -a /etc/sysctl.conf >/dev/null
    else
        # sed -i 's/vm.swappiness = 0/vm.swappiness = 10/' /etc/sysctl.conf
        sudo sed -i 's/^vm.swappiness.*/vm.swappiness = 10/' /etc/sysctl.conf
    fi
    # Make the configuration take effect
    sudo sysctl -p
}

# ============================================================

if [ $# -ne 0 ]; then
    for func in $@; do
        declare -F configure_$func >/dev/null || continue
        echo "Configuring $func..."
        eval "configure_$func"
    done
    return
fi

configure_tuna
configure_upgrade
configure_install
configure_nano
configure_vim
configure_zsh
configure_tmux
configure_nodejs
configure_docker
configure_fail2ban
configure_iptables
configure_hostname
configure_timedate
configure_bootinfo
configure_oomkiller
