#!/bin/bash

# TSID Client Installation Script
# Rocky Linux 8, 9, 10 version-specific dependency resolution

set -e

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

# Functions
print_status() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Detect Rocky Linux version
detect_rocky_version() {
    if [ -f /etc/rocky-release ]; then
        VERSION=$(grep -oE '[0-9]+' /etc/rocky-release | head -1)
        echo "$VERSION"
    elif [ -f /etc/redhat-release ]; then
        VERSION=$(grep -oE '[0-9]+' /etc/redhat-release | head -1)
        echo "$VERSION"
    else
        print_error "Rocky Linux/RHEL/CentOS not detected"
        exit 1
    fi
}

# Install for Rocky 8
install_rocky_8() {
    print_status "Installing TSID Client for Rocky Linux 8..."
    
    # 1. Enable EPEL and PowerTools
    print_status "Enabling EPEL and PowerTools repositories..."
    dnf install -y epel-release
    dnf config-manager --set-enabled powertools || \
    dnf config-manager --set-enabled crb || \
    print_warning "PowerTools/CRB repository not available"
    
    # 2. Install json-c library
    print_status "Installing json-c library..."
    dnf install -y json-c json-c-devel || {
        print_warning "json-c installation failed, trying alternative..."
        dnf install -y json-c || true
    }
    
    # 3. Create symbolic link for libjson-c.so.5
    print_status "Creating symbolic link for libjson-c.so.5..."
    if [ -f /usr/lib64/libjson-c.so.4 ] && [ ! -f /usr/lib64/libjson-c.so.5 ]; then
        ln -sf /usr/lib64/libjson-c.so.4 /usr/lib64/libjson-c.so.5
        print_status "Created symbolic link: libjson-c.so.5 -> libjson-c.so.4"
    else
        print_warning "libjson-c.so.5 already exists or libjson-c.so.4 not found"
    fi
    
    # 4. Update library cache
    ldconfig
    
    # 5. Add repository
    print_status "Adding TSID repository..."
    cat > /etc/yum.repos.d/tsid.repo << EOF
[tsid]
name=TSID Client Repository for Rocky Linux 8
baseurl=https://tsid-pcguard.t5online.com/yum-repo/rocky/8/x86_64/
enabled=1
gpgcheck=0
EOF
    
    # 6. Clean cache and install
    print_status "Cleaning DNF cache and installing tsid-client..."
    dnf clean all
    
    # Try normal installation first
    if dnf install -y tsid-client; then
        print_status "TSID Client installed successfully!"
    else
        print_warning "Normal installation failed, trying with dependency resolution..."
        
        # Try with --skip-broken
        if dnf install -y tsid-client --skip-broken; then
            print_status "TSID Client installed with --skip-broken option"
        else
            print_warning "DNF installation failed, trying direct RPM installation..."
            
            # Download and install RPM directly
            cd /tmp
            wget -q https://tsid-pcguard.t5online.com/yum-repo/rocky/8/x86_64/tsid-client-1.0.0-550.el8.x86_64.rpm
            
            if rpm -ivh --nodeps tsid-client-1.0.0-550.el8.x86_64.rpm; then
                print_status "TSID Client installed successfully via direct RPM!"
            else
                print_error "All installation methods failed"
                exit 1
            fi
        fi
    fi
}

# Install for Rocky 9
install_rocky_9() {
    print_status "Installing TSID Client for Rocky Linux 9..."
    
    # 1. Enable EPEL and CRB
    print_status "Enabling EPEL and CRB repositories..."
    dnf install -y epel-release
    dnf config-manager --set-enabled crb || \
    print_warning "CRB repository not available"
    
    # 2. Install dependencies
    print_status "Installing dependencies..."
    dnf install -y json-c json-c-devel
    
    # 3. Add repository
    print_status "Adding TSID repository..."
    cat > /etc/yum.repos.d/tsid.repo << EOF
[tsid]
name=TSID Client Repository for Rocky Linux 9
baseurl=https://tsid-pcguard.t5online.com/yum-repo/rocky/9/x86_64/
enabled=1
gpgcheck=0
EOF
    
    # 4. Clean cache and install
    print_status "Cleaning DNF cache and installing tsid-client..."
    dnf clean all
    
    if dnf install -y tsid-client; then
        print_status "TSID Client installed successfully!"
    else
        print_error "Installation failed"
        exit 1
    fi
}

# Install for Rocky 10
install_rocky_10() {
    print_status "Installing TSID Client for Rocky Linux 10..."
    
    # 1. Enable EPEL and CRB
    print_status "Enabling EPEL and CRB repositories..."
    dnf install -y epel-release
    dnf config-manager --set-enabled crb || \
    print_warning "CRB repository not available"
    
    # 2. Install dependencies
    print_status "Installing dependencies..."
    dnf install -y json-c json-c-devel
    
    # 3. Add repository
    print_status "Adding TSID repository..."
    cat > /etc/yum.repos.d/tsid.repo << EOF
[tsid]
name=TSID Client Repository for Rocky Linux 10
baseurl=https://tsid-pcguard.t5online.com/yum-repo/rocky/10/x86_64/
enabled=1
gpgcheck=0
EOF
    
    # 4. Clean cache and install
    print_status "Cleaning DNF cache and installing tsid-client..."
    dnf clean all
    
    if dnf install -y tsid-client; then
        print_status "TSID Client installed successfully!"
    else
        print_error "Installation failed"
        exit 1
    fi
}

# Verify installation
verify_installation() {
    print_status "Verifying installation..."
    
    if rpm -qa | grep -q tsid-client; then
        local INSTALLED_VERSION=$(rpm -qa | grep tsid-client | cut -d'-' -f3-)
        print_status "TSID Client installed: $INSTALLED_VERSION"
        
        # Check if services are available
        if systemctl list-unit-files | grep -q tsid; then
            print_status "TSID services are available"
        else
            print_warning "TSID services not found in systemd"
        fi
        
        return 0
    else
        print_error "TSID Client not found in RPM database"
        return 1
    fi
}

# Main installation logic
main() {
    print_status "TSID Client Installation Script"
    print_status "================================="
    
    # Check if running as root
    if [ "$EUID" -ne 0 ]; then
        print_error "Please run as root or with sudo"
        exit 1
    fi
    
    # Detect version
    ROCKY_VERSION=$(detect_rocky_version)
    print_status "Detected Rocky Linux $ROCKY_VERSION"
    
    # Install based on version
    case $ROCKY_VERSION in
        8)
            install_rocky_8
            ;;
        9)
            install_rocky_9
            ;;
        10)
            install_rocky_10
            ;;
        *)
            print_error "Unsupported Rocky Linux version: $ROCKY_VERSION"
            print_error "Supported versions: 8, 9, 10"
            exit 1
            ;;
    esac
    
    # Verify installation
    if verify_installation; then
        print_status "Installation completed successfully!"
        print_status ""
        
        # Run tsid-setup for configuration
        print_status "=== Configuration ==="
        print_status "Running tsid-setup to configure server code and emergency PIN..."
        print_status ""
        
        tsid-setup
        
        print_status ""
        print_status "Configuration completed!"
        print_status ""
        print_status "Next steps:"
        print_status "1. Restart display manager:"
        print_status "   - Rocky 8/9: systemctl restart lightdm"
        print_status "   - Rocky 10: systemctl restart gdm"
    else
        print_error "Installation verification failed"
        exit 1
    fi
}

# Run main function
main "$@"
