#!/bin/bash

RED='\033[0;31m'
GREEN='\033[0;32m'
NC='\033[0m'

if [ "$(id -u)" != "0" ]; then
    echo -e "${RED}Этот скрипт должен быть запущен с правами суперпользователя.${NC}"
    exit 1
fi

project_directory="/opt/dashboard"
update_directory="/tmp/update-dashboard"
log_directory="$project_directory/logs"
file_list="$update_directory/upd-file.txt"

# shellcheck disable=SC2164
cd $project_directory

source $project_directory/stop.sh


if [ ! -d "$log_directory" ]; then
    mkdir -p "$log_directory"
fi

if [ "$1" == "-all" ]; then
    all_updates=true
else
    all_updates=false
fi

function update_files {
    local current_dir="$1"
    while IFS= read -r file; do
        if [ -e "$current_dir/$file" ]; then
            if [ -d "$current_dir/$file" ]; then
                mkdir -p "$project_directory/${current_dir/$update_directory/}"
                update_files "$current_dir/$file"
            elif [ -f "$current_dir/$file" ]; then
                project_file="$project_directory/${current_dir/$update_directory/}/$file"
                project_file_dir=$(dirname "$project_file")
                if [ ! -d "$project_file_dir" ]; then
                    mkdir -p "$project_file_dir"
                fi
                if [ -e "$project_file" ]; then
                    cp "$current_dir/$file" "$project_file" >> "$log_directory/update.log"
                    echo -e "${GREEN}Файл $file успешно обновлен.${NC}"
                else
                    if [ "$all_updates" == true ]; then
                        cp "$current_dir/$file" "$project_file" >> "$log_directory/update.log"
                        echo -e "${GREEN}Файл $file добавлен в проект.${NC}"
                    else
                        read -p "Файл $file не найден в проекте. Хотите добавить его? (y/n): " choice
                        if [ "$choice" == "y" ]; then
                            cp "$current_dir/$file" "$project_file" >> "$log_directory/update.log"
                            echo -e "${GREEN}Файл $file добавлен в проект.${NC}"
                        else
                            echo -e "${RED}Файл $file пропущен.${NC}"
                        fi
                    fi
                fi
            fi
        else
            echo -e "${RED}Файл $file не существует.${NC}"
        fi
    done < "$file_list"
}

update_files "$update_directory"

sed -i 's/DISABLING_TASK=.*/DISABLING_TASK=True/g' .env

flask db migrate
flask db upgrade

sed -i 's/DISABLING_TASK=.*/DISABLING_TASK=False/g' .env

source $project_directory/start.sh 80

cd ~

echo -e "${GREEN}Обновление завершено.${NC}"
