#!/usr/bin/env bash

# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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

# description: ambari-agent daemon
# processname: ambari-agent

# /etc/init.d/ambari-agent

VERSION="${ambariVersion}"
HASH="${buildNumber}"

case "$1" in
  --version)
        echo -e $VERSION
        exit 0
        ;;
  --hash)
        echo -e $HASH
        exit 0
        ;;
esac

export PATH=/usr/sbin:/sbin:/usr/lib/ambari-server/*:$PATH
export AMBARI_CONF_DIR=/etc/ambari-server/conf:$PATH

# Because Ambari rpm unpacks modules here on all systems
export PYTHONPATH=/usr/lib/python2.6/site-packages:$PYTHONPATH

AMBARI_AGENT=ambari-agent
PYTHON_WRAP=/var/lib/ambari-agent/ambari-python-wrap
PIDFILE=/var/run/ambari-agent/$AMBARI_AGENT.pid
OUTFILE=/var/log/ambari-agent/ambari-agent.out
LOGFILE=/var/log/ambari-agent/ambari-agent.log
AGENT_SCRIPT=/usr/lib/python2.6/site-packages/ambari_agent/main.py
AMBARI_AGENT_PY_SCRIPT=/usr/lib/python2.6/site-packages/ambari_agent/AmbariAgent.py
OK=1
NOTOK=0

current_user=`id -u -n`

if [ "$EUID" -ne 0 ] ; then
  echo "" | sudo -S -l > /dev/null 2>&1
  if [ "$?" != "0" ] ; then
    echo "You can't perform this operation as non-sudoer user. Please, re-login or configure sudo access for this user."
    exit 0
  fi
fi

keysdir=$(awk -F "=" '/keysdir/ {print $2}' /etc/ambari-agent/conf/ambari-agent.ini)
# trim spaces
keysdir=${keysdir// }
keysdir=${keysdir%% }

change_files_permissions() {
    if [ ! -z "$keysdir" ]; then
        ambari-sudo.sh chown -R $current_user "$keysdir"
    fi
	ambari-sudo.sh chown -R $current_user "/var/run/ambari-agent/"
	ambari-sudo.sh chown -R $current_user "/var/log/ambari-agent/"
	ambari-sudo.sh chown -R $current_user "/var/lib/ambari-agent/data/"
	ambari-sudo.sh chown -R $current_user "/var/lib/ambari-agent/cache/"
	ambari-sudo.sh chown 	$current_user "/usr/lib/ambari-agent/"
}

# fills $PYTHON
. $PYTHON_WRAP -V 2>/dev/null

export PYTHON=$PYTHON

# Trying to read the passphrase from an environment
if [ ! -z $AMBARI_PASSPHRASE ]; then
  RESOLVED_AMBARI_PASSPHRASE=$AMBARI_PASSPHRASE
fi

# Reading the environment file
if [ -a /var/lib/ambari-agent/ambari-env.sh ]; then
  /var/lib/ambari-agent/ambari-sudo.sh chown -R $current_user "/var/lib/ambari-agent/ambari-env.sh"
  . /var/lib/ambari-agent/ambari-env.sh
fi

if [ ! -z $AMBARI_LOG_DIR ]; then
  LOGFILE=$AMBARI_LOG_DIR/ambari-agent.log
fi

if [ -z $RESOLVED_AMBARI_PASSPHRASE ] &&  [ ! -z $AMBARI_PASSPHRASE ]; then
  RESOLVED_AMBARI_PASSPHRASE=$AMBARI_PASSPHRASE
  # If the passphrase is not defined yet, use the value from the env file
elif [ -z $RESOLVED_AMBARI_PASSPHRASE ]; then
  # Passphrase is not defined anywhere, set the default value
  RESOLVED_AMBARI_PASSPHRASE="DEV"
fi

export AMBARI_PASSPHRASE=$RESOLVED_AMBARI_PASSPHRASE

#echo $AMBARI_PASSPHRASE

# check for version
check_python_version ()
{
  echo "Verifying Python version compatibility..."
  majversion=`$PYTHON -V 2>&1 | awk '{print $2}' | cut -d'.' -f1`
  minversion=`$PYTHON -V 2>&1 | awk '{print $2}' | cut -d'.' -f2`
  numversion=$(( 10 * $majversion + $minversion))
  if (( $numversion < 26 )); then
    echo "ERROR: Found Python version $majversion.$minversion. Ambari Agent requires Python version > 2.6"
    return $NOTOK
  fi
  echo "Using python " $PYTHON
  return $OK
}

retcode=0

case "$1" in
  start)
        check_python_version
        if [ "$?" -eq "$NOTOK" ]; then
          exit -1
        fi
        echo "Checking for previously running Ambari Agent..."
        if [ -f $PIDFILE ]; then
          PID=`cat $PIDFILE`
          if ! (ps -p $PID >/dev/null 2>/dev/null); then
            echo "$PIDFILE found with no process. Removing $PID..."
            ambari-sudo.sh rm -f $PIDFILE
          else
            tput bold
            echo "ERROR: $AMBARI_AGENT already running"
            tput sgr0
            echo "Check $PIDFILE for PID."
            exit -1
          fi
        fi
        change_files_permissions
        
        echo "Starting ambari-agent"
        nohup $PYTHON $AMBARI_AGENT_PY_SCRIPT "$@" > $OUTFILE 2>&1 &
        sleep 2
        PID=$!
        echo "Verifying $AMBARI_AGENT process status..."
        if ! (ps -p $PID >/dev/null 2>/dev/null); then
          if [ -s $OUTFILE ]; then
            echo "ERROR: $AMBARI_AGENT start failed. For more details, see $OUTFILE:"
            echo "===================="
            tail -n 10 $OUTFILE
            echo "===================="
          else
            echo "ERROR: $AMBARI_AGENT start failed"
          fi
          echo "Agent out at: $OUTFILE"
          echo "Agent log at: $LOGFILE"
          exit -1
        fi
        tput bold
        echo "Ambari Agent successfully started"
        tput sgr0
        echo "Agent PID at: $PIDFILE"
        echo "Agent out at: $OUTFILE"
        echo "Agent log at: $LOGFILE"
        ;;
  status)
        if [ -f $PIDFILE ]; then
          PID=`cat $PIDFILE`
          echo "Found $AMBARI_AGENT PID: $PID"
          if ! (ps -p $PID >/dev/null 2>/dev/null); then
            echo "$AMBARI_AGENT not running. Stale PID File at: $PIDFILE"
            retcode=2
          else
            tput bold
            echo "$AMBARI_AGENT running."
            tput sgr0
            echo "Agent PID at: $PIDFILE"
            echo "Agent out at: $OUTFILE"
            echo "Agent log at: $LOGFILE"
          fi
        else
          tput bold
          echo "$AMBARI_AGENT currently not running"
          tput sgr0
          retcode=3
        fi
        ;;
  stop)
        check_python_version
        if [ "$?" -eq "$NOTOK" ]; then
          exit -1
        fi
        if [ -f $PIDFILE ]; then
          PID=`cat $PIDFILE`
          echo "Found $AMBARI_AGENT PID: $PID"
          if ! (ps -p $PID >/dev/null 2>/dev/null); then
            tput bold
            echo "ERROR: $AMBARI_AGENT not running. Stale PID File at: $PIDFILE"
            tput sgr0
          else
            echo "Stopping $AMBARI_AGENT"
            change_files_permissions
            $PYTHON $AGENT_SCRIPT stop
          fi
          echo "Removing PID file at $PIDFILE"
          ambari-sudo.sh rm -f $PIDFILE
          tput bold
          echo "$AMBARI_AGENT successfully stopped"
          tput sgr0
        else
          tput bold
          echo "$AMBARI_AGENT is not running. No PID found at $PIDFILE"
          tput sgr0
        fi
        ;;
  restart)
        echo -e "Restarting $AMBARI_AGENT"
        scriptpath=$0
        $scriptpath stop
        shift
        $scriptpath start "$@"
        retcode=$?
        ;;
  reset)
          if [ "$#" -ne 2 ]; then
            echo "You must supply the hostname of the Ambari Server with the restore option. (e.g. ambari-agent reset c6401.ambari.apache.org)"
            exit 1
          fi
          if [ -f $PIDFILE ]; then
            echo "$AMBARI_AGENT is running. You must stop it before using reset."
            exit 1
          fi
          echo -e "Resetting $AMBARI_AGENT"
          change_files_permissions
          $PYTHON $AGENT_SCRIPT reset $2
          retcode=$?

          if [ $retcode -eq 0 ]; then
            tput bold
            echo "$AMBARI_AGENT has been reset successfully. Changed Ambari Server hostname to $2 and certificates were cleared."
            tput sgr0
          else
            tput bold
            echo "$AMBARI_AGENT could not be reset."
            tput sgr0
          fi
          ;;

  *)
        tput bold
        echo "Usage: /usr/sbin/ambari-agent {start|stop|restart|status|reset <server_hostname>}"
        tput sgr0
        retcode=1
esac

exit $retcode
