#!/bin/sh
# Скрипт деплоя для octopus (FIXED v7 - Correct paths and docker-compose)
LOG_FILE="/Volume1/DockerAppsData/mixapp/deploy-octopus.log"
HASH_FILE="/Volume1/DockerAppsData/mixapp/requirements-hash.txt"
DOCKER_COMPOSE_DIR="/Volume1/DockerYAML/mix"
APP_ROOT="/Volume1/DockerAppsData/mixapp/app"

echo "=== Deploy started at $(date) ===" >> "$LOG_FILE"

# 1. Git pull
echo "Step 1: Git pull..." >> "$LOG_FILE"
docker exec git-cli sh -c "cd /git/octopus && git pull" >> "$LOG_FILE" 2>&1

# 2. Вычисляем общий хеш (requirements + docker config + docker-compose.yml)
echo "Step 2: Checking for structural changes..." >> "$LOG_FILE"
NEW_HASH=$(docker exec git-cli sh -c "cd /git/octopus && cat myproject/requirements.txt docker/* docker/docker-compose.yml | md5sum" | awk '{print $1}')

OLD_HASH=""
if [ -f "$HASH_FILE" ]; then
    OLD_HASH=$(cat "$HASH_FILE")
fi

# 3. Копируем файлы приложения
echo "Step 3: Copying app files..." >> "$LOG_FILE"
rm -rf "$APP_ROOT/myproject"/*
cp -r /Volume1/DockerAppsData/git/octopus/myproject/. "$APP_ROOT/myproject/" >> "$LOG_FILE" 2>&1

rm -rf "$APP_ROOT/docker"
mkdir -p "$APP_ROOT/docker"
cp -r /Volume1/DockerAppsData/git/octopus/docker/. "$APP_ROOT/docker/" >> "$LOG_FILE" 2>&1

# 4. Обновляем docker-compose.yml (Infrastructure as Code)
echo "Step 4: Updating docker-compose.yml..." >> "$LOG_FILE"
cp /Volume1/DockerAppsData/git/octopus/docker/docker-compose.yml "$DOCKER_COMPOSE_DIR/docker-compose.yml" >> "$LOG_FILE" 2>&1

# 5. Устанавливаем права
echo "Step 5: Setting permissions..." >> "$LOG_FILE"
chown -R 1000:1000 "$APP_ROOT" >> "$LOG_FILE" 2>&1
chmod +x "$APP_ROOT/docker/entrypoint.sh" >> "$LOG_FILE" 2>&1

# Гарантируем существование media папки с правильными правами
mkdir -p /Volume1/DockerAppsData/mixapp/media >> "$LOG_FILE" 2>&1
chown -R 1000:1000 /Volume1/DockerAppsData/mixapp/media >> "$LOG_FILE" 2>&1
chown -R 1000:1000 /Volume1/DockerAppsData/mixapp/static >> "$LOG_FILE" 2>&1

# 6. Логика пересборки
cd "$DOCKER_COMPOSE_DIR"

if [ "$NEW_HASH" != "$OLD_HASH" ]; then
    echo "Step 6: Changes detected! Rebuilding ALL images..." >> "$LOG_FILE"
    docker-compose build >> "$LOG_FILE" 2>&1
    echo "$NEW_HASH" > "$HASH_FILE"
    echo "Images rebuilt successfully!" >> "$LOG_FILE"
else
    echo "Step 6: No structure changes, skipping rebuild." >> "$LOG_FILE"
fi

# 7. Полный перезапуск
echo "Step 7: Restarting ALL containers..." >> "$LOG_FILE"
docker-compose down >> "$LOG_FILE" 2>&1
docker-compose up -d >> "$LOG_FILE" 2>&1

# 8. Ждём запуска и исправляем права через docker exec (внутри контейнера от root)
echo "Step 8: Waiting for containers and fixing permissions..." >> "$LOG_FILE"
sleep 10  # Даём контейнерам время для запуска entrypoint.sh

# Исправляем права внутри контейнера (entrypoint.sh запускается от root)
docker exec mix_web chown -R appuser:appuser /app/myproject/media >> "$LOG_FILE" 2>&1
docker exec mix_web chown -R appuser:appuser /app/myproject/staticfiles >> "$LOG_FILE" 2>&1
docker exec mix_web chmod -R 777 /app/myproject/media >> "$LOG_FILE" 2>&1
echo "Permissions fixed inside container" >> "$LOG_FILE"

# Проверка
echo "Step 9: Check status..." >> "$LOG_FILE"
docker-compose ps >> "$LOG_FILE" 2>&1

echo "=== Deploy finished at $(date) ===" >> "$LOG_FILE"
