#!/bin/bash

#######################################
# CentOS Initial Setup Script
# Usage: ./pty_setup_centos_en.sh
#######################################

set -e  # Exit script on error

# Color definitions
CYAN='\033[0;36m'
BLUE='\033[1;94m'  # Bright blue
PURPLE='\033[0;35m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Display logo
clear
echo -e "${CYAN}"
cat << "EOF"

░█▀█░█░░░█▀█░▀█▀░█░█░░░█░█░█▀█░█░█░█▀▀░█▀▀
░█▀▀░█░░░█▀█░░█░░░█░░░░█▀█░█░█░█░█░▀▀█░█▀▀
░▀░░░▀▀▀░▀░▀░░▀░░░▀░░░░▀░▀░▀▀▀░▀▀▀░▀▀▀░▀▀▀
EOF
echo -e "${NC}"
echo -e "${PURPLE}═══════════════════════════════════════════════════════════${NC}"
echo ""
echo -e "${BLUE} CentOS Setup Script v1.0 (pty_setup_centos_en.sh)${NC}"
echo ""
echo -e "${BLUE} Copyright (C) 2019 by cpueblo@platyhouse.com, PlatyHouse Co.,LTD.${NC}"
echo -e "${BLUE} Visit https://www.platyhouse.com${NC}"
echo ""
echo -e "${PURPLE}═══════════════════════════════════════════════════════════${NC}"
echo ""

# Menu display function
show_menu() {
    echo -e "${PURPLE}═══════════════════════════════════════════════════════════${NC}"
    echo ""
    echo -e "  ${CYAN}0.${NC} Install All"
    echo -e "  ${CYAN}1.${NC} Set Hostname"
    echo -e "  ${CYAN}2.${NC} Configure Network IP"
    echo -e "  ${CYAN}3.${NC} Setup /etc/bashrc"
    echo -e "  ${CYAN}4.${NC} Clean YUM Cache"
    echo -e "  ${CYAN}5.${NC} System Package Update"
    echo -e "  ${CYAN}6.${NC} Install Python"
    echo -e "  ${CYAN}7.${NC} Install Node.js, Claude & Gemini CLI"
    echo -e "  ${CYAN}8.${NC} Install Essential Packages"
    echo -e "  ${CYAN}9.${NC} Set Timezone to Seoul"
    echo -e "  ${CYAN}10.${NC} Configure Time Server (time.bora.net)"
    echo -e "  ${CYAN}11.${NC} SELinux ON/OFF"
    echo -e "  ${CYAN}q.${NC} Quit"
    echo ""
    echo -e "${YELLOW}Select (e.g., 0,1,3 or 0):${NC} \c"
}

#######################################
# 1. Hostname Setup
#######################################
setup_hostname() {
    CURRENT_HOSTNAME=$(hostnamectl --static)
    echo -e "${CYAN}[1/11]${NC} Set Hostname, Current hostname: ${YELLOW}${CURRENT_HOSTNAME}${NC}"
    echo -e "${YELLOW}Do you want to change the hostname? (y/N):${NC} \c"
    read -n 1 -r REPLY_HOSTNAME
    echo
    if [[ $REPLY_HOSTNAME =~ ^[Yy]$ ]]; then
        echo -e "${YELLOW}Enter new hostname:${NC} \c"
        read HOSTNAME
        if [ -n "$HOSTNAME" ]; then
            hostnamectl set-hostname "$HOSTNAME"
            echo -e "  ${GREEN}✓${NC} Hostname has been set: ${YELLOW}$(hostnamectl --static)${NC}"
        else
            echo -e "  ${YELLOW}⊘${NC} Skipped due to empty input."
        fi
    else
        echo -e "  ${YELLOW}⊘${NC} Skipped hostname setup."
    fi
    echo ""
}

#######################################
# 2. Network IP Configuration
#######################################
setup_network() {
    echo -e "${CYAN}[2/11]${NC} Configure Network IP"
    echo -e "${YELLOW}Do you want to configure network IP? (y/N):${NC} \c"
    read -n 1 -r REPLY_IP
    echo
    if [[ $REPLY_IP =~ ^[Yy]$ ]]; then
        # Display available network interfaces
        echo -e "  ${BLUE}Available network interfaces:${NC}"
        ip -br link show | grep -v "lo" | awk '{print "    - "$1}'
        echo ""

        echo -e "${YELLOW}Network interface name (e.g., eth0, ens33):${NC} \c"
        read IFACE
        echo -e "${YELLOW}IP address (e.g., 192.168.1.100):${NC} \c"
        read IPADDR
        echo -e "${YELLOW}Subnet mask (e.g., 255.255.255.0):${NC} \c"
        read NETMASK
        echo -e "${YELLOW}Gateway (e.g., 192.168.1.1):${NC} \c"
        read GATEWAY
        echo -e "${YELLOW}DNS server (e.g., 8.8.8.8):${NC} \c"
        read DNS

        if [ -n "$IFACE" ] && [ -n "$IPADDR" ] && [ -n "$NETMASK" ] && [ -n "$GATEWAY" ] && [ -n "$DNS" ]; then
            # Create network script file
            IFCFG_FILE="/etc/sysconfig/network-scripts/ifcfg-${IFACE}"

            # Create backup if file exists
            if [ -f "$IFCFG_FILE" ]; then
                cp "$IFCFG_FILE" "${IFCFG_FILE}.backup.$(date +%Y%m%d_%H%M%S)"
            fi

            # Write network configuration file
            cat > "$IFCFG_FILE" << EOF
TYPE=Ethernet
BOOTPROTO=static
NAME=${IFACE}
DEVICE=${IFACE}
ONBOOT=yes
IPADDR=${IPADDR}
NETMASK=${NETMASK}
GATEWAY=${GATEWAY}
DNS1=${DNS}
EOF

            # Restart network
            echo -e "  ${BLUE}→${NC} Restarting network..."
            systemctl restart NetworkManager > /dev/null 2>&1

            echo -e "  ${GREEN}✓${NC} Network configuration completed."
            echo -e "    IP: ${YELLOW}${IPADDR}${NC}"
            echo -e "    Netmask: ${YELLOW}${NETMASK}${NC}"
            echo -e "    Gateway: ${YELLOW}${GATEWAY}${NC}"
            echo -e "    DNS: ${YELLOW}${DNS}${NC}"
        else
            echo -e "  ${YELLOW}⊘${NC} Skipped due to missing required information."
        fi
    else
        echo -e "  ${YELLOW}⊘${NC} Skipped network IP configuration."
    fi
    echo ""
}

#######################################
# 3. /etc/bashrc Setup
#######################################
setup_bashrc() {
    echo -e "${CYAN}[3/11]${NC} Add /etc/bashrc Configuration"
    echo -e "${YELLOW}Do you want to add custom settings to /etc/bashrc? (y/N):${NC} \c"
    read -n 1 -r REPLY_BASHRC
    echo
    if [[ $REPLY_BASHRC =~ ^[Yy]$ ]]; then
        # Create backup
        cp /etc/bashrc /etc/bashrc.backup.$(date +%Y%m%d_%H%M%S)

    # Content to add to bashrc
    cat >> /etc/bashrc << 'EOF'

#######################################
# Added by pty_setup_centos_en.sh - Start
#######################################

# Prompt color settings
export PS1='\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

# History settings
export HISTSIZE=10000
export HISTFILESIZE=20000
export HISTTIMEFORMAT="%Y-%m-%d %H:%M:%S "

# Default editor setting
export EDITOR=vi

# Useful aliases
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'
alias grep='grep --color=auto'
alias df='df -h'
alias du='du -h'

# git related commands
alias gs="git status"
alias gd="git diff --word-diff"
alias ga="git add"
alias gb="git branch"
alias gc="git checkout"
alias gl="git log --date=format:'%Y-%m-%d %H:%M:%S'"
# git add, commit function. Usage: gac "commit message"
gac() {
  git add -A
  git commit -m "$*"
}


## Prevent filename corruption in git show
git config --global core.quotepath false

## Fix git unicode decomposition
git config --global core.precomposeunicode true

## git color
git config --global color.ui true
git config --global color.status.changed "#ff0000 normal bold"
git config --global color.status.untracked "#dd99dd normal bold"
git config --global color.status.header "#ffffff normal bold"

## user settings
git config --global user.name "KwangHee Yoo"
git config --global user.email "cpueblo@platyhouse.com"

## Store git credentials
git config credential.helper store

# Enable executing . command.sh
PATH=$PATH:.

# Enable executing pty_centos.git
PATH=$PATH:/var/lib/pty_centos.git

#######################################


EOF

        echo -e "  ${GREEN}✓${NC} /etc/bashrc configuration completed."
    else
        echo -e "  ${YELLOW}⊘${NC} Skipped /etc/bashrc configuration."
    fi
    echo ""
}

#######################################
# 4. YUM Cache Cleanup
#######################################
setup_yum_clean() {
    echo -e "${CYAN}[4/11]${NC} Clean YUM Cache"
    echo -e "${YELLOW}Do you want to clean YUM cache? (y/N):${NC} \c"
    read -n 1 -r REPLY_YUM_CLEAN
    echo
    if [[ $REPLY_YUM_CLEAN =~ ^[Yy]$ ]]; then
        yum clean all > /dev/null 2>&1
        rm -rf /var/cache/yum
        echo -e "  ${GREEN}✓${NC} YUM cache has been cleaned."
    else
        echo -e "  ${YELLOW}⊘${NC} Skipped YUM cache cleanup."
    fi
    echo ""
}

#######################################
# 5. System Update
#######################################
setup_system_update() {
    echo -e "${CYAN}[5/11]${NC} System Package Update"
    echo -e "${YELLOW}Do you want to update the system? (y/N):${NC} \c"
    read -n 1 -r REPLY_UPDATE
    echo
    if [[ $REPLY_UPDATE =~ ^[Yy]$ ]]; then
        yum update -y
        echo -e "  ${GREEN}✓${NC} System update completed."
    else
        echo -e "  ${YELLOW}⊘${NC} Skipped system update."
    fi
    echo ""
}

#######################################
# 6. Python Installation
#######################################
setup_python() {
    echo -e "${CYAN}[6/11]${NC} Install Python"
    echo -e "${YELLOW}Do you want to install Python? (y/N):${NC} \c"
    read -n 1 -r REPLY_PYTHON
    echo
    if [[ $REPLY_PYTHON =~ ^[Yy]$ ]]; then
        echo -e "  ${BLUE}→${NC} Installing Python..."
        yum install -y python3 python3-pip > /dev/null 2>&1
        echo -e "  ${GREEN}✓${NC} Python installation completed: $(python3 --version)"
    else
        echo -e "  ${YELLOW}⊘${NC} Skipped Python installation."
    fi
    echo ""
}

#######################################
# 7. Node.js and Claude Installation
#######################################
setup_nodejs_claude() {
    echo -e "${CYAN}[7/11]${NC} Install Node.js, Claude & Gemini CLI"
    echo -e "${YELLOW}Do you want to install Node.js, Claude, and Gemini CLI? (y/N):${NC} \c"
    read -n 1 -r REPLY_CLAUDE
    echo
    if [[ $REPLY_CLAUDE =~ ^[Yy]$ ]]; then
        # Node.js installation
        echo -e "  ${BLUE}→${NC} Installing Node.js..."
        curl -fsSL https://rpm.nodesource.com/setup_lts.x | bash - > /dev/null 2>&1
        yum install -y nodejs > /dev/null 2>&1
        echo -e "  ${GREEN}✓${NC} Node.js installation completed: $(node --version)"

        # Claude installation
        echo -e "  ${BLUE}→${NC} Installing Claude..."
        npm install -g @anthropic-ai/claude-code > /dev/null 2>&1
        echo -e "  ${GREEN}✓${NC} Claude installation completed."

        # Gemini CLI installation
        echo -e "  ${BLUE}→${NC} Installing Gemini CLI..."
        npm install -g @google/gemini-cli > /dev/null 2>&1
        echo -e "  ${GREEN}✓${NC} Gemini CLI installation completed."
    else
        echo -e "  ${YELLOW}⊘${NC} Skipped Node.js and CLI installation."
    fi
    echo ""
}

#######################################
# 8. Essential Packages Installation
#######################################
setup_packages() {
    echo -e "${CYAN}[8/11]${NC} Install Essential Packages"
    echo -e "${YELLOW}Do you want to install essential packages? (vim, wget, curl, net-tools, etc.) (y/N):${NC} \c"
    read -n 1 -r REPLY_PACKAGES
    echo
    if [[ $REPLY_PACKAGES =~ ^[Yy]$ ]]; then
        yum install -y \
            vim \
            wget \
            curl \
            net-tools \
            bind-utils \
            telnet \
            tcpdump > /dev/null 2>&1

        echo -e "  ${GREEN}✓${NC} Essential packages installation completed."

        # tmux installation confirmation
        echo ""
        echo -e "  ${YELLOW}Do you want to install tmux? (y/N):${NC} \c"
        read -n 1 -r REPLY_TMUX
        echo
        if [[ $REPLY_TMUX =~ ^[Yy]$ ]]; then
            echo -e "  ${BLUE}→${NC} Installing tmux..."
            yum install -y tmux > /dev/null 2>&1
            echo -e "  ${GREEN}✓${NC} tmux installation completed."
        fi
    else
        echo -e "  ${YELLOW}⊘${NC} Skipped essential packages installation."
    fi
    echo ""
}

#######################################
# 9. Timezone Setup
#######################################
setup_timezone() {
    echo -e "${CYAN}[9/11]${NC} Set Timezone to Seoul"
    echo -e "${YELLOW}Do you want to set timezone to Asia/Seoul? (y/N):${NC} \c"
    read -n 1 -r REPLY_TIMEZONE
    echo
    if [[ $REPLY_TIMEZONE =~ ^[Yy]$ ]]; then
        timedatectl set-timezone Asia/Seoul
        echo -e "  ${GREEN}✓${NC} Timezone has been set to Asia/Seoul."
        echo -e "  Current time: ${YELLOW}$(date '+%Y-%m-%d %H:%M:%S %Z')${NC}"
    else
        echo -e "  ${YELLOW}⊘${NC} Skipped timezone setup."
    fi
    echo ""
}

#######################################
# 10. Time Server Setup
#######################################
setup_timeserver() {
    echo -e "${CYAN}[10/11]${NC} Configure Time Server (time.bora.net)"
    echo -e "${YELLOW}Do you want to configure time server to time.bora.net? (y/N):${NC} \c"
    read -n 1 -r REPLY_TIMESERVER
    echo
    if [[ $REPLY_TIMESERVER =~ ^[Yy]$ ]]; then
        echo -e "  ${BLUE}→${NC} Installing chrony package..."
        dnf install chrony -y > /dev/null 2>&1

        echo -e "  ${BLUE}→${NC} Enabling chronyd service..."
        systemctl enable --now chronyd > /dev/null 2>&1

        echo -e "  ${BLUE}→${NC} Adding time.bora.net server..."
        echo "server time.bora.net iburst" | tee -a /etc/chrony.conf > /dev/null

        echo -e "  ${BLUE}→${NC} Restarting chronyd..."
        systemctl restart chronyd > /dev/null 2>&1

        echo -e "  ${GREEN}✓${NC} Time server configuration completed."
        echo -e "  ${BLUE}Time synchronization sources:${NC}"
        chronyc sources -v
    else
        echo -e "  ${YELLOW}⊘${NC} Skipped time server configuration."
    fi
    echo ""
}

#######################################
# 11. SELinux ON/OFF Configuration
#######################################
setup_selinux() {
    echo -e "${CYAN}[11/11]${NC} SELinux ON/OFF Configuration"

    # Check current SELinux status
    CURRENT_SELINUX=$(getenforce 2>/dev/null || echo "Unknown")
    echo -e "  Current SELinux status: ${YELLOW}${CURRENT_SELINUX}${NC}"
    echo ""

    echo -e "${YELLOW}How do you want to configure SELinux?${NC}"
    echo -e "  ${CYAN}1.${NC} Disable SELinux"
    echo -e "  ${CYAN}2.${NC} Enable SELinux (Enforcing)"
    echo -e "  ${CYAN}3.${NC} Skip"
    echo -e "${YELLOW}Select (1/2/3):${NC} \c"
    read -n 1 -r REPLY_SELINUX
    echo
    echo

    case $REPLY_SELINUX in
        1)
            echo -e "  ${BLUE}→${NC} Disabling SELinux..."
            sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
            sed -i 's/SELINUX=permissive/SELINUX=disabled/g' /etc/selinux/config
            setenforce 0 2>/dev/null
            echo -e "  ${GREEN}✓${NC} SELinux has been disabled."
            echo -e "  ${YELLOW}[Note]${NC} Changes will take effect after reboot."
            ;;
        2)
            echo -e "  ${BLUE}→${NC} Enabling SELinux..."
            sed -i 's/SELINUX=disabled/SELINUX=enforcing/g' /etc/selinux/config
            sed -i 's/SELINUX=permissive/SELINUX=enforcing/g' /etc/selinux/config
            echo -e "  ${GREEN}✓${NC} SELinux has been set to enforcing."
            echo -e "  ${YELLOW}[Note]${NC} Changes will take effect after reboot."
            ;;
        3)
            echo -e "  ${YELLOW}⊘${NC} Skipped SELinux configuration."
            ;;
        *)
            echo -e "  ${RED}Invalid selection.${NC}"
            ;;
    esac
    echo ""
}

#######################################
# Main Execution Logic
#######################################

# Menu loop
while true; do
    # Display menu
    show_menu

    # Get user input
    read MENU_CHOICE

    # Process input (convert comma-separated values to array)
    IFS=',' read -ra CHOICES <<< "$MENU_CHOICE"

    echo ""

    # Check for quit
    if [[ "$MENU_CHOICE" == "q" ]] || [[ "$MENU_CHOICE" == "Q" ]]; then
        echo -e "${YELLOW}Exiting installation.${NC}"
        break
    fi

    # Install all and exit if 0 is selected
    if [[ "$MENU_CHOICE" == "0" ]]; then
        echo -e "${BLUE}Starting full installation...${NC}"
        echo ""
        setup_hostname
        setup_network
        setup_bashrc
        setup_yum_clean
        setup_system_update
        setup_python
        setup_nodejs_claude
        setup_packages
        setup_timezone
        setup_timeserver
        setup_selinux
        break
    fi

    # Execute selected items
    for choice in "${CHOICES[@]}"; do
        # Remove whitespace
        choice=$(echo "$choice" | xargs)

        case $choice in
            1)
                setup_hostname
                ;;
            2)
                setup_network
                ;;
            3)
                setup_bashrc
                ;;
            4)
                setup_yum_clean
                ;;
            5)
                setup_system_update
                ;;
            6)
                setup_python
                ;;
            7)
                setup_nodejs_claude
                ;;
            8)
                setup_packages
                ;;
            9)
                setup_timezone
                ;;
            10)
                setup_timeserver
                ;;
            11)
                setup_selinux
                ;;
            *)
                echo -e "${RED}Invalid selection: ${choice}${NC}"
                echo ""
                ;;
        esac
    done
done

#######################################
# Completion
#######################################
echo ""
echo -e "${PURPLE}═══════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}✓ CentOS initial setup completed!${NC}"
echo -e "${PURPLE}═══════════════════════════════════════════════════════════${NC}"
echo ""
echo -e "  ${CYAN}▶${NC} Current hostname: ${YELLOW}$(hostnamectl --static)${NC}"
echo ""
echo -e "${YELLOW}[Notice]${NC} To apply changes, run one of the following:"
echo -e "  ${BLUE}1.${NC} Restart your shell"
echo -e "  ${BLUE}2.${NC} source /etc/bashrc"
echo ""
echo -e "${PURPLE}═══════════════════════════════════════════════════════════${NC}"
