#!/bin/bash

# OpenVPN Client Automatic Installation and Configuration Script (with repository fix)
# Usage: sudo ./vpn.sh

set -e  # Exit immediately on error

echo "=== OpenVPN Client Automatic Installation and Configuration Script (with repository fix) ==="

# Check if running with root privileges
if [ "$EUID" -ne 0 ]; then
    echo "Please run this script with sudo"
    exit 1
fi

# Get current script directory
CURRENT_DIR=$(pwd)
echo "Current directory: $CURRENT_DIR"

# Create client configuration directory (create early for later use)
mkdir -p /etc/openvpn/client

# Check marker file to determine if repository fix has been executed
REPO_FIXED_FILE="/etc/openvpn/client/.repo_fixed"

# Part 1: Fix CentOS repository (only executed on first run)
if [ ! -f "$REPO_FIXED_FILE" ]; then
    echo "1. First run, fixing CentOS-Base.repo file..."
    
    # Change directory
    cd /etc/yum.repos.d

    # Backup original file
    if [ -f "CentOS-Base.repo" ]; then
        cp CentOS-Base.repo CentOS-Base.repo.backup
    fi

    # Create new CentOS-Base.repo file
    cat > CentOS-Base.repo << 'EOF2'
# CentOS-Base.repo
#
# The mirror system uses the connecting IP address of the client and the
# update status of each mirror to pick mirrors that are updated to and
# geographically close to the client.  You should use this for CentOS updates
# unless you are manually picking other mirrors.
#
# If the mirrorlist= does not work for you, as a fall back you can try the 
# remarked out baseurl= line instead.
#
#
 
[base]
name=CentOS-$releasever - Base
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/
#baseurl=http://vault.centos.org/7.9.2009/x86_64/os/
baseurl=http://vault.centos.org/7.9.2009/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
 
#released updates 
[updates]
name=CentOS-$releasever - Updates
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/
#baseurl=http://vault.centos.org/7.9.2009/x86_64/os/
baseurl=http://vault.centos.org/7.9.2009/updates/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
 
#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras&infra=$infra
#$baseurl=http://mirror.centos.org/centos/$releasever/extras/$basearch/
#baseurl=http://vault.centos.org/7.9.2009/x86_64/os/
baseurl=http://vault.centos.org/7.9.2009/extras/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
 
#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus&infra=$infra
#baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/
#baseurl=http://vault.centos.org/7.9.2009/x86_64/os/
baseurl=http://vault.centos.org/7.9.2009/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
EOF2

    # Clean and rebuild cache
    echo "Cleaning and rebuilding YUM cache..."
    yum clean all
    yum makecache

    echo "CentOS-Base.repo successfully updated and cache rebuilt"
    
    # Create marker file
    touch "$REPO_FIXED_FILE"
    echo "Repository fix completed, marker file created: $REPO_FIXED_FILE"
    echo ""
else
    echo "1. Detected that repository configuration has been fixed, skipping this step"
    echo ""
fi

# Part 2: Install and configure OpenVPN (check if already installed)
echo "2. Checking and installing OpenVPN..."

# Check if OpenVPN is already installed
if ! command -v openvpn &> /dev/null; then
    echo "OpenVPN not installed, starting installation..."
    yum -y install epel-release
    yum -y install openvpn
    echo "OpenVPN installation completed!"
else
    echo "OpenVPN already installed, version: $(openvpn --version | head -1)"
fi

# Part 3: Copy configuration file
echo "3. Processing OpenVPN configuration file..."

# Check if OpenVPN-Client.conf file exists in current directory
if [ -f "$CURRENT_DIR/OpenVPN-Client.conf" ]; then
    # Check if target file exists and whether update is needed
    if [ -f "/etc/openvpn/client/OpenVPN-Client.conf" ]; then
        # Compare if file contents are the same
        if cmp -s "$CURRENT_DIR/OpenVPN-Client.conf" "/etc/openvpn/client/OpenVPN-Client.conf"; then
            echo "Configuration file already exists and contents are identical, skipping copy"
        else
            echo "Configuration file exists but contents differ, updating..."
            cp "$CURRENT_DIR/OpenVPN-Client.conf" /etc/openvpn/client/
            chmod 600 /etc/openvpn/client/OpenVPN-Client.conf
            echo "Configuration file updated!"
        fi
    else
        echo "Found $CURRENT_DIR/OpenVPN-Client.conf file, copying to /etc/openvpn/client/"
        cp "$CURRENT_DIR/OpenVPN-Client.conf" /etc/openvpn/client/
        chmod 600 /etc/openvpn/client/OpenVPN-Client.conf
        echo "Configuration file copy completed!"
    fi
    echo "Original file retained at: $CURRENT_DIR/OpenVPN-Client.conf"
else
    echo "Error: OpenVPN-Client.conf file not found in current directory ($CURRENT_DIR)"
    echo "Please ensure OpenVPN-Client.conf file is in the current directory"
    echo "Current directory contents:"
    ls -la "$CURRENT_DIR/"
    exit 1
fi

# Part 4: Process account credentials
AUTH_FILE="/etc/openvpn/client/auth.txt"

# Check if account credentials are already saved
if [ -f "$AUTH_FILE" ]; then
    echo "4. Detected saved account credentials file"
    read -p "Use saved account credentials? (y/n): " use_saved
    if [ "$use_saved" = "y" ] || [ "$use_saved" = "Y" ]; then
        echo "Using saved account credentials"
        # Modify configuration file to use password file
        sed -i 's/^auth-user-pass$/auth-user-pass \/etc\/openvpn\/client\/auth.txt/' /etc/openvpn/client/OpenVPN-Client.conf
    else
        # Input new account credentials and save
        read -p "Please enter VPN username: " username
        read -s -p "Please enter VPN password: " password
        echo
        echo "$username" > "$AUTH_FILE"
        echo "$password" >> "$AUTH_FILE"
        chmod 600 "$AUTH_FILE"
        echo "Account credentials saved to $AUTH_FILE"
        # Modify configuration file to use password file
        sed -i 's/^auth-user-pass$/auth-user-pass \/etc\/openvpn\/client\/auth.txt/' /etc/openvpn/client/OpenVPN-Client.conf
    fi
else
    # First run, input and save account credentials
    echo "4. First run, please enter VPN account credentials"
    read -p "Please enter VPN username: " username
    read -s -p "Please enter VPN password: " password
    echo
    echo "$username" > "$AUTH_FILE"
    echo "$password" >> "$AUTH_FILE"
    chmod 600 "$AUTH_FILE"
    echo "Account credentials saved to $AUTH_FILE"
    # Modify configuration file to use password file
    sed -i 's/^auth-user-pass$/auth-user-pass \/etc\/openvpn\/client\/auth.txt/' /etc/openvpn/client/OpenVPN-Client.conf
fi

# Verify installation
echo "5. Verifying installation..."
echo "OpenVPN version: $(openvpn --version | head -1)"
echo "Configuration file location: /etc/openvpn/client/OpenVPN-Client.conf"
echo "Account credentials file: /etc/openvpn/client/auth.txt"
echo "Original configuration file retained at: $CURRENT_DIR/OpenVPN-Client.conf"

# Create convenient management script (if not exists)
if [ ! -f "/usr/local/bin/vpn-manage" ]; then
    echo "6. Creating convenient management script..."
    cat > /usr/local/bin/vpn-manage << 'EOF'
#!/bin/bash

case "$1" in
    "start")
        cd /etc/openvpn/client/
        openvpn --config OpenVPN-Client.conf
        ;;
    "stop")
        pkill openvpn
        echo "VPN stopped"
        ;;
    "status")
        if pgrep openvpn > /dev/null; then
            echo "VPN is running"
        else
            echo "VPN is not running"
        fi
        ;;
    "change-auth")
        read -p "Please enter new VPN username: " username
        read -s -p "Please enter new VPN password: " password
        echo
        echo "$username" > /etc/openvpn/client/auth.txt
        echo "$password" >> /etc/openvpn/client/auth.txt
        chmod 600 /etc/openvpn/client/auth.txt
        echo "Account credentials updated"
        ;;
    "update-config")
        # Update configuration file function
        if [ -f "./OpenVPN-Client.conf" ]; then
            cp ./OpenVPN-Client.conf /etc/openvpn/client/
            chmod 600 /etc/openvpn/client/OpenVPN-Client.conf
            echo "Configuration file updated"
        else
            echo "Error: OpenVPN-Client.conf file not found in current directory"
        fi
        ;;
    "reset-repo")
        # Reset repository marker, next run will re-fix repository
        rm -f /etc/openvpn/client/.repo_fixed
        echo "Repository marker reset, next run will re-fix repository"
        ;;
    *)
        echo "Usage: vpn-manage {start|stop|status|change-auth|update-config|reset-repo}"
        echo "  start         - Start VPN connection"
        echo "  stop          - Stop VPN connection"
        echo "  status        - Check VPN status"
        echo "  change-auth   - Change account credentials"
        echo "  update-config - Update configuration file (copy from current directory)"
        echo "  reset-repo    - Reset repository marker (re-fix repository next time)"
        ;;
esac
EOF

    chmod +x /usr/local/bin/vpn-manage
    echo "Convenient management script created!"
else
    echo "6. Convenient management script already exists, skipping creation"
fi

echo ""
echo "=== Installation completed! ==="
echo "Usage instructions:"
echo "Start VPN:     vpn-manage start"
echo "Stop VPN:      vpn-manage stop"
echo "Check status:  vpn-manage status"
echo "Change credentials: vpn-manage change-auth"
echo "Update config: vpn-manage update-config"
echo "Reset repository: vpn-manage reset-repo"

# 直接提示用户如何使用systemd服务，不询问是否立即启动
echo ""
echo "VPN installation completed."
echo "To start VPN as a system service, run: systemctl start openvpn-client"
echo "To enable auto-start on boot: systemctl enable openvpn-client"
echo "To check VPN status: systemctl status openvpn-client"
echo ""
echo "Note: The 'vpn-manage start' command will run VPN in the foreground."
echo "For background operation, use the systemd service instead."