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

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

# above options don't require any of the extra processing -- just kick off the script with
# options intact.
if [[ $action == "bypass" ]]; then
	/opt/traffic_ops/install/bin/_postinstall "$@"
	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

# install carton first
cpanm Carton

# carton installs all the perl dependencies in cpanfile
cd /opt/traffic_ops/app

export POSTGRES_HOME=${POSTGRES_HOME:-/usr/pgsql-9.6}
/usr/local/bin/carton

# Install go 
/opt/traffic_ops/install/bin/install_go.sh

# Install go and goose
/opt/traffic_ops/install/bin/install_goose.sh

export PERL5LIB=/opt/traffic_ops/app/lib:/opt/traffic_ops/app/local/lib/perl5
/opt/traffic_ops/install/bin/_postinstall "$@"

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