#!/bin/bash
# Auto-deployment script for shorts-maker
# This script is triggered by Gitea webhook on push

set -e

# Configuration
APP_DIR="/home/bini/shorts-maker"
LOG_FILE="/var/log/shorts-maker-deploy.log"
COMPOSE_FILE="docker-compose.yml"

# Logging function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

log "=== Deployment started ==="

# Navigate to app directory
cd "$APP_DIR" || { log "ERROR: Cannot cd to $APP_DIR"; exit 1; }

# Pull latest code
log "Pulling latest code from git..."
git fetch origin
git reset --hard origin/main
log "Git pull completed"

# Rebuild and restart containers
log "Rebuilding Docker containers..."
docker compose -f "$COMPOSE_FILE" build --no-cache

log "Restarting containers..."
docker compose -f "$COMPOSE_FILE" down
docker compose -f "$COMPOSE_FILE" up -d

# Clean up old images
log "Cleaning up old Docker images..."
docker image prune -f

log "=== Deployment completed successfully ==="

# Show running containers
docker compose -f "$COMPOSE_FILE" ps
