#!/bin/bash
#
# Manual Deployment Fallback Script
# Purpose: Deploy manually when Gitea Actions is unavailable
#
# Usage:
#   ./scripts/manual-deploy-fallback.sh [branch]  # Deploy specific branch
#   ./scripts/manual-deploy-fallback.sh           # Deploy current branch
#

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)"
ANSIBLE_DIR="${PROJECT_ROOT}/deployment/ansible"
INVENTORY="${ANSIBLE_DIR}/inventory/production.yml"

PRODUCTION_SERVER="94.16.110.151"
REGISTRY="git.michaelschiemer.de:5000"
IMAGE="framework"
BRANCH="${1:-$(git rev-parse --abbrev-ref HEAD)}"

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

log_error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# Check prerequisites
check_prerequisites() {
    log_step "Checking prerequisites..."

    # Check if git is clean
    if [[ -n $(git status --porcelain) ]]; then
        log_error "Git working directory is not clean. Commit or stash changes first."
        exit 1
    fi

    # Check if ansible is installed
    if ! command -v ansible-playbook &> /dev/null; then
        log_error "ansible-playbook not found. Install Ansible first."
        exit 1
    fi

    # Check if docker is available
    if ! command -v docker &> /dev/null; then
        log_error "docker not found. Install Docker first."
        exit 1
    fi

    # Check SSH access to production server
    if ! ssh -i ~/.ssh/production deploy@"${PRODUCTION_SERVER}" "echo 'SSH OK'" &> /dev/null; then
        log_error "Cannot SSH to production server. Check your SSH key."
        exit 1
    fi

    log_info "Prerequisites check passed"
}

# Build Docker image locally
build_image() {
    log_step "Building Docker image for branch: ${BRANCH}"

    cd "${PROJECT_ROOT}"

    # Checkout branch
    git checkout "${BRANCH}"
    git pull origin "${BRANCH}"

    # Get commit SHA
    COMMIT_SHA=$(git rev-parse --short HEAD)
    IMAGE_TAG="${COMMIT_SHA}-$(date +%s)"

    log_info "Building image with tag: ${IMAGE_TAG}"

    # Build image
    docker build \
        --file Dockerfile.production \
        --tag "${REGISTRY}/${IMAGE}:${IMAGE_TAG}" \
        --tag "${REGISTRY}/${IMAGE}:latest" \
        --build-arg BUILD_DATE="$(date -u +'%Y-%m-%dT%H:%M:%SZ')" \
        --build-arg VCS_REF="${COMMIT_SHA}" \
        .

    log_info "Image built successfully"
}

# Push image to registry
push_image() {
    log_step "Pushing image to registry..."

    # Login to registry (prompt for password if needed)
    log_info "Logging in to registry..."
    docker login "${REGISTRY}"

    # Push image
    docker push "${REGISTRY}/${IMAGE}:${IMAGE_TAG}"
    docker push "${REGISTRY}/${IMAGE}:latest"

    log_info "Image pushed successfully"
}

# Deploy via Ansible
deploy_ansible() {
    log_step "Deploying via Ansible..."

    cd "${ANSIBLE_DIR}"

    ansible-playbook \
        -i "${INVENTORY}" \
        playbooks/deploy-update.yml \
        -e "image_tag=${IMAGE_TAG}" \
        -e "git_commit_sha=${COMMIT_SHA}"

    log_info "Ansible deployment completed"
}

# Run health checks
run_health_checks() {
    log_step "Running health checks..."

    cd "${ANSIBLE_DIR}"

    ansible-playbook \
        -i "${INVENTORY}" \
        playbooks/health-check.yml

    log_info "Health checks passed"
}

# Main deployment flow
main() {
    echo ""
    log_warn "╔════════════════════════════════════════════════════════╗"
    log_warn "║     MANUAL DEPLOYMENT FALLBACK (No Gitea Actions)     ║"
    log_warn "╚════════════════════════════════════════════════════════╝"
    echo ""

    log_info "Branch: ${BRANCH}"
    echo ""

    read -p "Continue with manual deployment? (yes/no): " -r
    if [[ ! "$REPLY" =~ ^[Yy][Ee][Ss]$ ]]; then
        log_info "Deployment cancelled"
        exit 0
    fi

    check_prerequisites
    build_image
    push_image
    deploy_ansible
    run_health_checks

    echo ""
    log_warn "╔════════════════════════════════════════════════════════╗"
    log_warn "║          MANUAL DEPLOYMENT COMPLETED                   ║"
    log_warn "╚════════════════════════════════════════════════════════╝"
    echo ""
    log_info "Deployed: ${REGISTRY}/${IMAGE}:${IMAGE_TAG}"
    log_info "Commit: ${COMMIT_SHA}"
    log_info "Branch: ${BRANCH}"
    echo ""
    log_info "Verify deployment: https://michaelschiemer.de"
    echo ""
}

main "$@"
