#!/bin/bash

#
# 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.
#

trap 'echo "Error on line ${LINENO} of ${0}"; exit 1' ERR
set -o errexit -o nounset

for arg in "$@"; do
	case $arg in
		-h*) action=bypass;;
		-defaults*) action=bypass;;
		-n*) action=bypass;;
	esac
done

PATH+=:/usr/libexec/
python_bin="$(command -v {python,platform-python}{3{{.,}{9,8,7,6},},2{7,.7,},} | head -n1)"
if [[ -z "$python_bin" ]]; then
	echo 'No python3 or python2 executable was found. Python is required to run the Postinstall script.' >/dev/stderr
	exit 1
fi

# above options don't require any of the extra processing -- just kick off the script with
# options intact.
if [[ -v action && "$action" == "bypass" ]]; then
	"$python_bin" /opt/traffic_ops/install/bin/_postinstall.py "$@"
	exit
fi

# make sure installed with proper permissions
umask 022

if [[ ! $(su - postgres psql -w -c 'show is_superuser' </dev/null 2>/dev/null) =~ 'on' ]]; then
	echo >&2 "postinstall requires the postgres user to have superuser access to postgresql. Aborting."
	exit 1
fi

"$python_bin" /opt/traffic_ops/install/bin/_postinstall.py "$@"

# should all be owned by trafops user
chown -R trafops:trafops /opt/traffic_ops
