# !/bin/bash

# 检查 Docker 是否安装
if ! [ -x "$(command -v docker)" ]; then
  echo 'Error: Docker is not installed.' >&2
  exit 1
fi
echo 'Docker is installed.'

# 检查是否有正在运行的 IPFS 容器
if [ "$(docker ps -q -f name=ipfs_host)" ]; then
  echo 'Error: An IPFS container is already running.' >&2
  exit 1
fi
echo 'No running IPFS container found.'

# 检查是否有同名的停止状态的 IPFS 容器
if [ "$(docker ps -aq -f status=exited -f name=ipfs_host)" ]; then
  echo 'Error: A stopped IPFS container with the same name already exists.' >&2
  exit 1
fi
echo 'No stopped IPFS container with the same name found.'

echo 'Proceeding with deployment...'
# 创建存储目录
current_dir=$(pwd)
cd $current_dir
mkdir -p ./ipfs_staging
mkdir -p ./ipfs_data

echo 'Storage directories created.'

# 设置环境变量
export ipfs_staging=./ipfs_staging
export ipfs_data=./ipfs_data
export ipfs_swarm_port=4002
export ipfs_api_port=8080
export ipfs_gateway_port=5001

echo "IPFS staging directory: ${ipfs_staging}"
echo "IPFS data directory: ${ipfs_data}"
echo "IPFS swarm port: ${ipfs_swarm_port}"
echo "IPFS API port: ${ipfs_api_port}"
echo "IPFS gateway port: ${ipfs_gateway_port}"

# 运行 IPFS 容器
docker run -d --name ipfs_host -v ${ipfs_staging}:/export -v ${ipfs_data}:/data/ipfs -p ${ipfs_swarm_port}:4001 -p ${ipfs_api_port}:8080 -p ${ipfs_gateway_port}:5001 ipfs/kubo:latest
if [ $? -ne 0 ]; then
  docker rm -f ipfs_host 2>/dev/null
  rm -rf ./ipfs_staging
  rm -rf ./ipfs_data
  echo 'Error: Failed to start the IPFS container.' >&2
  exit 1
fi
echo 'IPFS container started successfully.'

open "http://localhost:${ipfs_gateway_port}/webui"