filesystem: "root"
mode: 0755
path: "/usr/local/bin/etcd-snapshot-restore.sh"
contents:
  inline: |
    #!/usr/bin/env bash

    set -o errexit
    set -o pipefail

    # example
    # ./etcd-snapshot-restore.sh $path-to-snapshot $inital_cluster

    if [[ $EUID -ne 0 ]]; then
      echo "This script must be run as root"
      exit 1
    fi

    usage () {
        echo 'Path to snapshot and initial cluster are required: ./etcd-snapshot-restore.sh $path-to-snapshot $initial_cluster'
        exit 1
    }

    if [ "$1" == "" ] || [ "$2" == "" ]; then
        usage
    fi

    SNAPSHOT_FILE="$1"
    ETCD_INITIAL_CLUSTER="$2"
    ASSET_DIR=./assets
    CONFIG_FILE_DIR=/etc/kubernetes
    MANIFEST_DIR="${CONFIG_FILE_DIR}/manifests"
    MANIFEST_STOPPED_DIR="${ASSET_DIR}/manifests-stopped"
    RUN_ENV=/run/etcd/environment

    ETCD_VERSION=v3.3.10
    ETCDCTL="${ASSET_DIR}/bin/etcdctl"
    ETCD_DATA_DIR=/var/lib/etcd
    ETCD_MANIFEST="${MANIFEST_DIR}/etcd-member.yaml"
    ETCD_STATIC_RESOURCES="${CONFIG_FILE_DIR}/static-pod-resources/etcd-member"
    STOPPED_STATIC_PODS="${ASSET_DIR}/tmp/stopped-static-pods"

    source "/usr/local/bin/openshift-recovery-tools"

    function run {
      init
      dl_etcdctl
      backup_manifest
      DISCOVERY_DOMAIN=$(grep -oP '(?<=discovery-srv=).*[^"]' $ASSET_DIR/backup/etcd-member.yaml )
      if [ -z "$DISCOVERY_DOMAIN" ]; then
        echo "Discovery domain can not be extracted from $ASSET_DIR/backup/etcd-member.yaml"
        exit 1
      fi
      validate_environment
      source /run/etcd/environment
      ETCD_NAME=$(validate_etcd_name)
      stop_static_pods
      stop_etcd
      stop_kubelet
      stop_all_containers
      backup_data_dir
      remove_data_dir
      restore_snapshot
      start_static_pods
      start_kubelet
    }

    run
