#!/bin/bash
# 移动云 ECS 限制解除脚本（在 VPS 上以 root 执行）
# 用法: bash ecloud-unlock.sh -y

set -euo pipefail
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; BLUE='\033[0;34m'; NC='\033[0m'
AUTO=false; [[ "${1:-}" == "-y" || "${1:-}" == "--yes" ]] && AUTO=true
[[ "$(id -u)" -ne 0 ]] && { echo -e "${RED}请使用 root 执行${NC}"; exit 1; }
BACKUP_DIR="/root/ecloud_unlock_backup_$(date +%Y%m%d_%H%M%S)"
LOG_FILE="${BACKUP_DIR}/unlock.log"
mkdir -p "${BACKUP_DIR}"; exec > >(tee -a "${LOG_FILE}") 2>&1
echo -e "${BLUE}===== 移动云限制解除 =====${NC}"
for u in multi-queue-ecloud.service ecloud-monitor.service cloud-monitor.service cmss-agent.service uniagent.service; do
  systemctl list-unit-files "$u" &>/dev/null || continue
  systemctl stop "$u" 2>/dev/null || true; systemctl disable "$u" 2>/dev/null || true; systemctl mask "$u" 2>/dev/null || true
  echo -e "${GREEN}已 mask: $u${NC}"
done
systemctl list-unit-files --no-pager --no-legend 2>/dev/null | awk '{print $1}' | grep -iE 'ecloud|cmss|cloud-monitor|uniagent' | grep '\.service$' | while read -r u; do
  systemctl stop "$u" 2>/dev/null || true; systemctl disable "$u" 2>/dev/null || true; systemctl mask "$u" 2>/dev/null || true
  echo -e "${GREEN}已 mask: $u${NC}"
done
for f in /etc/motd /etc/issue /etc/issue.net; do [[ -f "$f" ]] && cp -a "$f" "${BACKUP_DIR}/$(basename "$f").bak"; done
: > /etc/motd; : > /etc/issue.net; [[ -f /etc/issue ]] && echo "" > /etc/issue
if systemctl list-unit-files auditd.service &>/dev/null; then
  if $AUTO || [[ "$(read -rp '停止 auditd? (y/N): ' c; echo $c)" =~ ^[Yy]$ ]]; then
    systemctl stop auditd 2>/dev/null || true; systemctl disable auditd 2>/dev/null || true
  fi
fi
cat > /etc/sysctl.d/99-ecloud-unlock.conf <<'EOF'
fs.file-max = 1048576
net.core.somaxconn = 65535
net.ipv4.ip_local_port_range = 1024 65535
EOF
sysctl -p /etc/sysctl.d/99-ecloud-unlock.conf 2>/dev/null || true
echo "完成，日志: ${LOG_FILE}"
