#!/bin/bash

# 设置图片数量和输出文件名
IMAGE_NUM_ALL=`ls /opt/websites/nav/assets/images/logos | wc -l`
# there are 221 logos in total, and index are from 0, so the max index is 220
# whhereas there has an avatar.jpg file in this dir, so need to subtract one
let IMAGE_NUM_ALL=IMAGE_NUM_ALL-1
IMAGE_NUM_NEEDED=`cat /opt/websites/nav/index.html | grep -E '[0-9]{1,3}.jpg' | wc -l`
if [[ $IMAGE_NUM_NEEDED -gt $IMAGE_NUM_ALL ]]; then
    alarm='Navigation:\nThere is NOT enough logos to use, please check ASAP.'
    bash /opt/scripts/alert/sendmsg.sh "$alarm"
    exit 233
fi

# 初始化数组
declare -a arr=()

# 随机选择图片名，不重复
for ((i=0; i<$IMAGE_NUM_NEEDED; i++)); do
    while true; do
        # 随机生成图片名
        RAND=$((RANDOM%IMAGE_NUM_ALL))
        IMG_NAME=$RAND.jpg

        # 判断图片名是否已经被选择过
        chosen=0
        for num in "${arr[@]}"; do
            if [ "$num" == "$IMG_NAME" ]; then
                chosen=1
                break
            fi
        done

        # 如果图片名未被选择过，则将其添加到数组中
        if [ "$chosen" -eq 0 ]; then
            arr=(${arr[@]} $IMG_NAME)
            break
        fi
    done
done

# 需要修改的文件的路径和名称
filename_origin="/opt/websites/nav/index.html"
filename_copy="/opt/websites/nav/index_copy.html"
cp $filename_origin $filename_copy

# 循环处理所有符合指定模式的行
let count=0
lineno=1
while read line; do
    # 获取文件名和路径
    oldname=$(echo $line | grep -Eo '[0-9]{1,3}.jpg')

    if [[ $oldname != '' ]]; then
        newname=${arr[$count]}
        # 替换文件名
        sed -i "${lineno}s/\/$oldname/\/$newname/" $filename_origin
        let count=count+1
    fi
    let lineno=lineno+1
done < $filename_copy

rm $filename_copy


