#!/usr/bin/env bash
# 文件名: skopeo_deploy.sh
# 作者: 树辉<shuhui@vqiu.cn>
# vim:sw=4:ts=4:et

set -e

# 终端颜色定义
txtbld=$(tput bold)             # Bold
bldred=${txtbld}$(tput setaf 1) # red
bldgre=${txtbld}$(tput setaf 2) # green
bldylw=${txtbld}$(tput setaf 3) # yellow
txtrst=$(tput sgr0)             # Reset
err=${bldred}ERROR${txtrst}
info=${bldgre}INFO${txtrst}
warn=${bldylw}WARNING${txtrst}

name=skopeo
temp_path=$(mktemp -d)
version=1.17.0
conf_dir=/etc/containers

# 判断环境平台
if [ -z "${ARCH}" ]; then
  case $(uname -m) in
    x86_64) ARCH=amd64 ;;
    aarch64) ARCH=arm64 ;;
    *) printf "$err: 不支持该平台 $(uname -m)"; exit 1 ;;
  esac
fi

sed -n -e '1,/^exit 0$/!p' $0 > ${temp_path}/${name}-${version}.tar.xz 2>/dev/null

cd ${temp_path}
printf "$info: [ ${bldgre}${name}-${version}${txtrst} ] 安装中...\n"

if [[ ! -e /usr/bin/${name} ]]
then
    tar axvf ${temp_path}/${name}-${version}.tar.xz -C ${temp_path} >/dev/null
    cp -rf ${temp_path}/${name}-${version}-${ARCH} /usr/bin/${name} >/dev/null
    chmod +x /usr/bin/${name}
    rm -rf ${temp_path}
fi

test -d ${conf_dir} || mkdir -p ${conf_dir}

cat >${conf_dir}/policy.json<<EOF
{
  "default": [
    {
      "type": "insecureAcceptAnything"
    }
  ],
  "transports": {
    "docker": {
      "registry.access.redhat.com": [
        {
          "type": "signedBy",
          "keyType": "GPGKeys",
          "keyPath": "/etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release"
        }
      ],
      "registry.redhat.io/redhat/redhat-operator-index": [
        {
          "type": "insecureAcceptAnything"
        }
      ],
      "registry.redhat.io": [
        {
          "type": "signedBy",
          "keyType": "GPGKeys",
          "keyPath": "/etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release"
        }
      ]
    },
    "docker-daemon": {
      "": [
        {
          "type": "insecureAcceptAnything"
        }
      ]
    }
  }
}
EOF

printf "$info: [ ${bldgre}${name}${txtrst} ] 安装完成!\n"
rm -rf ${temp_path}
exit 0
