#!/bin/bash

#--
# Copyright 2012 Red Hat, 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.
#++

# Restore applications

# oo-restorer turns an idle application back on making it available to serve
# requests again.

function print_help {
    echo "Usage: $0"
    echo "  -u UUID  (app to restore UUID)"
    exit 1
}


while getopts 'u:d' OPTION
do
case $OPTION in
        u) uuid=$OPTARG
    ;;
        d) set -x
    ;;
        ?) print_help
    ;;
esac
done

if [ -z "$uuid" ] || ! [ -d "/var/lib/openshift/$uuid" ]
then
    print_help
fi

source /usr/libexec/openshift/cartridges/abstract/info/lib/util
source "/var/lib/openshift/${uuid}/.env/OPENSHIFT_HOMEDIR"

# Turn user application back on.
framework_carts=$(get_installed_framework_carts)
primary_framework_cart=${framework_carts[0]}

stop_lock_file="${OPENSHIFT_HOMEDIR}/${primary_framework_cart}/run/stop_lock"
if [ -f "$stop_lock_file" ]
then
    rm "$stop_lock_file"
else
    # Do not restore non-idled application. Browser may cause 20+ retries when restoring application.
    exit 0
fi

# code copied from node/lib/util_ext
runuser --shell /bin/sh "$uuid" -c "echo started >$OPENSHIFT_HOMEDIR/app-root/runtime/.state"

/usr/sbin/oo-admin-ctl-gears startgear "${uuid}"

HTTP_DIR=`dirname "/etc/httpd/conf.d/openshift/${uuid}"*/00000_default.conf`

# Enable proxy setup
sed -i "s/#ProxyPass/ProxyPass/g" $HTTP_DIR/*.conf

rm -f $HTTP_DIR/0000000000000_disabled.conf

service httpd graceful
/usr/bin/logger -p local0.notice -t oo_restorer "Restored: ${uuid}"
