#!/bin/bash
# author:德玛西亚
# url:www.xxx.com
config="[Unit]\n 
Description=A API For Subscription Convert\n
After=network.target\n

[Service]\n
Type=simple\n
ExecStart=/root/subconverter/subconverter\n
WorkingDirectory=/root/subconverter\n
Restart=always\n
RestartSec=10\n

[Install]\n
WantedBy=multi-user.target"\n

#check os
if [ -f /etc/os-release ]; then
    source /etc/os-release
    if [ "${ID}" = "ubuntu" ]; then
        ins="apt-get"
    elif [ "${ID}" = "centos" ]; then
        ins="yum"
    else
        echo -e "\033[32m未检测到操作系统类型 \033[0m"
    fi
fi

function version_compare() {
    if [[ "$1" == "$2" ]]; then
        echo "本地版本 $1 与 远程版本 $2 相同，无需更新！"
        return 0
    fi

    if [[ "$(printf '%s\n' "$1" "$2" | sort -V | head -n1)" == "$1" ]]; then
        echo "本地版本 $1 小于 远程版本 $2，可以更新。"
        return 1
    else
        echo "本地版本 $1 大于 远程版本 $2，无需更新！"
        return 0
    fi
}

function SubWeb(){
    $ins update -y
    echo -e "\033[32m正在安装依赖软件包... \033[0m"
    sleep 1
    $ins install -y curl wget sudo nodejs git
    
    if [ ! "$(command -v npm)" ]; then
    echo -e "\033[32mnpm 没有安装,正在安装... \033[0m" >&2
    sleep 1
    $ins install npm –enablerepo=epel
    npm -v
    sleep 3
    fi

    node_version=$(node -v | sed 's/^v//')
    version_compare "$node_version" "16.0.0"
    if [ $? -eq 1 ]; then
        source ~/.nvm/nvm.sh 
        if [ ! "$(command -v nvm)" ]; then
        echo -e "\033[32mnvm没有安装,正在安装... \033[0m" >&2
        sleep 1
        wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | bash
        nvm -v
        sleep 3
        fi
        echo -e "\033[32m正在安装指定版本nodejs... \033[0m" >&2
        sleep 1
        nvm install v16.0.0
        nvm alias default v16.0.0
        nvm current
        node -v
        sleep 3
    fi
    

    if [ ! "$(command -v cnpm)" ]; then
    echo -e "\033[32mcnpm 没有安装,正在安装... \033[0m" >&2
    sleep 1
    npm cache clean --force
    npm config set strict-ssl false
    npm install -g cnpm --registry=https://registry.npm.taobao.org
    cnpm -v
    sleep 3
    fi
    
    if [ ! "$(command -v yarn)" ]; then
    echo -e "\033[32myarn 没有安装,正在安装... \033[0m" >&2
    sleep 1
    cnpm install -g yarn
    yarn -v
    sleep 3
    fi
    
    #获取当前路径
    currentPath=$(cd `dirname $0`; pwd)
    rm -rf "$currentPath/$2"
    
    echo -e "\033[32m正在拉取sub-web... \033[0m"
    sleep 1
    git clone "https://github.jobcher.com/gh/$1"
    cd $2
    
    # 配置文件路径  
    Subconverter_config_file="$currentPath/$2/src/views/Subconverter.vue" 
    env_converter_config_file="$currentPath/$2/.env"
    
    echo -e "\033[32m请输入您的后端别名（别名:域名）:\033[0m"
    read customBackend_name 
    echo -e "\033[32m请输入您的后端域名（别名:域名）:\033[0m"
    read customBackend #后端域名
    
    sed -i "/customBackend:\s*{/a \"$customBackend_name\":\"$customBackend\", " $Subconverter_config_file
    sed -i "/this\.tanchuang\(\)/d" $Subconverter_config_file
    sed -i "/this\.getBackendVersion\(\)/d" $Subconverter_config_file
    
    sed -i "/backendOptions:\s*\[/a {value: \"$customBackend\"}, " $Subconverter_config_file
    
    sed -i "s#customBackend:\sthis\.getUrlParam\(\).*\$# customBackend: this.getUrlParam() == \"\" ? \"$customBackend\" : this.getUrlParam(),#" $Subconverter_config_file
    
    sed -i "s#\(^VUE_APP_SUBCONVERTER_DEFAULT_BACKEND =\).*#\1\"$customBackend\"#" $env_converter_config_file
    
    echo -e "\033[32m已删除配置文件弹窗广告！ \033[0m"
    echo -e "\033[32m正在构建依赖... \033[0m"
    yarn install
    echo -e "\033[32m正在打包... \033[0m"
    yarn build
    echo -e "\033[32m前端安装完成，请将/root/sub-web/dist目录发布至web服务器... \033[0m"
    echo -e "\033[32m若使用本脚本安装后端，伪静态规则请配置如下：
    location /sub{
        proxy_pass http://127.0.0.1:25500;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header REMOTE-HOST \$remote_addr;
        add_header X-Cache \$upstream_cache_status;
        #Set Nginx Cache
        add_header Cache-Control no-cache;
        expires 12h;
    }\033[0m"
    menw
}
function SubConverter(){
    #后端配置文件
    echo -e "\033[32m请输入token（随机）：\033[0m"
    read api_access_token #随机
    echo -e "\033[32m请输入解析的后端域名：\033[0m"
    read managed_config_prefix
    echo -e "\033[32m请输入监听ip：（直接回车默认127.0.0.1无需更改）\033[0m"
    read listen
    echo -e "\033[32m请输入端口：（直接回车默认25500）\033[0m"
    read port
    if [ -z "${listen}" ];then
        listen="127.0.0.1"
    fi
    if [ -z "${port}" ];then
        port="25500"
    fi
    
    echo -e "\033[32m正在拉取后端文件... \033[0m"
    sleep 3
    cd /root
    wget https://github.com/MetaCubeX/subconverter/releases/download/Alpha/subconverter_linux64.tar.gz
    tar -zxvf subconverter_linux64.tar.gz && cd subconverter
    cp -i pref.example.ini pref.ini
    #获取当前路径
    currentPath=$(cd `dirname $0`; pwd)
    # 配置文件路径  
    config_file="$currentPath/pref.ini"  
  
    # 设置新的IP和端口值  \表示特殊符合处理，转义符
    

    # 检查配置文件是否存在  
    if [ ! -f "$config_file" ]; then  
        echo -e "\033[32m Error: $config_file 不存在! \033[0m"
        exit 1  
    fi  

    # 使用sed命令修改配置文件中【huake】下的ip和port的值  
    #sed -i -e "s/^\[huake\]$/\[huake\]\nip=${new_ip}\nport=$new_port/" "$config_file"  #追加
    # 替换
    sed -i "s/\(^api_access_token=\).*/\1${api_access_token}/" $config_file
    sed -i "s/\(^managed_config_prefix=\).*/\1${managed_config_prefix}/" $config_file
    sed -i "s/\(^listen=\).*/\1$listen/" $config_file
    sed -i "s/\(^port=\).*/\1$port/" $config_file
    echo -e "\033[32m配置文件修改成功,正在创建服务进程并启动... \033[0m"
    sleep 3
    touch /etc/systemd/system/sub.service
    echo -e $config > /etc/systemd/system/sub.service
    systemctl daemon-reload
    systemctl stop sub
    systemctl start sub
    systemctl enable sub
    systemctl status sub
    # 打印调试信息 
    echo -e "\033[32m ----------------配置信息---------------- \033[0m"
    echo -e "\033[32m api_access_token:\033[0m $api_access_token"
    echo -e "\033[32m managed_config_prefix:\033[0m $managed_config_prefix"
    echo -e "\033[32m listen:\033[0m $listen"
    echo -e "\033[32m port:\033[0m $port"
    echo -e "\033[32m 后端启动成功....... \033[0m"
    menw
    
}

menw(){
    echo -e "\033[32m -------------------菜单------------------- \033[0m"
    PS3='请选择:'
    op1="安装sub-web-modify前端"
    op2="安装SubConverter后端"
    op0="退出脚本"

    options=($op1 $op2 $op0)
    select opt in "${options[@]}"
    do
        case $opt in
            $op1)
                SubWeb "https://github.com/youshandefeiyang/sub-web-modify.git" "sub-web-modify"
                ;;
            $op2)
                SubConverter
                ;;
            $op0)
                exit 0
                break
                ;;
            *) echo 输入错误，请重新选择：;;
        esac
    done
} 
menw