#!/bin/bash -eu

# Copyright 2019 Imply Data, Inc.
#
# 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.

PWD="$(pwd)"
WHEREAMI="$(dirname "$0")"
WHEREAMI="$(cd "$WHEREAMI" && pwd)"

if [ $# -ne 2 ]
then
  echo "usage: $0 dir command ..." >&2
  exit 2
fi

OS="$(uname)"
INCLUDED_SVLOGD="$(which svlogd)" || echo "Svlogd installation not found"
if [ -z $INCLUDED_SVLOGD ]; then
  case "$OS" in
    'Linux')
      INCLUDED_SVLOGD="$WHEREAMI"/svlogd-linux-amd64
      ;;
    'Darwin')
      xattr -cr "$WHEREAMI"/svlogd-macos
      INCLUDED_SVLOGD="$WHEREAMI"/svlogd-macos
      ;;
    *)
      ;;
  esac
fi


SVLOGD="${SVLOGD:-$INCLUDED_SVLOGD}"

mkdir -p "$1"

if [ "$SVLOGD" != "" ]
then
  # Make sure we can actually run svlogd.
  # Just because the OS matches doesn't mean the binary will run.
  if "$SVLOGD" 2>&1 | grep -q "usage:"
  then
    exec "$WHEREAMI"/svlogd-wrapper "$SVLOGD" "$1" "$2"
  fi
fi

# Fallback to just writing to a file without rotation.
exec >> "$1"/current
exec 2>&1
exec sh -c "exec $2"
