#!/bin/bash

# Copyright (c) 2017 Tigera, Inc. 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.

# This wrapper script  runs the calico-felix binary and restarts it if it
# exits for a config change, which is signalled by an exit code of 129,
# as used by SIGHUP.

# Pass signals sent to this script through to Felix.
trap 'echo "calico-felix-wrapper: SIGINT received, passing on to calico-felix"; kill -INT $pid' SIGINT
trap 'echo "calico-felix-wrapper: SIGTERM received, passing on to calico-felix"; kill -TERM $pid' SIGTERM
trap 'echo "calico-felix-wrapper: SIGHUP received, passing on to calico-felix"; kill -HUP $pid' SIGHUP

rc=unknown

if [ "$SET_CORE_PATTERN" == "true" ]; then
  echo '/tmp/core_%h_%e.%p' > /proc/sys/kernel/core_pattern
fi

# When Felix is run in a non-root netns (for FV testing) the conntrack subsystem doesn't
# start tracking packets until it is used in some way.  This means that Felix's datastore
# connection ends up being untracked, causing it to be dropped in BPF mode.
iptables -A FORWARD -m conntrack --ctstate ESTABLISHED -m comment --comment "cali:workaround"

while true; do
  if [ "$DELAY_FELIX_START" == "true" ]; then
    while [ ! -e /start-trigger ]; do
      echo "calico-felix-wrapper: Delaying starting felix..."
      sleep 1
    done
  fi

  source /extra-env.sh

  echo "calico-felix-wrapper: Starting calico-felix"
  calico-felix &
  pid=$!
  echo "calico-felix-wrapper: Started calico-felix, PID=$pid"
  wait $pid
  rc=$?
  echo "calico-felix-wrapper: Process stopped, RC=$rc"
  if [ "$rc" == "129" ]; then
    echo "calico-felix-wrapper: Restarting calico-felix for config reload"
    while [ -e /delay-felix-restart ]; do
      echo "Waiting for felix restart to be triggered..."
      sleep 1
    done
    continue
  fi
  echo "calico-felix-wrapper: Exiting due to non-config shutdown RC=$rc"
  break
done
