#!/bin/bash

# --- 1. Define Variables and Prompt for Input ---

# Define the local directory where the kubeconfig file will be stored
LOCAL_KUBE_DIR="$HOME/.kube"
# Define the local destination path for the config file
LOCAL_CONFIG_PATH="$LOCAL_KUBE_DIR/config"
# Define the remote source file path (standard k3s kubeconfig location)
REMOTE_CONFIG_PATH="/etc/rancher/k3s/k3s.yaml"
# Define the remote username
REMOTE_USER="rancher"

echo "--- K3s Kubeconfig Fetcher ---"

# Prompt the user for the K3s server IP address
read -r -p "Enter the K3s master server IP address: " SERVER_IP

# Validate that an IP was entered
if [[ -z "$SERVER_IP" ]]; then
    echo "Error: Server IP address cannot be empty. Exiting."
    exit 1
fi

# --- 2. Create Local Directory ---

# Create the .kube directory if it doesn't exist
echo "Creating local directory: $LOCAL_KUBE_DIR"
mkdir -p "$LOCAL_KUBE_DIR"

# --- 3. Execute SCP for File Download ---

# The scp command will download the file from the remote server.
# The user will be prompted for the password by the scp/ssh process.
echo "Attempting to download kubeconfig from $REMOTE_USER@$SERVER_IP..."
echo "You will be prompted to enter the password for the user 'rancher'."

# SCP Syntax: scp [user@]remote_host:source_file local_destination
sudo scp "$REMOTE_USER@$SERVER_IP:$REMOTE_CONFIG_PATH" "$LOCAL_CONFIG_PATH"

# Check the exit status of the scp command
if [ $? -ne 0 ]; then
    echo "---"
    echo "ERROR: File transfer failed. Check the following:"
    echo "* Ensure SSH is running on the server."
    echo "* Verify the IP address and the password for 'rancher' are correct."
    echo "* Ensure 'rancher' user has read permission to $REMOTE_CONFIG_PATH (may require elevated permissions on the server)."
    exit 1
fi

echo "SUCCESS: Kubeconfig file downloaded to $LOCAL_CONFIG_PATH"

# --- 4. Post-Download Configuration Steps ---

# 4a. Update Server IP in the config file
# The k3s config often uses 127.0.0.1 internally, which must be replaced with the public IP.
echo "Updating server IP from 127.0.0.1 to $SERVER_IP in the config file..."
sudo sed -i "s/127.0.0.1/$SERVER_IP/g" "$LOCAL_CONFIG_PATH"

# 4b. Set correct permissions (read/write only for the owner)
echo "Setting restrictive permissions on the config file (chmod 600)..."
sudo chmod 600 "$LOCAL_CONFIG_PATH"

# 4c. Set ownership to the current user (since 'sudo scp' might set root ownership)
echo "Setting file ownership to the current user: $USER"
sudo chown "$USER":"$(id -gn $USER)" "$LOCAL_CONFIG_PATH"

echo "---"
echo "Kubeconfig is ready! You can now use kubectl to manage your cluster."
echo "Example: kubectl get nodes"