#!/bin/bash
# Diagnostic script for backup-database.sh permission issues
# Run this on your VPS to identify the root cause

SCRIPT="/opt/app/backend/honey-be/scripts/backup-database.sh"
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

echo "=========================================="
echo "Backup Script Permission Diagnostic"
echo "=========================================="
echo ""

# 1. File exists
echo "1. Checking if file exists..."
if [ -f "$SCRIPT" ]; then
    echo -e "   ${GREEN}✅ File exists${NC}"
else
    echo -e "   ${RED}❌ File NOT found at: $SCRIPT${NC}"
    echo "   Please verify the path."
    exit 1
fi
echo ""

# 2. File permissions
echo "2. File permissions:"
ls -la "$SCRIPT"
echo ""

# 3. Is executable
echo "3. Is file executable?"
if [ -x "$SCRIPT" ]; then
    echo -e "   ${GREEN}✅ File is executable${NC}"
else
    echo -e "   ${RED}❌ File is NOT executable${NC}"
    echo "   Fix: chmod +x $SCRIPT"
fi
echo ""

# 4. Shebang line
echo "4. Shebang line (first line):"
SHEBANG=$(head -1 "$SCRIPT")
echo "   $SHEBANG"
if [[ "$SHEBANG" == "#!/bin/bash" ]] || [[ "$SHEBANG" == "#!/usr/bin/bash" ]]; then
    echo -e "   ${GREEN}✅ Shebang looks correct${NC}"
else
    echo -e "   ${YELLOW}⚠️  Unexpected shebang${NC}"
fi
echo ""

# 5. Bash exists
echo "5. Checking if bash interpreter exists:"
if [ -f /bin/bash ]; then
    echo -e "   ${GREEN}✅ /bin/bash exists${NC}"
    /bin/bash --version | head -1
elif [ -f /usr/bin/bash ]; then
    echo -e "   ${GREEN}✅ /usr/bin/bash exists${NC}"
    /usr/bin/bash --version | head -1
else
    echo -e "   ${RED}❌ bash not found in /bin/bash or /usr/bin/bash${NC}"
    echo "   Found at: $(which bash 2>/dev/null || echo 'NOT FOUND')"
fi
echo ""

# 6. Line endings
echo "6. Checking line endings:"
FILE_TYPE=$(file "$SCRIPT")
echo "   $FILE_TYPE"
if echo "$FILE_TYPE" | grep -q "CRLF"; then
    echo -e "   ${RED}❌ File has Windows line endings (CRLF)${NC}"
    echo "   Fix: dos2unix $SCRIPT"
    echo "   Or: sed -i 's/\r$//' $SCRIPT"
elif echo "$FILE_TYPE" | grep -q "ASCII text"; then
    echo -e "   ${GREEN}✅ Line endings look correct (LF)${NC}"
else
    echo -e "   ${YELLOW}⚠️  Could not determine line endings${NC}"
fi
echo ""

# 7. Mount options
echo "7. Checking filesystem mount options:"
MOUNT_INFO=$(mount | grep -E "(/opt|/app)" || echo "Not a separate mount")
echo "   $MOUNT_INFO"
if echo "$MOUNT_INFO" | grep -q "noexec"; then
    echo -e "   ${RED}❌ Filesystem mounted with 'noexec' flag${NC}"
    echo "   This prevents script execution!"
    echo "   Fix: Remove 'noexec' from /etc/fstab and remount"
else
    echo -e "   ${GREEN}✅ No 'noexec' flag detected${NC}"
fi
echo ""

# 8. SELinux
echo "8. Checking SELinux:"
if command -v getenforce &> /dev/null; then
    SELINUX_STATUS=$(getenforce 2>/dev/null)
    echo "   Status: $SELINUX_STATUS"
    if [ "$SELINUX_STATUS" = "Enforcing" ]; then
        echo -e "   ${YELLOW}⚠️  SELinux is enforcing - may block execution${NC}"
        echo "   Check context: ls -Z $SCRIPT"
    else
        echo -e "   ${GREEN}✅ SELinux not blocking (or disabled)${NC}"
    fi
else
    echo -e "   ${GREEN}✅ SELinux not installed${NC}"
fi
echo ""

# 9. Directory permissions
echo "9. Parent directory permissions:"
DIR=$(dirname "$SCRIPT")
ls -ld "$DIR"
if [ -x "$DIR" ]; then
    echo -e "   ${GREEN}✅ Directory is executable${NC}"
else
    echo -e "   ${RED}❌ Directory is NOT executable${NC}"
    echo "   Fix: chmod +x $DIR"
fi
echo ""

# 10. Syntax check
echo "10. Checking script syntax:"
if bash -n "$SCRIPT" 2>&1; then
    echo -e "   ${GREEN}✅ Syntax is valid${NC}"
else
    echo -e "   ${RED}❌ Syntax errors found${NC}"
    bash -n "$SCRIPT"
fi
echo ""

# 11. Test execution
echo "11. Testing script execution (dry run):"
echo "   Attempting to read first 10 lines..."
if head -10 "$SCRIPT" > /dev/null 2>&1; then
    echo -e "   ${GREEN}✅ Can read script${NC}"
else
    echo -e "   ${RED}❌ Cannot read script${NC}"
fi
echo ""

# 12. Cron job check
echo "12. Checking cron configuration:"
if [ "$EUID" -eq 0 ]; then
    echo "   Root's crontab:"
    crontab -l 2>/dev/null | grep -i backup || echo "   (No backup cron job found in root's crontab)"
    echo ""
    echo "   To check cron job, run: sudo crontab -l"
else
    echo "   (Run as root to check crontab: sudo crontab -l)"
fi
echo ""

# 13. Environment check
echo "13. Checking required commands:"
REQUIRED_COMMANDS=("docker" "ssh" "gzip" "bash")
for cmd in "${REQUIRED_COMMANDS[@]}"; do
    if command -v "$cmd" &> /dev/null; then
        CMD_PATH=$(which "$cmd")
        echo -e "   ${GREEN}✅ $cmd${NC} found at: $CMD_PATH"
    else
        echo -e "   ${RED}❌ $cmd${NC} NOT found in PATH"
    fi
done
echo ""

# 14. Secret file check
echo "14. Checking secret file:"
SECRET_FILE="/run/secrets/honey-config.properties"
if [ -f "$SECRET_FILE" ]; then
    echo -e "   ${GREEN}✅ Secret file exists${NC}"
    if [ -r "$SECRET_FILE" ]; then
        echo -e "   ${GREEN}✅ Secret file is readable${NC}"
    else
        echo -e "   ${RED}❌ Secret file is NOT readable${NC}"
    fi
else
    echo -e "   ${YELLOW}⚠️  Secret file not found (script will fail at runtime)${NC}"
fi
echo ""

# Summary
echo "=========================================="
echo "Summary & Recommendations"
echo "=========================================="

ISSUES=0

if [ ! -x "$SCRIPT" ]; then
    echo -e "${RED}❌ Issue: File is not executable${NC}"
    echo "   Fix: chmod +x $SCRIPT"
    ISSUES=$((ISSUES + 1))
fi

if file "$SCRIPT" | grep -q "CRLF"; then
    echo -e "${RED}❌ Issue: Windows line endings detected${NC}"
    echo "   Fix: dos2unix $SCRIPT (or: sed -i 's/\r$//' $SCRIPT)"
    ISSUES=$((ISSUES + 1))
fi

if mount | grep -E "(/opt|/app)" | grep -q "noexec"; then
    echo -e "${RED}❌ Issue: Filesystem mounted with noexec${NC}"
    echo "   Fix: Remove noexec from /etc/fstab and remount"
    ISSUES=$((ISSUES + 1))
fi

if [ "$ISSUES" -eq 0 ]; then
    echo -e "${GREEN}✅ No obvious issues found${NC}"
    echo ""
    echo "If cron still fails, try:"
    echo "  1. Update cron to use bash explicitly:"
    echo "     0 2 * * * /bin/bash $SCRIPT >> /opt/app/logs/backup.log 2>&1"
    echo ""
    echo "  2. Check cron logs:"
    echo "     sudo journalctl -u cron | tail -50"
    echo ""
    echo "  3. Test manual execution:"
    echo "     sudo $SCRIPT --keep-local"
else
    echo ""
    echo -e "${YELLOW}Found $ISSUES issue(s) that need to be fixed.${NC}"
fi

echo ""
echo "=========================================="

