#!/bin/bash
# ============================================================
# GBS Master Node Build Environment Installation Script
# Run on: 192.168.20.100 (CentOS 7)
#
# Installs:
#   - Oracle JDK 1.8.0_202 (extracted from existing Docker image)
#   - Apache Maven 3.8.8 (with Alibaba Cloud mirror)
#   - Dockerfile template
#   - yum vault mirrors (CentOS 7 EOL fix)
#   - ACR login
#
# Usage:
#   bash install_env.sh
# ============================================================

set -e

echo "=========================================="
echo "  GBS Build Environment Setup"
echo "  Host: $(hostname) ($(hostname -I 2>/dev/null || echo 'unknown'))"
echo "=========================================="

# ---- Step 1: Extract JDK from existing Docker image ----
echo ""
echo "[1/6] Installing JDK 1.8.0_202..."

if [ -d "/opt/jdk1.8.0_202" ] && [ -x "/opt/jdk1.8.0_202/bin/java" ]; then
    echo "  JDK already installed, skipping."
else
    # Find an image with JDK
    IMAGE=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep 'ali_img_ns' | head -1)
    if [ -z "$IMAGE" ]; then
        echo "ERROR: No suitable Docker image found with JDK!"
        exit 1
    fi
    echo "  Extracting JDK from: $IMAGE"
    docker rm -f jdk-extract-tmp 2>/dev/null || true
    docker create --name jdk-extract-tmp "$IMAGE" /bin/true > /dev/null
    docker cp jdk-extract-tmp:/opt/jdk1.8.0_202 /opt/jdk1.8.0_202
    docker rm jdk-extract-tmp > /dev/null
    echo "  JDK extracted to /opt/jdk1.8.0_202"
fi

# Configure JAVA_HOME
cat > /etc/profile.d/java.sh << 'EOF'
export JAVA_HOME=/opt/jdk1.8.0_202
export PATH=$JAVA_HOME/bin:$PATH
EOF
chmod +x /etc/profile.d/java.sh
source /etc/profile.d/java.sh
echo "  $(java -version 2>&1 | head -1)"

# ---- Step 2: Install Maven ----
echo ""
echo "[2/6] Installing Maven 3.8.8..."

if [ -x "/opt/maven/bin/mvn" ]; then
    echo "  Maven already installed, skipping."
else
    MAVEN_VERSION="3.8.8"
    MAVEN_URLS=(
        "https://mirrors.aliyun.com/apache/maven/maven-3/${MAVEN_VERSION}/binaries/apache-maven-${MAVEN_VERSION}-bin.tar.gz"
        "https://archive.apache.org/dist/maven/maven-3/${MAVEN_VERSION}/binaries/apache-maven-${MAVEN_VERSION}-bin.tar.gz"
    )
    DOWNLOADED=0
    for url in "${MAVEN_URLS[@]}"; do
        echo "  Trying: $url"
        if curl -fsSL -o /tmp/maven.tar.gz "$url" --connect-timeout 15 --max-time 300; then
            DOWNLOADED=1
            break
        fi
    done
    if [ $DOWNLOADED -eq 0 ]; then
        echo "ERROR: Could not download Maven!"
        exit 1
    fi
    mkdir -p /opt/maven
    tar -xzf /tmp/maven.tar.gz -C /opt/maven --strip-components=1
    rm -f /tmp/maven.tar.gz
fi

# Configure Maven environment
cat > /etc/profile.d/maven.sh << 'EOF'
export MAVEN_HOME=/opt/maven
export PATH=$MAVEN_HOME/bin:$PATH
EOF
chmod +x /etc/profile.d/maven.sh
source /etc/profile.d/maven.sh

# Configure Alibaba Maven mirror
mkdir -p /root/.m2
cat > /root/.m2/settings.xml << 'XMLEOF'
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.2.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.2.0 https://maven.apache.org/xsd/settings-1.2.0.xsd">
  <localRepository>/root/.m2/repository</localRepository>
  <mirrors>
    <mirror>
      <id>aliyunmaven</id>
      <name>Alibaba Cloud Maven Mirror</name>
      <url>https://maven.aliyun.com/repository/public</url>
      <mirrorOf>central</mirrorOf>
    </mirror>
  </mirrors>
  <profiles>
    <profile>
      <id>alibaba-repos</id>
      <repositories>
        <repository>
          <id>aliyun-public</id>
          <url>https://maven.aliyun.com/repository/public</url>
          <releases><enabled>true</enabled></releases>
          <snapshots><enabled>true</enabled></snapshots>
        </repository>
        <repository>
          <id>aliyun-spring</id>
          <url>https://maven.aliyun.com/repository/spring</url>
          <releases><enabled>true</enabled></releases>
          <snapshots><enabled>true</enabled></snapshots>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <id>aliyun-plugin</id>
          <url>https://maven.aliyun.com/repository/public</url>
          <releases><enabled>true</enabled></releases>
          <snapshots><enabled>true</enabled></snapshots>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  </profiles>
  <activeProfiles>
    <activeProfile>alibaba-repos</activeProfile>
  </activeProfiles>
</settings>
XMLEOF
cp /root/.m2/settings.xml /opt/maven/conf/settings.xml
echo "  Maven $(mvn -version 2>&1 | head -1)"

# ---- Step 3: Fix yum repos (CentOS 7 EOL) ----
echo ""
echo "[3/6] Configuring yum vault mirrors..."

cp /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bak.$(date +%Y%m%d) 2>/dev/null || true
cat > /etc/yum.repos.d/CentOS-Base.repo << 'YUMEOF'
[base]
name=CentOS-7 - Base - vault.aliyun.com
baseurl=https://mirrors.aliyun.com/centos-vault/7.9.2009/os/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=1

[updates]
name=CentOS-7 - Updates - vault.aliyun.com
baseurl=https://mirrors.aliyun.com/centos-vault/7.9.2009/updates/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=1

[extras]
name=CentOS-7 - Extras - vault.aliyun.com
baseurl=https://mirrors.aliyun.com/centos-vault/7.9.2009/extras/x86_64/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
enabled=1
YUMEOF
yum clean all > /dev/null 2>&1
yum makecache fast > /dev/null 2>&1
echo "  yum repos configured (aliyun centos-vault)"

# ---- Step 4: Verify Docker ----
echo ""
echo "[4/6] Verifying Docker..."
echo "  Docker $(docker --version)"

# ---- Step 5: Login to ACR ----
echo ""
echo "[5/6] Logging in to ACR..."
echo 'idurCT!rIq9EzISD' | docker login --username=10952138@qq.com --password-stdin jjb-registry-registry.cn-hangzhou.cr.aliyuncs.com 2>&1 | grep -v WARNING

# ---- Step 6: Install Dockerfile template ----
echo ""
echo "[6/6] Installing Dockerfile template..."
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
mkdir -p /opt/docker-templates
if [ -f "${SCRIPT_DIR}/Dockerfile" ]; then
    cp "${SCRIPT_DIR}/Dockerfile" /opt/docker-templates/
    echo "  Dockerfile copied to /opt/docker-templates/"
fi
if [ -f "${SCRIPT_DIR}/build.sh" ]; then
    cp "${SCRIPT_DIR}/build.sh" /opt/docker-templates/
    chmod +x /opt/docker-templates/build.sh
    echo "  build.sh copied to /opt/docker-templates/"
fi

# ---- Summary ----
echo ""
echo "=========================================="
echo "  INSTALLATION COMPLETE"
echo "=========================================="
echo ""
echo "  Java:    $(/opt/jdk1.8.0_202/bin/java -version 2>&1 | head -1)"
echo "  Maven:   $(/opt/maven/bin/mvn -version 2>&1 | head -1)"
echo "  Docker:  $(docker --version)"
echo ""
echo "  JAVA_HOME=/opt/jdk1.8.0_202"
echo "  MAVEN_HOME=/opt/maven"
echo "  Dockerfile: /opt/docker-templates/Dockerfile"
echo "  Build script: /opt/docker-templates/build.sh"
echo ""
echo "  NOTE: Run 'source /etc/profile.d/java.sh' and"
echo "        'source /etc/profile.d/maven.sh' or re-login"
echo "        to use java/mvn commands."
echo "=========================================="
