#!/bin/bash

env_file='/opt/source-code/v2ray-4.34.0/envfile'

if [[ $1 == 'start' ]]; then
    cat $env_file | grep -q 'https_proxy'
    if [[ $? -ne 0 ]]; then
        echo 'export http_proxy="http://127.0.0.1:10808"' >> $env_file
        echo 'export https_proxy="http://127.0.0.1:10809"' >> $env_file
        echo 'export all_proxy="socks://127.0.0.1:10809"' >> $env_file
        source $env_file
    else
        echo -e "\e[1;3;31mv2ray has \e[1;3;32mALREADY\e[1;3;31m been started, do nothing...\e[0m"
        exit 11
    fi
    /opt/source-code/v2ray-4.34.0/v2ray -config /opt/source-code/v2ray-4.34.0/config.json > /dev/null 2>&1 &
    echo -e "\e[1;33mNow you can surfing around~\e[0m"
elif [[ $1 == 'stop' ]]; then
    v2ray_pid=`ps -ef | grep '/opt/source-code/v2ray-4.34.0/v2ray' | grep -v grep | awk '{print $2}'`
    > $env_file
    source $env_file
    if [[ $v2ray_pid != '' ]]; then
        for vpid in $v2ray_pid; do
            kill -9 $vpid > /dev/null 2>&1
        done
        echo -e "\e[1;33mWelcome to the real world~\e[0m"
    else
        echo -e "\e[1;3;31mv2ray has \e[1;3;32mALREADY\e[1;3;31m been stopped, do nothing...\e[0m"
    fi
elif [[ $1 == 'renew' ]]; then
    read -t 60 -p "Please input valid oversea IP: " ip
    sed -i '69s/.*/            "address": "'$ip'",/' /opt/source-code/v2ray-4.34.0/config.json > /dev/null 2>&1 &
    sed -i '/azure/{n;s/.*/  Hostname '$ip'/g}' /root/.ssh/config
elif [[ $1 == 'status' ]]; then
    cat $env_file | grep -q 'https_proxy'
    is_empty=$?
    v2ray_pid=`ps -ef | grep '/opt/source-code/v2ray-4.34.0/v2ray' | grep -v grep | awk '{print $2}'`
    if [[ $v2ray_pid == '' && $is_empty -ne 0 ]]; then
        echo -e "\e[1;36mService is NOT running~\e[0m"
    elif [[ $v2ray_pid == '' && $is_empty -eq 0 ]]; then
        echo -e "\e[1;35mService is NOT running, BUT need check /opt/source-code/v2ray-4.34.0/envfile content, should be EMPTY\e[0m"
    elif [[ $v2ray_pid != '' && $is_empty -eq 0 ]]; then
        echo -e "\e[1;32mService is running~\e[0m"
    elif [[ $v2ray_pid != '' && $is_empty -ne 0 ]]; then
        echo -e "\e[1;35mService is running, BUT need check /opt/source-code/v2ray-4.34.0/envfile content, should NOT be empty~\e[0m"
    fi
elif [[ $1 == 'restart' ]]; then
    > $env_file
    echo 'export http_proxy="http://127.0.0.1:10808"' >> $env_file
    echo 'export https_proxy="http://127.0.0.1:10809"' >> $env_file
    echo 'export all_proxy="socks://127.0.0.1:10809"' >> $env_file
    v2ray_pid=`ps -ef | grep '/opt/source-code/v2ray-4.34.0/v2ray' | grep -v grep | awk '{print $2}'`
    if [[ $v2ray_pid == '' ]]; then
        /opt/source-code/v2ray-4.34.0/v2ray -config /opt/source-code/v2ray-4.34.0/config.json > /dev/null 2>&1 &
    else
        :
    fi
    source $env_file
    echo -e "\e[1;35mService restarted, dive deeper~\e[0m"
else
    echo -e "\e[1;3;31mOnly accept start|stop|renew as parameter.\e[0m"
    exit 1
fi



