#!/bin/bash


time=$(date "+%Y-%m-%d_%H-%M-%S")
defaultTag=":latest"


inputImage=${1:-cog-hello-world${defaultTag}}
ciperPrivateKey=${2:-8c4c3af66c696dfe72cdedacf16c02332dfea1de7edd09f2264f5bbdf9122f430ddc9a324d79da4a855e82785a4b675fc3baf0e35f7f46763d3a14233fa072d1}
port=${3:-5000}
outputImage=${4:-output-image:${time}}

# 1. 基础镜像 2. 加密密钥 3. 端口 4. 输出镜像

echo "inputImage     : $inputImage"
echo "ciperPrivateKey: $ciperPrivateKey"
echo "port           : $port"
echo "outputImage    : $outputImage"



dockerfile="Dockerfile"

echo "FROM $inputImage" > $dockerfile
echo "RUN apt-get update && apt-get install procps -y" >> $dockerfile
echo "COPY proxy proxy" >> $dockerfile
echo "COPY script.sh  script.sh" >> $dockerfile
echo "RUN chmod +x script.sh" >> $dockerfile
echo "CMD ./script.sh" >> $dockerfile


go build -ldflags "-X main.CipherPrivateKey=${ciperPrivateKey}" -o ./proxy 


# version=$(git describe --tags)
# docker build -f Dockerfile -t aiwithproxy:${version} .



scriptfile="script.sh"


echo "nohup ./proxy  &" >  $scriptfile

echo "nohup python -m cog.server.http &" >>  $scriptfile

echo "echo \"rm  /bin/sh  /bin/bash /bin/dash /bin/rbash     rm  /usr/bin/cp \"" >>  $scriptfile
echo "rm  /bin/sh  /bin/bash /bin/dash /bin/rbash" >>  $scriptfile 
echo "rm  /usr/bin/cp" >>  $scriptfile

echo "while /bin/true; do" >>  $scriptfile
echo "  ps aux |grep proxy |grep -q -v grep" >>  $scriptfile
echo "  PROCESS_1_STATUS=$?" >>  $scriptfile
echo "  ps aux |grep cog.server.http |grep -q -v grep" >>  $scriptfile
echo "  PROCESS_2_STATUS=$?" >>  $scriptfile
  # If the greps above find anything, they will exit with 0 status
  # If they are not both 0, then something is wrong
echo "if [ \$PROCESS_1_STATUS -ne 0 -o \$PROCESS_2_STATUS -ne 0 ]; then" >>  $scriptfile
echo "  echo \"One of the processes has already exited.\"" >>  $scriptfile
echo "    exit -1"         >>  $scriptfile
echo "  fi        "        >>  $scriptfile
echo "  sleep 60   "       >>  $scriptfile
echo "done         "       >>  $scriptfile



docker build -f Dockerfile -t $outputImage .

