#!/bin/bash
# Copyright 2016 The Kubernetes Authors All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -o errexit
set -o nounset
set -o pipefail

NODEUP_URL=NUSource
NODEUP_HASH=NUSHash

export AWS_REGION=eu-west-1


echo "http_proxy=http://example.com:80" >> /etc/environment
echo "https_proxy=http://example.com:80" >> /etc/environment
echo "no_proxy=" >> /etc/environment
echo "NO_PROXY=" >> /etc/environment
while read in; do export $in; done < /etc/environment
case `cat /proc/version` in
*[Dd]ebian*)
  echo "Acquire::http::Proxy \"${http_proxy}\";" > /etc/apt/apt.conf.d/30proxy ;;
*[Uu]buntu*)
  echo "Acquire::http::Proxy \"${http_proxy}\";" > /etc/apt/apt.conf.d/30proxy ;;
*[Rr]ed[Hh]at*)
  echo "http_proxy=${http_proxy}" >> /etc/yum.conf ;;
esac
echo "DefaultEnvironment=\"http_proxy=${http_proxy}\" \"https_proxy=${http_proxy}\" \"NO_PROXY=${no_proxy}\" \"no_proxy=${no_proxy}\"" >> /etc/systemd/system.conf
systemctl daemon-reload
systemctl daemon-reexec


function ensure-install-dir() {
  INSTALL_DIR="/var/cache/kubernetes-install"
  # On ContainerOS, we install to /var/lib/toolbox install (because of noexec)
  if [[ -d /var/lib/toolbox ]]; then
    INSTALL_DIR="/var/lib/toolbox/kubernetes-install"
  fi
  mkdir -p ${INSTALL_DIR}
  cd ${INSTALL_DIR}
}

# Retry a download until we get it. args: name, sha, url1, url2...
download-or-bust() {
  local -r file="$1"
  local -r hash="$2"
  shift 2

  urls=( $* )
  while true; do
    for url in "${urls[@]}"; do
      commands=(
        "curl -f --ipv4 --compressed -Lo "${file}" --connect-timeout 20 --retry 6 --retry-delay 10"
        "wget --inet4-only --compression=auto -O "${file}" --connect-timeout=20 --tries=6 --wait=10"
        "curl -f --ipv4 -Lo "${file}" --connect-timeout 20 --retry 6 --retry-delay 10"
        "wget --inet4-only -O "${file}" --connect-timeout=20 --tries=6 --wait=10"
      )
      for cmd in "${commands[@]}"; do
        echo "Attempting download with: ${cmd} {url}"
        if ! (${cmd} "${url}"); then
          echo "== Download failed with ${cmd} =="
          continue
        fi
        if [[ -n "${hash}" ]] && ! validate-hash "${file}" "${hash}"; then
          echo "== Hash validation of ${url} failed. Retrying. =="
          rm -f "${file}"
        else
          if [[ -n "${hash}" ]]; then
            echo "== Downloaded ${url} (SHA1 = ${hash}) =="
          else
            echo "== Downloaded ${url} =="
          fi
          return
        fi
      done
    done

    echo "All downloads failed; sleeping before retrying"
    sleep 60
  done
}

validate-hash() {
  local -r file="$1"
  local -r expected="$2"
  local actual

  actual=$(sha256sum ${file} | awk '{ print $1 }') || true
  if [[ "${actual}" != "${expected}" ]]; then
    echo "== ${file} corrupted, hash ${actual} doesn't match expected ${expected} =="
    return 1
  fi
}

function split-commas() {
  echo $1 | tr "," "\n"
}

function try-download-release() {
  # TODO(zmerlynn): Now we REALLY have no excuse not to do the reboot
  # optimization.

  local -r nodeup_urls=( $(split-commas "${NODEUP_URL}") )
  if [[ -n "${NODEUP_HASH:-}" ]]; then
    local -r nodeup_hash="${NODEUP_HASH}"
  else
  # TODO: Remove?
    echo "Downloading sha256 (not found in env)"
    download-or-bust nodeup.sha256 "" "${nodeup_urls[@]/%/.sha256}"
    local -r nodeup_hash=$(cat nodeup.sha256)
  fi

  echo "Downloading nodeup (${nodeup_urls[@]})"
  download-or-bust nodeup "${nodeup_hash}" "${nodeup_urls[@]}"

  chmod +x nodeup
}

function download-release() {
  # In case of failure checking integrity of release, retry.
  until try-download-release; do
    sleep 15
    echo "Couldn't download release. Retrying..."
  done

  echo "Running nodeup"
  # We can't run in the foreground because of https://github.com/docker/docker/issues/23793
  ( cd ${INSTALL_DIR}; ./nodeup --install-systemd-unit --conf=${INSTALL_DIR}/kube_env.yaml --v=8  )
}

####################################################################################

/bin/systemd-machine-id-setup || echo "failed to set up ensure machine-id configured"

echo "== nodeup node config starting =="
ensure-install-dir

cat > cluster_spec.yaml << '__EOF_CLUSTER_SPEC'
cloudConfig:
  nodeTags: something
docker:
  logLevel: INFO
kubeProxy:
  cpuLimit: 30m
  cpuRequest: 30m
  featureGates:
    AdvancedAuditing: "true"
  memoryLimit: 30Mi
  memoryRequest: 30Mi
kubelet:
  kubeconfigPath: /etc/kubernetes/config.txt

__EOF_CLUSTER_SPEC

cat > ig_spec.yaml << '__EOF_IG_SPEC'
fileAssets:
- content: xYagtQLwBAAi3V8Wc2Jrojz28I0= (fingerprint)
  name: tokens
  path: /kube/tokens.csv
hooks:
- manifest: 8BN3anFUyDlkVF/JnaJqbwpq8ME= (fingerprint)
  name: apply-to-all.service
kubelet:
  kubeconfigPath: /etc/kubernetes/igconfig.txt
nodeLabels:
  label2: value2
  labelname: labelvalue
taints:
- key1=value1:NoSchedule
- key2=value2:NoExecute

__EOF_IG_SPEC

cat > kube_env.yaml << '__EOF_KUBE_ENV'
{}

__EOF_KUBE_ENV

download-release
echo "== nodeup node config done =="
