#!/bin/bash
# 生成新的部署验证码
# 用法: ./generate-code.sh

DATA_DIR="/var/lib/alphamarket"
CODES_FILE="$DATA_DIR/codes.json"

# 确保目录存在
mkdir -p "$DATA_DIR"

# 生成24位复杂验证码
CHARS="ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789"
CODE=""
for i in {1..24}; do
    INDEX=$((RANDOM % ${#CHARS}))
    CODE="${CODE}${CHARS:$INDEX:1}"
done

# 创建 JSON 结构
TIMESTAMP=$(date +%s)
if [ -f "$CODES_FILE" ]; then
    # 追加到现有文件
    TMP_FILE=$(mktemp)
    jq --arg code "$CODE" --argjson ts "$TIMESTAMP" '.[$code] = {"created": $ts}' "$CODES_FILE" > "$TMP_FILE"
    mv "$TMP_FILE" "$CODES_FILE"
else
    # 创建新文件
    echo "{\"$CODE\": {\"created\": $TIMESTAMP}}" > "$CODES_FILE"
fi

echo ""
echo "=================================="
echo "  新的部署验证码已生成"
echo "=================================="
echo ""
echo "验证码:"
echo "$CODE"
echo ""
echo "有效期: 1小时"
echo "使用次数: 仅限一次，用完即失效"
echo ""
echo "生成时间: $(date '+%Y-%m-%d %H:%M:%S')"
echo "过期时间: $(date -d '+1 hour' '+%Y-%m-%d %H:%M:%S')"
echo ""
echo "=================================="
