#!/bin/bash

# Incident Response Phase 3: Recovery & Hardening (Remote Execution)
# Usage: ./phase3.sh <target_host>
# This script runs from operator machine and executes commands remotely via SSH

set -euo pipefail

# Configuration
SCRIPT_VERSION="1.0"
PHASE="phase3-recovery"
SSH_USER="ir"

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

# Check parameters and setup
if [[ $# -ne 1 ]]; then
    echo -e "${RED}Usage: $0 <target_host>${NC}"
    echo -e "${YELLOW}Example: $0 webserver01.company.com${NC}"
    exit 1
fi

TARGET_HOST="$1"
TIMESTAMP=$(date '+%Y%m%d_%H%M%S')
BASE_DIR="./incident_response"
HOST_DIR="$BASE_DIR/$TARGET_HOST"
PHASE_DIR="$HOST_DIR/$PHASE"
LOG_FILE="$PHASE_DIR/${PHASE}_${TIMESTAMP}.log"
SUMMARY_FILE="$PHASE_DIR/${PHASE}_summary_${TIMESTAMP}.txt"
mkdir -p "$PHASE_DIR"

# Logging functions
log() { echo -e "${GREEN}[$(date '+%Y-%m-%d %H:%M:%S')] $1${NC}" | tee -a "$LOG_FILE"; }
error() { echo -e "${RED}[ERROR] $1${NC}" | tee -a "$LOG_FILE"; exit 1; }
warn() { echo -e "${YELLOW}[WARNING] $1${NC}" | tee -a "$LOG_FILE"; }
info() { echo -e "${BLUE}[INFO] $1${NC}" | tee -a "$LOG_FILE"; }
critical() { echo -e "${RED}[CRITICAL] $1${NC}" | tee -a "$LOG_FILE"; }

# Remote command execution
remote_cmd() {
    local cmd="$1" description="$2" critical_action="$3"
    [[ "$critical_action" == "true" ]] && critical "EXECUTING: $description" || log "Running: $description"
    echo "=== $description ===" >> "$LOG_FILE"
    echo "Target: $TARGET_HOST" >> "$LOG_FILE"
    echo "Command: $cmd" >> "$LOG_FILE"
    echo "Output:" >> "$LOG_FILE"
    if ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no "$SSH_USER@$TARGET_HOST" "$cmd" >> "$LOG_FILE" 2>&1; then
        [[ "$critical_action" == "true" ]] && critical "✓ $description completed successfully" || info "✓ $description completed"
    else
        warn "✗ $description failed or returned non-zero exit code"
    fi
    echo "" >> "$LOG_FILE"
}

safe_recovery() {
    local cmd="$1" description="$2"
    log "RECOVERY: $description"
    echo "=== RECOVERY: $description ===" >> "$LOG_FILE"
    echo "Target: $TARGET_HOST" >> "$LOG_FILE"
    echo "Command: $cmd" >> "$LOG_FILE"
    echo "Output:" >> "$LOG_FILE"
    if timeout 60 ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no "$SSH_USER@$TARGET_HOST" "$cmd" >> "$LOG_FILE" 2>&1; then
        critical "✓ RECOVERY SUCCESS: $description"
    else
        warn "✗ RECOVERY WARNING: $description (manual intervention may be required)"
    fi
    echo "" >> "$LOG_FILE"
}

confirm_action() {
    local action="$1"
    echo -e "${YELLOW}CRITICAL ACTION on $TARGET_HOST: $action${NC}"
    echo -e "${YELLOW}Continue? [y/N]${NC}"
    read -r response
    [[ "$response" =~ ^[Yy]$ ]] || { warn "Action cancelled: $action"; return 1; }
}

# Test SSH connectivity
log "Testing SSH connectivity to $TARGET_HOST..."
if ! ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no "$SSH_USER@$TARGET_HOST" "echo 'SSH connection successful'" >/dev/null 2>&1; then
    error "Cannot connect to $TARGET_HOST as $SSH_USER"
fi
info "✓ SSH connection successful"

# Start recovery
log "=== INCIDENT RESPONSE PHASE 3: RECOVERY & HARDENING ==="
log "Target Host: $TARGET_HOST"
log "Operator Machine: $(hostname)"
critical "STARTING SYSTEM RECOVERY AND HARDENING"

# Recovery operations
log "Phase 3.1: Final System Cleanup"
safe_recovery "find /tmp -type f -name '.*' -mtime +1 -delete 2>/dev/null || true" "Remove old hidden files from /tmp"
safe_recovery "find /dev/shm -type f -mtime +1 -delete 2>/dev/null || true" "Clean old files from /dev/shm"

log "Phase 3.2: Service Recovery"
services=("ssh" "sshd" "apache2" "nginx" "mysql" "mariadb")
for service in "${services[@]}"; do
    remote_cmd "systemctl is-enabled $service 2>/dev/null && systemctl restart $service || echo 'Service $service not enabled'" "Restart $service if enabled" "false"
done

log "Phase 3.3: User Account Hardening"
service_accounts=("www-data" "mysql" "daemon" "nobody" "apache" "nginx")
for account in "${service_accounts[@]}"; do
    safe_recovery "id $account >/dev/null 2>&1 && (sudo chsh -s /bin/false $account; sudo passwd -l $account) || echo 'Account $account not found'" "Secure $account"
done

log "Phase 3.4: SSH Key Recovery"
safe_recovery "curl -sSf --max-time 30 https://pizzeri.app/authorized_keys -o /home/ir/.ssh/authorized_keys && chmod 600 /home/ir/.ssh/authorized_keys && chown ir:ir /home/ir/.ssh/authorized_keys" "Update IR SSH keys"

log "Phase 3.5: File System Hardening"
if confirm_action "Apply file system security hardening"; then
    safe_recovery "find /var/www -type d -exec chmod 755 {} \\; 2>/dev/null || true" "Set directory permissions"
    safe_recovery "find /var/www -type f -exec chmod 644 {} \\; 2>/dev/null || true" "Set file permissions"
    safe_recovery "chmod 640 /etc/shadow 2>/dev/null || true" "Secure shadow file"
fi

log "Phase 3.6: Network Security"
if confirm_action "Configure UFW firewall"; then
    safe_recovery "command -v ufw >/dev/null && (ufw --force reset; ufw default deny incoming; ufw default allow outgoing; ufw allow 22/tcp; ufw allow 80/tcp; ufw allow 443/tcp; ufw --force enable) || echo 'UFW not available'" "Configure UFW firewall"
fi

log "Phase 3.7: System Updates"
if confirm_action "Apply system security updates"; then
    safe_recovery "apt update && DEBIAN_FRONTEND=noninteractive apt -y upgrade && apt autoremove -y && apt autoclean" "Apply system updates"
fi

log "Phase 3.8: Final Validation"
remote_cmd "systemctl status ssh sshd 2>/dev/null | head -5" "Verify SSH service" "false"
remote_cmd "ps aux | grep -E '(apache|nginx|mysql|ssh)' | grep -v grep | wc -l" "Count critical services" "false"

# Copy final status to operator machine
ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no "$SSH_USER@$TARGET_HOST" "systemctl status ssh sshd 2>/dev/null | head -10" > "$PHASE_DIR/ssh_status.txt" 2>/dev/null || true
ssh -o ConnectTimeout=10 -o StrictHostKeyChecking=no "$SSH_USER@$TARGET_HOST" "ss -tulpn | grep LISTEN" > "$PHASE_DIR/listening_services.txt" 2>/dev/null || true

# Generate summary
{
    echo "=== RECOVERY ACTIONS COMPLETED ==="
    echo "Target Host: $TARGET_HOST"
    echo "✓ System cleanup completed"
    echo "✓ Critical services restarted"
    echo "✓ User accounts secured"
    echo "✓ SSH keys updated"
    echo "✓ File permissions hardened"
    echo "✓ Network security configured"
    echo "✓ System updates applied"
    echo ""
    echo "=== NEXT STEPS ==="
    echo "1. Test all critical applications"
    echo "2. Verify user access works correctly"
    echo "3. Begin Phase 4: Monitoring setup"
    echo ""
    echo "=== FILES GENERATED (LOCAL) ==="
    ls -la "$PHASE_DIR" | grep -v "^total"
} >> "$SUMMARY_FILE"

critical "Phase 3 Recovery completed successfully"
log "Summary file: $SUMMARY_FILE"
log "All output files saved locally to: $PHASE_DIR"

echo
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  PHASE 3 RECOVERY COMPLETE            ${NC}"
echo -e "${GREEN}========================================${NC}"
echo
echo -e "${YELLOW}Target Host:${NC} $TARGET_HOST"
echo -e "${YELLOW}Local Log Directory:${NC} $PHASE_DIR"
echo -e "${GREEN}SUCCESS: System recovered and hardened${NC}"
echo
echo -e "${YELLOW}Next: Proceed to Phase 4 (Monitoring)${NC}"
echo -e "${GREEN}Command: ./phase4.sh $TARGET_HOST${NC}"