#!/bin/bash

# ASDA Client Uninstaller Script
# This script completely removes all components of ASDA Client to allow for a fresh installation

# Function to print colorized output
print_status() {
    local color=$1
    local message=$2
    
    case "$color" in
        "green") echo -e "\e[32m$message\e[0m" ;;
        "red") echo -e "\e[31m$message\e[0m" ;;
        "yellow") echo -e "\e[33m$message\e[0m" ;;
        "blue") echo -e "\e[34m$message\e[0m" ;;
        *) echo "$message" ;;
    esac
}

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    print_status "red" "Please run as root (use sudo)"
    exit 1
fi

print_status "blue" "ASDA Client Uninstaller"
print_status "blue" "======================="
print_status "yellow" "This script will completely remove all ASDA Client components from your system."
print_status "yellow" "This includes services, files, configuration, and user permissions."
read -p "Are you sure you want to proceed? (y/N): " confirm

if [[ "$confirm" != [Yy]* ]]; then
    print_status "yellow" "Uninstallation cancelled."
    exit 0
fi

# 1. Stop and disable ASDA client service
print_status "blue" "Stopping and disabling ASDA Client service..."
systemctl stop asda-client 2>/dev/null
systemctl disable asda-client 2>/dev/null
print_status "green" "ASDA Client service stopped and disabled."

# 2. Remove the systemd service file
print_status "blue" "Removing systemd service file..."
rm -f /etc/systemd/system/asda-client.service
systemctl daemon-reload
print_status "green" "Systemd service file removed."

# 3. Kill any running processes
print_status "blue" "Killing any running ASDA Client processes..."
pkill -f "node.*client.js" 2>/dev/null
print_status "green" "All ASDA Client processes terminated."

# 4. Remove pending 'at' jobs for unblocking IPs
print_status "blue" "Removing scheduled at jobs..."
# List and remove all at jobs, not just for asda user
if command -v atq &>/dev/null && command -v atrm &>/dev/null; then
    # Check for any at jobs containing unblock or asda
    AT_JOBS=$(atq | awk '{print $1}')
    
    if [ -n "$AT_JOBS" ]; then
        print_status "yellow" "Found scheduled jobs, checking for ASDA-related jobs..."
        
        for job in $AT_JOBS; do
            # Get the job content
            JOB_CONTENT=$(at -c $job 2>/dev/null | grep -i "unblock\|asda")
            
            if [ -n "$JOB_CONTENT" ]; then
                print_status "yellow" "Removing ASDA-related job #$job"
                atrm $job 2>/dev/null
            fi
        done
    fi
    
    # Also remove all jobs from asda user if it exists
    if id -u asda &>/dev/null; then
        for job in $(atq | grep asda | awk '{print $1}'); do
            print_status "yellow" "Removing asda user job #$job"
            atrm $job 2>/dev/null
        done
    fi
    
    print_status "green" "Scheduled jobs removed."
else
    print_status "yellow" "at command not found. Skipping at job cleanup."
fi

# 5. Remove sudo permissions
print_status "blue" "Removing sudo permissions..."
rm -f /etc/sudoers.d/asda-security
rm -f /etc/sudoers.d/asda-fail2ban
print_status "green" "Sudo permissions removed."

# 6. Remove Fail2Ban integration
print_status "blue" "Checking for ASDA Fail2Ban configuration..."
if [ -f /etc/fail2ban/action.d/asda-notify.conf ]; then
    rm -f /etc/fail2ban/action.d/asda-notify.conf
    print_status "green" "Fail2Ban action configuration removed."
fi

if [ -f /etc/fail2ban/jail.d/sshd-asda.conf ]; then
    rm -f /etc/fail2ban/jail.d/sshd-asda.conf
    print_status "green" "Fail2Ban jail configuration removed."
fi

# 7. Check and clear all Fail2Ban jails
print_status "blue" "Checking for active Fail2Ban jails..."

if command -v fail2ban-client &> /dev/null; then
    # First, ensure Fail2Ban service is running to allow jail operations
    if ! systemctl is-active fail2ban &>/dev/null; then
        print_status "yellow" "Fail2Ban service not running. Starting service temporarily..."
        systemctl start fail2ban
    fi
    
    # Get list of all jails
    JAILS=$(fail2ban-client status 2>/dev/null | grep "Jail list" | sed "s/^[^:]*:[ \t]*//g" | sed "s/,//g")
    
    if [ -n "$JAILS" ]; then
        print_status "yellow" "Found the following Fail2Ban jails: $JAILS"
        
        # Special focus on sshd jail as it's the primary one used by ASDA
        if echo "$JAILS" | grep -q "sshd"; then
            print_status "blue" "Found sshd jail, ensuring it's completely cleared..."
            fail2ban-client set sshd unbanip all
            
            # Get list of banned IPs from sshd jail
            SSHD_BANNED_IPS=$(fail2ban-client status sshd | grep "Banned IP list" | sed "s/^.*Banned IP list:[[:space:]]*//g")
            
            # If there are still banned IPs, try to unban them individually
            if [ -n "$SSHD_BANNED_IPS" ]; then
                print_status "yellow" "Some IPs still banned in sshd jail. Trying individual unbanning..."
                for IP in $SSHD_BANNED_IPS; do
                    print_status "yellow" "Unbanning IP: $IP from sshd jail"
                    fail2ban-client set sshd unbanip $IP
                done
            fi
            
            # Final check for sshd jail
            REMAINING_SSHD_IPS=$(fail2ban-client status sshd | grep "Banned IP list" | sed "s/^.*Banned IP list:[[:space:]]*//g")
            if [ -n "$REMAINING_SSHD_IPS" ]; then
                print_status "red" "Warning: Some IPs could not be unbanned from sshd: $REMAINING_SSHD_IPS"
                print_status "yellow" "Attempting to restart Fail2Ban to clear persistent bans..."
                systemctl restart fail2ban
                sleep 2
                fail2ban-client set sshd unbanip all
            else
                print_status "green" "All IPs successfully unbanned from sshd jail"
            fi
        fi
        
        # Unban all IPs from all other jails
        for jail in $JAILS; do
            if [ "$jail" != "sshd" ]; then
                print_status "blue" "Unbanning all IPs from jail: $jail"
                
                # First try with 'unbanip all' command
                fail2ban-client set $jail unbanip all
                
                # Check if IPs remain banned (for cases where 'unbanip all' doesn't work)
                BANNED_IPS=$(fail2ban-client status $jail | grep "Banned IP list" | sed "s/^.*Banned IP list:[[:space:]]*//g")
                
                if [ -n "$BANNED_IPS" ]; then
                    print_status "yellow" "Found remaining banned IPs in $jail: $BANNED_IPS"
                    print_status "blue" "Attempting to unban each IP individually..."
                    
                    for IP in $BANNED_IPS; do
                        print_status "yellow" "Unbanning IP: $IP from jail: $jail"
                        fail2ban-client set $jail unbanip $IP
                    done
                    
                    # Verify all IPs were unbanned
                    REMAINING_IPS=$(fail2ban-client status $jail | grep "Banned IP list" | sed "s/^.*Banned IP list:[[:space:]]*//g")
                    if [ -n "$REMAINING_IPS" ]; then
                        print_status "red" "Warning: Some IPs could not be unbanned from $jail: $REMAINING_IPS"
                    else
                        print_status "green" "All IPs successfully unbanned from $jail"
                    fi
                else
                    print_status "green" "All IPs unbanned from $jail"
                fi
            fi
        done
    else
        print_status "green" "No active Fail2Ban jails found."
    fi
    
    # Try to stop fail2ban to clear any persistent state
    print_status "blue" "Stopping Fail2Ban to clear any remaining state..."
    systemctl stop fail2ban
    sleep 2
    
    # Final check - if fail2ban is needed on the system, restart it
    if systemctl is-enabled fail2ban &>/dev/null; then
        print_status "blue" "Restarting Fail2Ban service (it was enabled)..."
        systemctl start fail2ban
    fi
    
else
    print_status "yellow" "fail2ban-client not found. Skipping Fail2Ban jail cleanup."
fi

# 9. Unblock any IPs that were blocked by ASDA
print_status "blue" "Checking for IPs blocked by ASDA..."
# Find any DROP rules that might have been added by ASDA
BLOCKED_IPS=$(sudo iptables -L INPUT -n | grep DROP | awk '{print $4}' | grep -v "0.0.0.0/0")

if [ -n "$BLOCKED_IPS" ]; then
    print_status "yellow" "Found potentially blocked IPs, attempting to unblock..."
    for ip in $BLOCKED_IPS; do
        sudo iptables -D INPUT -s $ip -j DROP 2>/dev/null
        print_status "green" "Unblocked IP: $ip"
    done
else
    print_status "green" "No blocked IPs found."
fi

# 10. Remove the ASDA client directory
print_status "blue" "Removing ASDA Client files..."
rm -rf /opt/asda/client
print_status "green" "ASDA Client files removed."

# 11. Ask if the user wants to remove the asda user
read -p "Do you want to remove the 'asda' user from the system? (y/N): " remove_user
if [[ "$remove_user" == [Yy]* ]]; then
    print_status "blue" "Removing asda user..."
    
    # Kill any processes owned by asda
    pkill -u asda 2>/dev/null
    
    # Remove user and home directory
    userdel -r asda 2>/dev/null
    
    # If home directory still exists, force remove it
    if [ -d /home/asda ]; then
        rm -rf /home/asda
    fi
    
    print_status "green" "User 'asda' removed."
else
    print_status "yellow" "Keeping the 'asda' user. You can remove it later with 'sudo userdel -r asda'."
fi

# 12. Remove /opt/asda directory if empty
if [ -d /opt/asda ] && [ -z "$(ls -A /opt/asda)" ]; then
    print_status "blue" "Removing empty /opt/asda directory..."
    rmdir /opt/asda
    print_status "green" "Directory removed."
fi

print_status "green" "✅ ASDA Client has been completely uninstalled from your system."
print_status "yellow" "You can now perform a fresh installation."
print_status "blue" "To reinstall, run the install.sh script from your ASDA distribution."

exit 0
