#!/bin/bash

# 🎬 Plex Media Server Management Script
# A sexy, modern script for managing Plex Media Server with style
# Author: acedanger
# Version: 2.0

set -euo pipefail

# 🎨 Color definitions for sexy output
readonly RED='\033[0;31m'
readonly GREEN='\033[0;32m'
readonly YELLOW='\033[1;33m'
readonly BLUE='\033[0;34m'
readonly PURPLE='\033[0;35m'
readonly CYAN='\033[0;36m'
readonly WHITE='\033[1;37m'
readonly BOLD='\033[1m'
readonly DIM='\033[2m'
readonly RESET='\033[0m'

# 🔧 Configuration
readonly PLEX_SERVICE="plexmediaserver"
readonly SCRIPT_NAME="$(basename "$0")"
readonly PLEX_WEB_URL="http://localhost:32400/web"

# 🎭 Unicode symbols for fancy output
readonly CHECKMARK="✅"
readonly CROSS="❌"
readonly ROCKET="🚀"
readonly STOP_SIGN="🛑"
readonly RECYCLE="♻️"
readonly INFO="ℹ️"
readonly HOURGLASS="⏳"
readonly SPARKLES="✨"

# 📊 Function to print fancy headers
print_header() {
    echo -e "\n${PURPLE}${BOLD}╔══════════════════════════════════════════════════════════════╗${RESET}"
    echo -e "${PURPLE}${BOLD}║                    ${SPARKLES} PLEX MEDIA SERVER ${SPARKLES}                   ║${RESET}"
    echo -e "${PURPLE}${BOLD}╚══════════════════════════════════════════════════════════════╝${RESET}\n"
}

# 🎉 Function to print completion footer
print_footer() {
    echo -e "\n${DIM}${CYAN}╰─── Operation completed ${SPARKLES} ───╯${RESET}\n"
}

# 🎯 Function to print status with style
print_status() {
    local status="$1"
    local message="$2"
    local color="$3"
    echo -e "${color}${BOLD}[${status}]${RESET} ${message}"
}

# ⏱️ Function to show loading animation
show_loading() {
    local message="$1"
    local pid="$2"
    local spin='-\|/'
    local i=0
    
    echo -ne "${CYAN}${HOURGLASS} ${message}${RESET}"
    while kill -0 "$pid" 2>/dev/null; do
        i=$(( (i+1) %4 ))
        printf "\r${CYAN}${HOURGLASS} ${message} ${spin:$i:1}${RESET}"
        sleep 0.1
    done
    printf "\r${CYAN}${HOURGLASS} ${message} ${CHECKMARK}${RESET}\n"
}

# 🚀 Enhanced start function
start_plex() {
    print_status "${ROCKET}" "Starting Plex Media Server..." "${GREEN}"
    
    if systemctl is-active --quiet "$PLEX_SERVICE"; then
        print_status "${INFO}" "Plex is already running!" "${YELLOW}"
        show_detailed_status
        return 0
    fi
    
    sudo systemctl start "$PLEX_SERVICE" &
    local pid=$!
    show_loading "Initializing Plex Media Server" $pid
    wait $pid
    
    sleep 2  # Give it a moment to fully start
    
    if systemctl is-active --quiet "$PLEX_SERVICE"; then
        print_status "${CHECKMARK}" "Plex Media Server started successfully!" "${GREEN}"
        echo -e "${DIM}${CYAN}Access your server at: ${WHITE}${PLEX_WEB_URL}${RESET}"
        print_footer
    else
        print_status "${CROSS}" "Failed to start Plex Media Server!" "${RED}"
        return 1
    fi
}

# 🛑 Enhanced stop function
stop_plex() {
    print_status "${STOP_SIGN}" "Stopping Plex Media Server..." "${YELLOW}"
    
    if ! systemctl is-active --quiet "$PLEX_SERVICE"; then
        print_status "${INFO}" "Plex is already stopped!" "${YELLOW}"
        return 0
    fi
    
    sudo systemctl stop "$PLEX_SERVICE" &
    local pid=$!
    show_loading "Gracefully shutting down Plex" $pid
    wait $pid
    
    if ! systemctl is-active --quiet "$PLEX_SERVICE"; then
        print_status "${CHECKMARK}" "Plex Media Server stopped successfully!" "${GREEN}"
        print_footer
    else
        print_status "${CROSS}" "Failed to stop Plex Media Server!" "${RED}"
        return 1
    fi
}

# ♻️ Enhanced restart function
restart_plex() {
    print_status "${RECYCLE}" "Restarting Plex Media Server..." "${BLUE}"
    
    if systemctl is-active --quiet "$PLEX_SERVICE"; then
        stop_plex
        echo ""
    fi
    
    start_plex
}

# 📊 Enhanced status function with detailed info
show_detailed_status() {
    local service_status
    service_status=$(systemctl is-active "$PLEX_SERVICE" 2>/dev/null || echo "inactive")
    
    echo -e "\n${BOLD}${BLUE}╔══════════════════════════════════════════════════════════════╗${RESET}"
    echo -e "${BOLD}${BLUE}║                        SERVICE STATUS                        ║${RESET}"
    echo -e "${BOLD}${BLUE}╚══════════════════════════════════════════════════════════════╝${RESET}"
    
    case "$service_status" in
        "active")
            print_status "${CHECKMARK}" "Service Status: ${GREEN}${BOLD}ACTIVE${RESET}" "${GREEN}"
            
            # Get additional info
            local uptime
            uptime=$(systemctl show "$PLEX_SERVICE" --property=ActiveEnterTimestamp --value | xargs -I {} date -d {} "+%Y-%m-%d %H:%M:%S" 2>/dev/null || echo "Unknown")
            
            local memory_usage
            memory_usage=$(systemctl show "$PLEX_SERVICE" --property=MemoryCurrent --value 2>/dev/null || echo "0")
            if [[ "$memory_usage" != "0" ]] && [[ "$memory_usage" =~ ^[0-9]+$ ]]; then
                memory_usage="$(( memory_usage / 1024 / 1024 )) MB"
            else
                memory_usage="Unknown"
            fi
            
            echo -e "${DIM}${CYAN}   Started: ${WHITE}${uptime}${RESET}"
            echo -e "${DIM}${CYAN}   Memory Usage: ${WHITE}${memory_usage}${RESET}"
            echo -e "${DIM}${CYAN}   Web Interface: ${WHITE}${PLEX_WEB_URL}${RESET}"
            echo -e "${DIM}${CYAN}   Service Name: ${WHITE}${PLEX_SERVICE}${RESET}"
            ;;
        "inactive")
            print_status "${CROSS}" "Service Status: ${RED}${BOLD}INACTIVE${RESET}" "${RED}"
            echo -e "${DIM}${YELLOW}   Use '${SCRIPT_NAME} start' to start the service${RESET}"
            ;;
        "failed")
            print_status "${CROSS}" "Service Status: ${RED}${BOLD}FAILED${RESET}" "${RED}"
            echo -e "${DIM}${RED}   Check logs with: ${WHITE}journalctl -u ${PLEX_SERVICE}${RESET}"
            ;;
        *)
            print_status "${INFO}" "Service Status: ${YELLOW}${BOLD}${service_status^^}${RESET}" "${YELLOW}"
            ;;
    esac
    
    # Show recent logs
    echo -e "\n${DIM}${CYAN}┌─── Recent Service Logs  ───┐${RESET}"
    echo -e "${DIM}$(journalctl -u "$PLEX_SERVICE" --no-pager -n 3 --since "7 days ago" 2>/dev/null | tail -3 || echo "No recent logs available")${RESET}"
    echo -e "${DIM}${CYAN}└────────────────────────────┘${RESET}"
}

# 🔧 Show available commands
show_help() {
    echo -e "${BOLD}${WHITE}Usage:${RESET} ${CYAN}${SCRIPT_NAME}${RESET} ${YELLOW}<command>${RESET}"
    echo ""
    echo -e "${BOLD}${WHITE}Available Commands:${RESET}"
    echo -e "  ${GREEN}${BOLD}start${RESET}     ${ROCKET} Start Plex Media Server"
    echo -e "  ${YELLOW}${BOLD}stop${RESET}      ${STOP_SIGN} Stop Plex Media Server"
    echo -e "  ${BLUE}${BOLD}restart${RESET}   ${RECYCLE} Restart Plex Media Server"
    echo -e "  ${CYAN}${BOLD}status${RESET}    ${INFO} Show detailed service status"
    echo -e "  ${PURPLE}${BOLD}help${RESET}      ${SPARKLES} Show this help message"
    echo ""
    echo -e "${DIM}${WHITE}Examples:${RESET}"
    echo -e "  ${DIM}${SCRIPT_NAME} start     # Start the Plex service${RESET}"
    echo -e "  ${DIM}${SCRIPT_NAME} status    # Show current status${RESET}"
    echo ""
}

# 🎯 Main script logic
main() {
    # Check if running as root
    if [[ $EUID -eq 0 ]]; then
        print_header
        print_status "${CROSS}" "Don't run this script as root! Use your regular user account." "${RED}"
        exit 1
    fi
    
    # Check if no arguments provided
    if [[ $# -eq 0 ]]; then
        print_header
        show_help
        exit 1
    fi
    
    # Show header for all operations except help
    if [[ "${1,,}" != "help" ]] && [[ "${1,,}" != "--help" ]] && [[ "${1,,}" != "-h" ]]; then
        print_header
    fi
    
    case "${1,,}" in  # Convert to lowercase
        "start")
            start_plex
            ;;
        "stop")
            stop_plex
            ;;
        "restart"|"reload")
            restart_plex
            ;;
        "status"|"info")
            show_detailed_status
            ;;
        "help"|"--help"|"-h")
            print_header
            show_help
            ;;
        *)
            print_status "${CROSS}" "Unknown command: ${RED}${BOLD}$1${RESET}" "${RED}"
            echo ""
            show_help
            exit 1
            ;;
    esac
}

# 🚀 Execute main function with all arguments
main "$@"