#!/bin/bash
#====================================================================
# Description: Install and configure salt-minion for Debian 12 / 安装并配置 salt-minion 用于 Debian 12
# Author: Liu YanHao
# Updated by: Zhang JinWei
# Create Time: 2024-12-26
# Last Modified: 2025-06-13
# Version: 1.1
# Usage: ./salt_install.sh <IP_ADDRESS> <SALT_ID_PREFIX>
# Example: ./salt_install.sh 192.168.1.100 web
#====================================================================
set -e

# ----------------------------------------Check System Environment / 检查系统环境----------------------------------------
function check_os() {
    # Check OS version / 检查操作系统版本
    if ! grep -q "Debian GNU/Linux 12" /etc/os-release 2>/dev/null; then
        echo -e "\e[31m脚本仅支持 Debian 12 / This script only supports Debian 12\e[0m"
        exit 1
    fi

    # Validate required parameters / 验证必需的参数
    if [[ -z "${1}" ]] || [[ -z "${2}" ]]; then
        echo -e "\e[31m请提供正确的 IP 地址和 salt_id 前缀参数 / Please provide correct IP address and salt_id prefix\e[0m"
        exit 1
    fi
}

# ----------------------------------------Install SaltStack / 安装SaltStack----------------------------------------
function install_salt() {
    # 安装salt-minion
    dpkg -l | grep -wq salt-minion || dpkg -i /root/cdninstall/pkg/salt/salt-common_3005.5+ds-1_all.deb /root/cdninstall/pkg/salt/salt-minion_3005.5+ds-1_all.deb || true

    # 修复依赖关系
    apt-get -f install -y

    # 更新源并安装salt-minion
    apt-get update
    apt-get install -y salt-minion
    
    # 配置salt-minion
    echo 'master: 103.8.215.62' >/etc/salt/minion
    echo "${2}-${1}" >/etc/salt/minion_id
    systemctl enable salt-minion && systemctl restart salt-minion

    # Check installation result / 检查安装结果
    if ! [[ $? -eq 0 ]]; then
        echo -e "\e[31mSalt minion 安装失败 / Salt minion installation failed\e[0m"
        exit 1
    fi
}

# ----------------------------------------Main Function / 主函数----------------------------------------
function main() {
    check_os "${1}" "${2}"     # Check system environment and parameters / 检查系统环境和参数
    install_salt "${1}" "${2}" # Install and configure salt-minion / 安装并配置 salt-minion
}

main "${1}" "${2}"

