#!/bin/bash

# VTL Management CLI Tool
# Global command for managing Virtual Tape Library system

VERSION="1.0.0"

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m' # No Color

# Functions for service management
start_service() {
    local service=$1
    echo -ne "Starting ${service}... "
    if systemctl start $service 2>/dev/null; then
        echo -e "${GREEN}✓${NC}"
        return 0
    else
        echo -e "${RED}✗${NC}"
        return 1
    fi
}

stop_service() {
    local service=$1
    echo -ne "Stopping ${service}... "
    if systemctl stop $service 2>/dev/null; then
        echo -e "${GREEN}✓${NC}"
        return 0
    else
        echo -e "${RED}✗${NC}"
        return 1
    fi
}

restart_service() {
    local service=$1
    echo -ne "Restarting ${service}... "
    if systemctl restart $service 2>/dev/null; then
        echo -e "${GREEN}✓${NC}"
        return 0
    else
        echo -e "${RED}✗${NC}"
        return 1
    fi
}

# Status check function
check_status() {
    echo -e "${BOLD}${CYAN}╔════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${BOLD}${CYAN}║           VTL System Status Dashboard                      ║${NC}"
    echo -e "${BOLD}${CYAN}╚════════════════════════════════════════════════════════════╝${NC}"
    echo ""
    
    # Services Status
    echo -e "${BOLD}${BLUE}📊 Services Status:${NC}"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    # Check mhvtl
    if systemctl is-active --quiet mhvtl; then
        echo -e "  ${GREEN}●${NC} mhvtl          ${GREEN}running${NC}   (Virtual Tape Library)"
    else
        echo -e "  ${RED}●${NC} mhvtl          ${RED}stopped${NC}   (Virtual Tape Library)"
    fi
    
    # Check apache2
    if systemctl is-active --quiet apache2; then
        echo -e "  ${GREEN}●${NC} apache2        ${GREEN}running${NC}   (Web UI Server)"
    else
        echo -e "  ${RED}●${NC} apache2        ${RED}stopped${NC}   (Web UI Server)"
    fi
    
    # Check tgt
    if systemctl is-active --quiet tgt; then
        echo -e "  ${GREEN}●${NC} tgt            ${GREEN}running${NC}   (iSCSI Target)"
    else
        echo -e "  ${RED}●${NC} tgt            ${RED}stopped${NC}   (iSCSI Target)"
    fi
    
    echo ""
    
    # Components Status
    echo -e "${BOLD}${BLUE}🔧 Components:${NC}"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    # vtltape processes
    VTLTAPE_COUNT=$(pgrep -f "vtltape" | wc -l)
    if [ $VTLTAPE_COUNT -gt 0 ]; then
        echo -e "  ${GREEN}✓${NC} vtltape        ${GREEN}$VTLTAPE_COUNT processes${NC}"
    else
        echo -e "  ${RED}✗${NC} vtltape        ${RED}not running${NC}"
    fi
    
    # vtllibrary process
    if pgrep -f "vtllibrary" > /dev/null; then
        echo -e "  ${GREEN}✓${NC} vtllibrary     ${GREEN}running${NC}"
    else
        echo -e "  ${RED}✗${NC} vtllibrary     ${RED}not running${NC}"
    fi
    
    echo ""
    
    # Devices Status
    echo -e "${BOLD}${BLUE}💾 SCSI Devices:${NC}"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    # Library
    if lsscsi -g 2>/dev/null | grep -q "mediumx"; then
        LIBRARY_INFO=$(lsscsi -g 2>/dev/null | grep mediumx | awk '{print $3, $4, "-", $NF}')
        echo -e "  ${GREEN}✓${NC} Library        ${GREEN}detected${NC}  ($LIBRARY_INFO)"
    else
        echo -e "  ${RED}✗${NC} Library        ${RED}not detected${NC}"
    fi
    
    # Tape Drives
    TAPE_COUNT=$(lsscsi -g 2>/dev/null | grep "tape" | wc -l)
    if [ $TAPE_COUNT -gt 0 ]; then
        echo -e "  ${GREEN}✓${NC} Tape Drives    ${GREEN}$TAPE_COUNT detected${NC}"
        lsscsi -g 2>/dev/null | grep tape | while read line; do
            VENDOR=$(echo $line | awk '{print $3}')
            MODEL=$(echo $line | awk '{print $4}')
            DEVICE=$(echo $line | awk '{print $NF}')
            echo -e "    └─ $VENDOR $MODEL → $DEVICE"
        done
    else
        echo -e "  ${RED}✗${NC} Tape Drives    ${RED}none detected${NC}"
    fi
    
    echo ""
    
    # Network Services
    echo -e "${BOLD}${BLUE}🌐 Network Services:${NC}"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    # Web UI
    if netstat -tuln 2>/dev/null | grep -q ":80 " || ss -tuln 2>/dev/null | grep -q ":80 "; then
        echo -e "  ${GREEN}✓${NC} Web UI         ${GREEN}http://localhost/mhvtl-config/${NC}"
    else
        echo -e "  ${RED}✗${NC} Web UI         ${RED}not accessible${NC}"
    fi
    
    # iSCSI
    TARGET_COUNT=$(tgtadm --lld iscsi --mode target --op show 2>/dev/null | grep "Target" | grep -v "System" | wc -l)
    if [ $TARGET_COUNT -gt 0 ]; then
        echo -e "  ${GREEN}✓${NC} iSCSI Targets  ${GREEN}$TARGET_COUNT configured${NC}"
    else
        echo -e "  ${YELLOW}⚠${NC} iSCSI Targets  ${YELLOW}none configured${NC}"
    fi
    
    echo ""
    
    # Overall Health
    echo -e "${BOLD}${BLUE}💚 Overall Health:${NC}"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    # Calculate health score
    SCORE=0
    MAX_SCORE=6
    
    systemctl is-active --quiet mhvtl && ((SCORE++))
    systemctl is-active --quiet apache2 && ((SCORE++))
    systemctl is-active --quiet tgt && ((SCORE++))
    [ $VTLTAPE_COUNT -gt 0 ] && ((SCORE++))
    pgrep -f "vtllibrary" > /dev/null && ((SCORE++))
    lsscsi -g 2>/dev/null | grep -q "mediumx" && ((SCORE++))
    
    PERCENTAGE=$((SCORE * 100 / MAX_SCORE))
    
    if [ $PERCENTAGE -eq 100 ]; then
        echo -e "  ${GREEN}●${NC} System Status: ${GREEN}${BOLD}HEALTHY${NC} (${SCORE}/${MAX_SCORE} checks passed)"
        echo -e "  ${GREEN}✓${NC} All components operational"
    elif [ $PERCENTAGE -ge 66 ]; then
        echo -e "  ${YELLOW}●${NC} System Status: ${YELLOW}${BOLD}DEGRADED${NC} (${SCORE}/${MAX_SCORE} checks passed)"
        echo -e "  ${YELLOW}⚠${NC} Some components need attention"
    else
        echo -e "  ${RED}●${NC} System Status: ${RED}${BOLD}CRITICAL${NC} (${SCORE}/${MAX_SCORE} checks passed)"
        echo -e "  ${RED}✗${NC} Multiple components offline"
    fi
    
    echo ""
}

# List devices
list_devices() {
    echo -e "${BOLD}${CYAN}SCSI Devices:${NC}"
    echo ""
    lsscsi -g
    echo ""
}

# Show help
show_help() {
    echo -e "${BOLD}${CYAN}VTL Management Tool v${VERSION}${NC}"
    echo ""
    echo -e "${BOLD}Usage:${NC}"
    echo "  vtl <command> [options]"
    echo ""
    echo -e "${BOLD}Commands:${NC}"
    echo ""
    echo -e "  ${GREEN}status${NC}              Show VTL system status and health"
    echo -e "  ${GREEN}start${NC}               Start all VTL services"
    echo -e "  ${GREEN}stop${NC}                Stop all VTL services"
    echo -e "  ${GREEN}restart${NC}             Restart all VTL services"
    echo -e "  ${GREEN}devices${NC}             List all SCSI devices"
    echo ""
    echo -e "  ${GREEN}start-mhvtl${NC}         Start only MHVTL service"
    echo -e "  ${GREEN}stop-mhvtl${NC}          Stop only MHVTL service"
    echo -e "  ${GREEN}restart-mhvtl${NC}       Restart only MHVTL service"
    echo ""
    echo -e "  ${GREEN}start-web${NC}           Start only Web UI (Apache)"
    echo -e "  ${GREEN}stop-web${NC}            Stop only Web UI (Apache)"
    echo -e "  ${GREEN}restart-web${NC}         Restart only Web UI (Apache)"
    echo ""
    echo -e "  ${GREEN}start-iscsi${NC}         Start only iSCSI service (TGT)"
    echo -e "  ${GREEN}stop-iscsi${NC}          Stop only iSCSI service (TGT)"
    echo -e "  ${GREEN}restart-iscsi${NC}       Restart only iSCSI service (TGT)"
    echo ""
    echo -e "  ${GREEN}logs${NC} [service]      Show logs for service (mhvtl|apache2|tgt)"
    echo -e "  ${GREEN}web${NC}                 Open Web UI URL"
    echo -e "  ${GREEN}version${NC}             Show version information"
    echo -e "  ${GREEN}help${NC}                Show this help message"
    echo ""
    echo -e "${BOLD}Examples:${NC}"
    echo "  vtl status              # Check system status"
    echo "  vtl start               # Start all services"
    echo "  vtl restart-mhvtl       # Restart only MHVTL"
    echo "  vtl logs mhvtl          # View MHVTL logs"
    echo ""
}

# Show logs
show_logs() {
    local service=${1:-mhvtl}
    echo -e "${BOLD}${CYAN}Logs for ${service}:${NC}"
    echo ""
    journalctl -u $service -n 50 --no-pager
}

# Main command handler
case "${1}" in
    status)
        check_status
        ;;
    
    start)
        echo -e "${BOLD}${CYAN}Starting VTL Services...${NC}"
        echo ""
        start_service "mhvtl"
        sleep 2
        start_service "apache2"
        start_service "tgt"
        echo ""
        echo -e "${GREEN}✓${NC} All services started"
        echo ""
        sleep 2
        check_status
        ;;
    
    stop)
        echo -e "${BOLD}${CYAN}Stopping VTL Services...${NC}"
        echo ""
        stop_service "mhvtl"
        stop_service "apache2"
        stop_service "tgt"
        echo ""
        echo -e "${GREEN}✓${NC} All services stopped"
        ;;
    
    restart)
        echo -e "${BOLD}${CYAN}Restarting VTL Services...${NC}"
        echo ""
        restart_service "mhvtl"
        sleep 2
        restart_service "apache2"
        restart_service "tgt"
        echo ""
        echo -e "${GREEN}✓${NC} All services restarted"
        echo ""
        sleep 2
        check_status
        ;;
    
    start-mhvtl)
        start_service "mhvtl"
        sleep 2
        check_status
        ;;
    
    stop-mhvtl)
        stop_service "mhvtl"
        ;;
    
    restart-mhvtl)
        restart_service "mhvtl"
        sleep 2
        check_status
        ;;
    
    start-web)
        start_service "apache2"
        ;;
    
    stop-web)
        stop_service "apache2"
        ;;
    
    restart-web)
        restart_service "apache2"
        ;;
    
    start-iscsi)
        start_service "tgt"
        ;;
    
    stop-iscsi)
        stop_service "tgt"
        ;;
    
    restart-iscsi)
        restart_service "tgt"
        ;;
    
    devices)
        list_devices
        ;;
    
    logs)
        show_logs "${2}"
        ;;
    
    web)
        echo -e "${BOLD}${CYAN}Web UI URL:${NC}"
        echo ""
        echo "  http://localhost/mhvtl-config/"
        echo ""
        ;;
    
    version)
        echo -e "${BOLD}${CYAN}VTL Management Tool${NC}"
        echo "Version: ${VERSION}"
        echo "MHVTL: $(vtltape --version 2>&1 | head -1 || echo 'Not installed')"
        echo ""
        ;;
    
    help|--help|-h)
        show_help
        ;;
    
    *)
        if [ -z "$1" ]; then
            check_status
        else
            echo -e "${RED}Error: Unknown command '${1}'${NC}"
            echo ""
            echo "Run 'vtl help' for usage information"
            exit 1
        fi
        ;;
esac
