#!/bin/bash
#
#***************************************************************************
# Author: liwanggui
# Email: liwanggui@163.com
# Date: 2022-12-20
# FileName: service.sh
# Description: 服务进程管理
# Copyright (C): 2022 All rights reserved
#***************************************************************************
#

# --- function for logs
function info() {
    echo -e "\033[0;34m$(date +'%F %T') - INFO -\033[0m $@"
}

function error() {
    echo -e "\033[0;31m$(date +'%F %T') - ERROR -\033[0m $@"
}

function warn() {
    echo -e "\033[0;33m$(date +'%F %T') - WARN -\033[0m $@"
}

# 获取脚本所在目录
script_file="$(readlink -f $0)"
current_path="$(dirname ${script_file})"
service_path="${current_path}/systemd"
service_list=()

# service 文件存放路径
systemd_path="/usr/lib/systemd/system"

# --- function for service manage
function get_service_list () {
    [ -d $service_path ] || {
        error "路径: $service_path 不存在,请检查后重试!"
        exit 1
    }

    for service in $(cd $service_path; ls *.service); do
        service_list+=($service) 
    done
}


function operation () {
    local action=$1
    local service=$2
    if [ -z ${service} ]; then
        error "缺少必要的参数 (服务名)"
        exit 1
    fi
    info "${action} ${service}"
    systemctl ${action} ${service}
}

function operation_all () {
    local action=$1
    for service in ${service_list[@]}; do
        operation ${action} ${service}
    done
}

function update_service () {
    local service_file="${service_path}/$1"
    local sys_service_file="${systemd_path}/$1"
    local service_file_md5sum=$(mktemp)
   
    local editor=$(type -P vim || type -P vi) # 优先使用 vim 

    if [ ! -f $service_file ] && [ ! -f $sys_service_file ];then
         error "文件 $service_file 和 $sys_service_file 都不存在, 请检查后重试!"
         exit 1
    fi

    if [ ! -f $service_file ]; then
       warn "文件 $service_file 不存在, 将从 $sys_service_file 复制一份" 
       /bin/cp -f $sys_service_file $service_file
    fi

    md5sum $service_file > $service_file_md5sum

    if ! sed "s|$service_path|$systemd_path|" $service_file_md5sum | md5sum -c &>/dev/null; then
        warn "文件 $service_file 与 $sys_service_file 内容不一致"
        warn "将 $service_file 内容替换为 $sys_service_file"
        /bin/cp -f $sys_service_file $service_file
        sleep 2
    fi

    $editor $service_file 
    if md5sum -c $service_file_md5sum &>/dev/null; then
        info "文件 $service_file 无变化"
        /bin/rm -f $service_file_md5sum
        return
    fi

    /bin/rm -f $service_file_md5sum
    info "您更新了 $service_file"
    info "同步更新 $sys_service_file" 
    /bin/cp -f $service_file $sys_service_file
    # 重载 systemd 服务单元
    systemctl daemon-reload
    info "更新完成, 重启后生效, 命令如下:"
    info ">>> systemctl restart $(basename $service_file)"
}

function upgrade() {
    local tmpfile=$(mktemp)
    local remote_url="https://dl.zrshuiwu.com/scripts/service.sh"
    if ! curl -sfL $remote_url -o $tmpfile; then
		error "脚本升级失败，获取远程文件失败 $remote_url"
        exit 1
    fi

	/bin/mv -f $tmpfile $script_file
    info "脚本升级完成 $script_file"
}

function help_menu() {
    cat<<EOF
Usage: 
    $(basename "$0") command

COMMANDS:
   status           查看服务状态
   start            启动服务进程
   stop             停止服务进程
   restart          重启服务进程
   update           更新服务配置
   upgrade          升级脚本

EOF
    exit 1
}

function run() {
    local action=$1
    local allsrv

    get_service_list

    if [[ "$action" != "update" ]]; then
        allsrv="ALL"
    fi
    
    echo -e "## 请选择你要操作的服务 ##"
    select srv in ${service_list[@]} $allsrv; do
        if [[ -n $srv ]]; then
            break
        fi
    done

    if [[ "$action" == "update" ]];then
         update_service $srv
         return 
    fi

    if [[ $srv == 'ALL' ]]; then
        operation_all ${action}
    else
        operation ${action} $srv
    fi
}

function main() {
    case ${1} in
        'start')
            run start
            ;;
        'stop')
            run stop
            ;;
        'status')
            run status
            ;;
        'restart')
            run restart
            ;;
        'update')
            run update
            ;;
        'upgrade')
            upgrade
            ;;
        *)
            help_menu
            ;;
    esac
}

[ -d ${current_path}/systemd ] || {
    error "在 ${current_path} 路径下找不到 'systemd' 目录，请将脚本放到正确的目录下，再重试！"
    exit 1
}

if [ $(id -u) -eq 0 ]; then
    main $@
else 
    exec sudo /bin/bash $0 $@
fi

