#!/bin/bash

# 查找项目根目录，通过寻找 manage.py 文件
find_project_root() {
    local current_dir="$PWD"
    while [ ! -f "$current_dir/manage.py" ]; do
        if [ "$current_dir" = "/" ]; then
            echo "未找到 Django 项目根目录，请确保在项目目录内执行脚本。"
            return 1
        fi
        current_dir=$(dirname "$current_dir")
    done
    echo "$current_dir"
    return 0
}

# 获取项目根目录
project_root=$(find_project_root)
if [ $? -ne 0 ]; then
    exit 1
fi

# 进入项目根目录
cd "$project_root"

# 执行 collectstatic 命令
echo "开始执行 collectstatic 命令..."
python3 manage.py collectstatic --noinput
if [ $? -ne 0 ]; then
    echo "collectstatic 命令执行失败。"
else
    echo "collectstatic 命令执行成功。"
fi

# 执行 makemigrations 命令
echo "开始执行 makemigrations 命令..."
python3 manage.py makemigrations
if [ $? -ne 0 ]; then
    echo "makemigrations 命令执行失败。"
else
    echo "makemigrations 命令执行成功。"
fi

# 执行 migrate 命令
echo "开始执行 migrate 命令..."
python3 manage.py migrate
if [ $? -ne 0 ]; then
    echo "migrate 命令执行失败。"
else
    echo "migrate 命令执行成功。"
fi

# 回到原始目录
cd - > /dev/null