#!/usr/bin/env bash
#
# remove-release.sh - Remove old distribution release from repository
#
# Usage: remove-release.sh <codename> [backup]
#
# Examples:
#   remove-release.sh bullseye yes
#   remove-release.sh jammy no
#

set -e
set -o pipefail

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m'

CODENAME=$1
BACKUP=${2:-yes}  # yes/no

if [ -z "$CODENAME" ]; then
    cat <<EOF
Usage: $0 <codename> [backup]

Remove old distribution release from repository.

Arguments:
  <codename>  Distribution codename to remove (e.g., bullseye, jammy)
  [backup]    Create backup before removal (yes/no, default: yes)

Examples:
  $0 bullseye yes      # Remove with backup
  $0 jammy no          # Remove without backup

This will:
  1. Check repository activity
  2. Create backup (if requested)
  3. Delete all repositories for codename
  4. Clean up files and directories
  5. Show next steps

WARNING: This is destructive and cannot be undone (unless backed up)!

EOF
    exit 1
fi

echo -e "${RED}=== Removing release: $CODENAME ===${NC}"
echo ""

# Проверка активности
echo -e "${YELLOW}→ Checking activity...${NC}"
activity=$(sudo grep "/$CODENAME/" /var/log/nginx/repo-access.log* 2>/dev/null | wc -l || echo "0")
# Remove any whitespace/newlines
activity=$(echo "$activity" | tr -d '[:space:]')
echo -e "  Activity in logs: ${activity} requests"

if [ "$activity" -gt 100 ]; then
    echo -e "${RED}⚠️  WARNING: Codename $CODENAME has $activity requests in logs${NC}"
    read -p "Continue anyway? (yes/no): " cont
    [ "$cont" = "yes" ] || exit 1
fi

# Список репозиториев
echo ""
echo -e "${YELLOW}→ Repositories to delete:${NC}"
if ! debrepomanager list --codename "$CODENAME" 2>/dev/null; then
    echo "No repositories found for $CODENAME"
fi
echo ""

# Подтверждение
echo -e "${RED}WARNING: This will DELETE all data for $CODENAME${NC}"
read -p "Type '$CODENAME' to confirm deletion: " confirm_text
if [ "$confirm_text" != "$CODENAME" ]; then
    echo "Aborted"
    exit 1
fi

# Создать backup
if [ "$BACKUP" = "yes" ]; then
    BACKUP_FILE="/backup/repo-${CODENAME}-$(date +%Y%m%d_%H%M%S).tar.gz"
    echo ""
    echo -e "${YELLOW}→ Creating backup: $BACKUP_FILE${NC}"
    sudo mkdir -p /backup
    
    # Поддержка разных путей для aptly root
    APTLY_PATHS="/srv/aptly/$CODENAME/ /opt/repo/$CODENAME/"
    
    sudo tar czf "$BACKUP_FILE" \
        /opt/repo/public/$CODENAME/ \
        /opt/repo/public/dists/$CODENAME/ \
        $APTLY_PATHS \
        2>/dev/null || echo -e "${YELLOW}⚠️  Some paths not found (ok if already removed)${NC}"
    if [ -f "$BACKUP_FILE" ]; then
        size=$(du -h "$BACKUP_FILE" | cut -f1)
        echo -e "${GREEN}✓ Backup created: $BACKUP_FILE ($size)${NC}"
    fi
fi

# Удалить репозитории через debrepomanager
echo ""
echo -e "${YELLOW}→ Deleting repositories...${NC}"

# Get list of repositories (format: component-codename, one per line, skip headers)
repo_list=$(debrepomanager list --codename "$CODENAME" 2>/dev/null | \
    grep -v "^Repositories for" | \
    grep -v "^Total:" | \
    grep -v "^$" | \
    grep -v "^  (none)" | \
    sed 's/^  //' || echo "")

deleted_count=0
if [ -n "$repo_list" ]; then
    for repo_name in $repo_list; do
        # Extract component from repo name (format: {component}-{codename})
        component="${repo_name%-${CODENAME}}"
        
        echo -e "  Deleting ${CODENAME}/${component}..."
        if debrepomanager delete-repo --codename "$CODENAME" --component "$component" --yes >/dev/null 2>&1; then
            echo -e "  ${GREEN}✓ Deleted${NC}"
            ((deleted_count++))
        else
            echo -e "  ${YELLOW}⚠️  Failed (may not exist)${NC}"
        fi
    done
    echo -e "${GREEN}✓ Deleted $deleted_count repositories${NC}"
else
    echo "  No repositories found"
fi

# Очистить файлы вручную (на случай если debrepomanager не удалил)
echo ""
echo -e "${YELLOW}→ Cleaning up files...${NC}"

# Aptly roots (поддержка разных путей)
for path in "/srv/aptly/$CODENAME" "/opt/repo/$CODENAME"; do
    if [ -d "$path" ]; then
        # Try without sudo first (for Docker), then with sudo (for production)
        if rm -rf "$path/" 2>/dev/null; then
            echo -e "  ${GREEN}✓ Removed $path/${NC}"
        elif command -v sudo >/dev/null 2>&1 && sudo rm -rf "$path/" 2>/dev/null; then
            echo -e "  ${GREEN}✓ Removed $path/ (with sudo)${NC}"
        else
            echo -e "  ${YELLOW}⚠️  Failed to remove $path/${NC}"
        fi
    fi
done

# Published files
if [ -d "/opt/repo/public/$CODENAME" ]; then
    if rm -rf "/opt/repo/public/$CODENAME/" 2>/dev/null; then
        echo -e "  ${GREEN}✓ Removed /opt/repo/public/$CODENAME/${NC}"
    elif command -v sudo >/dev/null 2>&1 && sudo rm -rf "/opt/repo/public/$CODENAME/" 2>/dev/null; then
        echo -e "  ${GREEN}✓ Removed /opt/repo/public/$CODENAME/ (with sudo)${NC}"
    else
        echo -e "  ${YELLOW}⚠️  Failed to remove /opt/repo/public/$CODENAME/${NC}"
    fi
fi

# Dual format symlinks
if [ -d "/opt/repo/public/dists/$CODENAME" ]; then
    if rm -rf "/opt/repo/public/dists/$CODENAME/" 2>/dev/null; then
        echo -e "  ${GREEN}✓ Removed /opt/repo/public/dists/$CODENAME/${NC}"
    elif command -v sudo >/dev/null 2>&1 && sudo rm -rf "/opt/repo/public/dists/$CODENAME/" 2>/dev/null; then
        echo -e "  ${GREEN}✓ Removed /opt/repo/public/dists/$CODENAME/ (with sudo)${NC}"
    else
        echo -e "  ${YELLOW}⚠️  Failed to remove /opt/repo/public/dists/$CODENAME/${NC}"
    fi
fi

# Обновить nginx конфигурацию codenames
echo ""
echo -e "${YELLOW}→ Updating nginx codenames configuration...${NC}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ -x "$SCRIPT_DIR/update-nginx-codenames.sh" ]; then
    if "$SCRIPT_DIR/update-nginx-codenames.sh" 2>&1 | grep -q "Configuration updated"; then
        echo -e "${GREEN}✓ Nginx codenames config updated${NC}"
    else
        echo -e "${YELLOW}⚠️  Failed to update nginx config (non-critical)${NC}"
        echo "  Run manually: ./scripts/update-nginx-codenames.sh"
    fi
else
    echo -e "${YELLOW}⚠️  update-nginx-codenames.sh not found (skipped)${NC}"
fi

echo ""
echo -e "${GREEN}=== $CODENAME removed successfully ===${NC}"
echo ""
echo -e "${BLUE}Next steps:${NC}"
echo ""
echo "1. Reload nginx (codenames already updated):"
echo "   sudo systemctl reload nginx"
echo ""
echo "2. Update client documentation"
echo ""
echo "3. Send EOL notification to users"
if [ "$BACKUP" = "yes" ] && [ -n "$BACKUP_FILE" ]; then
    echo ""
    echo "4. Backup saved to: $BACKUP_FILE"
    echo "   Restore with: sudo tar xzf $BACKUP_FILE -C /"
fi
echo ""
echo "Note: Nginx codenames config auto-updated at:"
echo "      /etc/nginx/conf.d/repo-codenames.conf"

