#!/usr/bin/env bash
# author: joe.zheng
# version: 24.04.02

set -e

# @self {
# AUTO-GENERATED, DO NOT EDIT!

SELF="$(basename $0)"
SELF_VERSION="$(sed -n '1,4s/# version: \(.*\)/\1/p' $0)"

# @self }
NAME="${SELF#*-}"

VERSION="1.7.14"      # version to install
CUR_VER=              # current version if any
UNINSTALL=n           # reset the deployment and uninstall components

ARCH="$(uname -m | sed 's/x86_64/amd64/')"
VARIANT="$(uname -s | tr A-Z a-z)-$ARCH"
INSTALL_DIR_BIN="/usr/local/bin"
INSTALL_DIR_SVC="/lib/systemd/system"
INSTALL_DIR_CFG="/etc/systemd/system"
ETC_CFG="/etc/$NAME/config.toml"
SVC_BIN="$INSTALL_DIR_SVC/$NAME.service"
SVC_CFG="$INSTALL_DIR_CFG/$NAME.service.d/http-proxy.conf"

BASEURL="https://github.com/containerd/containerd"

RUNC_VERSION="${RUNC_VERSION:-1.1.12}"
RUNC_BASEURL="https://github.com/opencontainers/runc"

# @dry-run {
# AUTO-GENERATED, DO NOT EDIT!

DRY_RUN="${DRY_RUN:-n}"        # "y" to enable
RUN=''                         # command prefix for dry run
if [[ $DRY_RUN == 'y' ]]; then
  RUN='echo'
fi

# @dry-run }

function usage() {
  cat <<EOF
Usage: $SELF [-m <type>] [-v <ver>] [-U] [-n] [-h]

  Setup $NAME the easy way

  -m <type>: install via mirror [$MIRRORS], default: $MIRROR
  -v <ver>:  target version, default: $VERSION
  -U:        uninstall it, default: $UNINSTALL
  -n:        print information only, default: $DRY_RUN
  -h:        print the usage message

Cache:

  To speed up deployment, the required files will be cached at "$CACHE"

Environment variables:

  MIRROR_URL:    mirror to use for GitHub, default: $MIRROR_URL
  OFFLINE:       force into offline mode [y n], default: $OFFLINE
  RUNC_VERSION:  version of runc, default: $RUNC_VERSION

Examples:

  1. Install $NAME
     $SELF

  2. Uninstall $NAME
     $SELF -U

  3. Install $NAME with specific version
     $SELF -v $VERSION

Version: $SELF_VERSION
EOF

}

function main() {
  # ensure the right one is used
  PATH=$INSTALL_DIR_BIN:$PATH

  # adjust default version if already deployed
  CUR_VER="$(current_version)"
  VERSION="${CUR_VER:-$VERSION}"

  while getopts ":m:v:hnU" opt
  do
    case $opt in
      m ) MIRROR=$OPTARG
          if echo $MIRRORS | grep -v -w $MIRROR >/dev/null 2>&1; then
            err "invalid mirror option $MIRROR"
            usage && exit 1
          fi
          ;;
      v ) VERSION=${OPTARG#v};;
      U ) UNINSTALL=y;;
      n ) DRY_RUN=y && RUN='echo';;
      h ) usage && exit;;
      * ) usage && echo "invalid option: -$OPTARG" && exit 1;;
    esac
  done
  shift $((OPTIND-1))

  for v in CACHE DRY_RUN MIRROR MIRROR_URL RUNC_VERSION UNINSTALL VERSION CUR_VER
  do
    eval echo "$v: \${$v}"
  done

  [[ $DRY_RUN == "y" ]] && exit

  validate_sudo
  check_prerequisites
  check_network
  check_mirror
  ensure_workdir
  ensure_cached
  if [[ $UNINSTALL == "y" ]]; then
    ensure_uninstalled
  else
    ensure_installed
  fi

  msg "done"
}

function current_version() {
  local version=
  if [[ -n $(which $NAME) ]]; then
    version="$($NAME -v | cut -d' ' -f3)"
    version=${version#v}
  fi
  echo $version
}

function check_prerequisites() {
  msg "check prerequisites"
  if [[ -z $(which curl) ]]; then
    err "curl is not available"
    exit 1
  fi
}

function ensure_cached() {
  msg "ensure files are cached"

  local pkg_file="$NAME-$VERSION-$VARIANT.tar.gz"
  local pkg_dir="$CACHE_PACKAGES/common/$NAME-$VERSION"
  local pkg_dir_runc="$CACHE_PACKAGES/common/runc-$RUNC_VERSION"

  mkdir -p $pkg_dir $pkg_dir_runc

  if [[ $OFFLINE == "y" ]]; then
    msg "WARNING: offline mode, cache must be ready"
  else
    local url="$(mirror_url $BASEURL)"
    local url_runc="$(mirror_url $RUNC_BASEURL)"

    download_file "$url/raw/main/$NAME.service" "$pkg_dir/$NAME.service"
    download_file "$url/releases/download/v$VERSION/$pkg_file" "$pkg_dir/$pkg_file"
    download_file "$url_runc/releases/download/v$RUNC_VERSION/runc.$ARCH" "$pkg_dir_runc/runc"
  fi

  msg "extract package to $CACHE_RUN"
  tar xzf $pkg_dir/$pkg_file -C $CACHE_RUN
}

function ensure_installed() {
  msg "ensure $NAME is installed"

  local pkg_dir="$CACHE_PACKAGES/common/$NAME-$VERSION"
  local pkg_dir_runc="$CACHE_PACKAGES/common/runc-$RUNC_VERSION"

  if [[ -n $CUR_VER ]]; then
    msg "version $CUR_VER has already installed"
    if [[ $CUR_VER != $VERSION ]]; then
      msg "WARNING: the installed version is not the target $VERSION"
      msg "uninstall current version with following command and install again:"
      msg "  $SELF -U"
    fi
  else
    msg "install $NAME to $INSTALL_DIR_BIN"
    $SUDO install -t $INSTALL_DIR_BIN $CACHE_RUN/bin/*
    msg "create default config: $ETC_CFG"
    $SUDO mkdir -p $(dirname $ETC_CFG)
    $NAME config default | $SUDO tee $ETC_CFG >/dev/null

    msg "create service config: $SVC_CFG"
    $SUDO cp $pkg_dir/$NAME.service $SVC_BIN
    $SUDO mkdir -p $(dirname $SVC_CFG)
    cat <<EOF | $SUDO tee $SVC_CFG
[Service]
Environment="HTTP_PROXY=$http_proxy"
Environment="HTTPS_PROXY=$https_proxy"
Environment="NO_PROXY=$no_proxy"
EOF
    $SUDO systemctl daemon-reload
    $SUDO systemctl enable --now $NAME

    msg "install runc"
    $SUDO install -t $INSTALL_DIR_BIN $pkg_dir_runc/runc

    cat <<EOF

# here are some tips to follow:
# check the current configuration
containerd config dump

# pull container image
sudo ctr image pull docker.io/library/busybox:latest

# create and run a container
sudo ctr run --rm -t docker.io/library/busybox:latest test
EOF
  fi
}

function ensure_uninstalled() {
  msg "ensure $NAME is uninstalled"

  if [[ -n $CUR_VER ]]; then
    msg "uninstall $NAME"
    $SUDO systemctl stop $NAME || true
    $SUDO rm -f $SVC_BIN
    $SUDO systemctl daemon-reload
    for f in $CACHE_RUN/bin/*; do
      $SUDO rm -f $INSTALL_DIR_BIN/${f##*/}
    done

    msg "try to delete config files"
    for f in $ETC_CFG $SVC_CFG; do
      read -p "delete $f? y/N: " result
      if [[ $result == "y" ]]; then
        $SUDO rm -f $f
        msg "deleted: $f"
      fi
    done

    msg "uninstall runc"
    $SUDO rm -f $INSTALL_DIR_BIN/runc
  else
    msg "already uninstalled"
  fi
}

# @base {
# AUTO-GENERATED, DO NOT EDIT!

function msg {
  echo "> $@"
}

function err {
  echo "> $@" >&2
}

function has() {
  [[ -z "${1##*$2*}" ]] && [[ -z "$2" || -n "$1" ]]
}

# @base }

# @sudo {
# AUTO-GENERATED, DO NOT EDIT!

SUDO="sudo"
if [[ $(id -u) == "0" ]]; then
  SUDO=""
fi

function validate_sudo() {
  if [[ -n $SUDO ]]; then
    msg "validate sudo"
    sudo -v
  fi
}

# @sudo }

# @network {
# AUTO-GENERATED, DO NOT EDIT!

OFFLINE="${OFFLINE:-n}"                           # no external network
MIRROR="${MIRROR:-auto}"                          # mirror option to use
MIRRORS="yes no auto"                             # valid mirror options
USE_MIRROR="${USE_MIRROR:-n}"                     # need to use mirror
MIRROR_URL="${MIRROR_URL:-https://iffi.me/proxy}" # mirror or http proxy to use
URL_TO_CHECK="${URL_TO_CHECK:-https://raw.githubusercontent.com}"

# the target URL is reachable but the response may be 4xx or 5xx
function can_access() {
   curl -IL -s -m 5 $1 >/dev/null 2>&1
}

function check_network() {
  msg "check network"
  if [[ $OFFLINE != 'y' ]]; then
    if ! can_access example.com; then
      msg "can't access external network"
      OFFLINE="y"
    fi
  fi
  msg "offline mode: $OFFLINE"
}

function check_mirror() {
  msg "use mirror or not"

  local mirror;
  if [[ $MIRROR == "auto" ]]; then
    mirror="yes" # default as needed
    if [[ $OFFLINE == "y" ]]; then
      msg "offline mode, assume mirror is needed"
    else
      local target="$URL_TO_CHECK"
      msg "check whether we can access $target"
      if can_access $target; then
        msg "curl $target is OK"
        mirror="no"
      else
        msg "curl $target is FAILED"
      fi
    fi
  fi
  if [[ $MIRROR == "yes" || $mirror == "yes" ]]; then
    msg "mirror is needed"
    if can_access $MIRROR_URL; then
      USE_MIRROR="y"
    else
      err "failed to access mirror ($MIRROR_URL)"
    fi
  fi
  msg "use mirror: $USE_MIRROR"
}

function mirror_url() {
  local origin="${1:?argument missing}"

  if [[ $USE_MIRROR == "y" ]]; then
    echo -n "$MIRROR_URL/$origin"
  else
    echo -n "$origin"
  fi
}

# @network }

# @cache {
# AUTO-GENERATED, DO NOT EDIT!

CACHE="${CACHE:-cache}"                                    # the cache directory
CACHE_RUN="${CACHE_RUN:-$CACHE/run/$SELF}"                 # runtime generated files
CACHE_IMAGES="${CACHE_IMAGES:-$CACHE/images}"              # exported container images
CACHE_PACKAGES="${CACHE_PACKAGES:-$CACHE/packages}"        # software packages, e.g. .deb, .tar.gz
CACHE_MANIFESTS="${CACHE_MANIFESTS:-$CACHE/manifests}"     # manifest files in YAML format
CACHE_DOWNLOADING="${CACHE_DOWNLOADING:-$CACHE/.download}" # temporary directory for downloading

function ensure_workdir() {
  msg "ensure workdir"

  for d in $CACHE_RUN $CACHE_IMAGES $CACHE_PACKAGES $CACHE_MANIFESTS $CACHE_DOWNLOADING; do
    if [[ ! -d $d ]]; then
      msg "create dir: $d"
      mkdir -p $d
    fi
  done
}

function download_file() {
  local src="${1:?missing source url}"
  local dst="${2:?missing destination}"

  if [[ -f "$dst" ]]; then
    msg "already exist: $dst"
  else
    msg "download: $src"
    local tmp="$CACHE_DOWNLOADING/$(basename $dst)"
    $RUN curl -fsSL $src > $tmp
    $RUN mkdir -p $(dirname $dst) && mv $tmp $dst
    msg "saved at: $dst"
  fi
}

# @cache }

main "$@"
