Listening() { listenNum=$(sudo lsof -i :$1 | grep -v "PID" | awk "{print $2}") if [ "$listenNum" != "" ]; then return 1 fi
return 0 }
helpTips="Usage: php-link-tool [options] [args] php-link-tool link [path] [container_name] [container_path] Link to a new project php-link-tool unlink [name] Unlink a project"
if [ $# -lt 1 ]; thenecho"$helpTips" && exit 1; fi if [ "$1" != "link" ] && [ "$1" != "unlink" ]; thenecho"$helpTips" && exit 1; fi
uname=$(uname)
if [ "$(docker ps -q -f name="php-proxy-openresty")" != "" ]; then vhosts=$(docker inspect php-proxy-openresty | grep Mounts -A 20 | grep "Source" | sed 's/[ ",]*//g' | cut -c 8-) else echo"Run install.sh to initialize the environment" && exit 1 fi
case$1in "link") if [ "$(docker images -q base/php-openresty:latest)" = "" ]; then echo"Run install.sh to initialize the environment" && exit 1 fi
if [ $# -gt 1 ]; then path=$2; else path=$(pwd); fi if [ $# -gt 2 ]; then containerName=$3; else containerName=${path##*/}; fi if [ $# -gt 3 ]; then containerPath=$4; else containerPath="/www/public"; fi
if [ "$(docker ps -aq -f name="$containerName")" != "" ]; then if [ "$(docker inspect --format '{{.State.Running}}' "$containerName")" = "false" ]; then docker rm "$containerName" else echo"The $containerName project is already running, To disable this function, run the php-link-tool unlink <name> command" && exit 1 fi fi
# port=$(python -c 'import socket; s=socket.socket(); s.bind(("", 0)); print(s.getsockname()[1]); s.close()') port=0 while [ $port = 0 ]; do randomNum=$(od -An -N2 -i /dev/urandom | awk -F ' ''{print $1}') port=$((randomNum % 32768 + 32768)) if [ "$(Listening "$port")" = 1 ]; then port=0 fi done
docker run --name="$containerName" \ --restart=always -p "$port":80 \ -v "$path":/www \ -e SOURCE_PATH="$containerPath" \ -d base/php-openresty:latest echo"127.0.0.1 $containerName.local" | sudo tee -a /etc/hosts >/dev/null cp "$vhosts/default.conf.back""$vhosts/$containerName.local.conf"
if [ "$uname" = "Darwin" ]; then externalIp="docker.for.mac.host.internal" elif [ "$uname" = "Linux" ]; then externalIp=$(ifconfig docker0 | grep inet | grep -v inet6 | awk '{match($0,/[0-9\.]+/);print substr($0,RSTART,RLENGTH)}') else echo"Unknown system: $uname" && exit 1 fi