#!/bin/bash

# Get Git commit hash
GIT_COMMIT_HASH=$(git rev-parse HEAD)

# Get Git branch name
GIT_BRANCH=$(git branch --show-current)

# Get build date in YYYYMMDDHHMMSS format
BUILD_DATE=$(date +"%Y%m%d%H%M%S")

# Output linker flags
echo "-X main.GitCommitHash=$GIT_COMMIT_HASH"
echo "-X main.GitBranch=$GIT_BRANCH"
echo "-X main.BuildDate=$BUILD_DATE"

# Set Go environment variables
export GOARCH=amd64
export GOOS=linux
export CGO_ENABLED=0



# 检查并创建 bin 目录
if [ ! -d "bin" ]; then
    mkdir -p bin
fi

# 定义文件名
FILE="admin"

# 删除旧的编译文件
rm -f bin/$FILE
go build   -o bin/$FILE main.go
go build -ldflags "-X main.GitBranch=$GIT_BRANCH -X main.GitCommit=$GIT_COMMIT_HASH -X main.BuildDate=$BUILD_DATE" -o bin/$FILE main.go

# 检查编译是否成功
if [ ! -f "bin/$FILE" ]; then
    echo "build failed."
    exit 1
else
    echo "build success."
fi


Host="114.132.124.145"
Username="ubuntu"
Password="@qq20160101"

RemotePath="/home/ubuntu/admin"
RemoteFile="$RemotePath/$FILE"
LocalFile="bin/$FILE"

plink -ssh -batch -pw "$Password" "$Username@$Host" "rm -f '$RemoteFile'"
if [ $? -eq 0 ]; then
    echo "删除文件成功"
else
    echo "删除文件失败"
    exit 1
fi

# 传输文件到远程主机
pscp -batch -pw "$Password" -p "config.yaml" "$Username@$Host:$RemotePath"
pscp -batch -pw "$Password" -p "$LocalFile" "$Username@$Host:$RemotePath" && \
plink -ssh -batch -pw "$Password" "$Username@$Host" "chmod +x '$RemoteFile'"

if [ $? -eq 0 ]; then
    echo "上传文件成功"
else
    echo "上传文件失败"
    exit 1
fi


# 远程执行脚本
plink -ssh -batch -pw "$Password" "$Username@$Host" "echo '$Password' | sudo -S supervisorctl restart $FILE"

if [ $? -eq 0 ]; then
    echo "远程脚本执行成功"
else
    echo "远程脚本执行失败"
    exit 1
fi



