#!/usr/bin/env bash
# Puppet Apply TASK
# Description: Applies a configuration fetched from the ADMIN_URL onto the server using puppet apply

TASK="PUPPET_APPLY"
source $(dirname $0)/oio-ga-tools-logger

if [ -z "$1" ]; then
  log "ERROR" $TASK" requires an url specified with -u"
  exit 1
fi

while getopts ":u:" opt; do
  case $opt in
    u)
      ADMIN_URL=$OPTARG
      ;;
    \?)
      log "WARN" "Invalid option provided -$OPTARG"
      exit 1
      ;;
    :)
      log "WARN" "Option -$OPTARG requires argument."
      exit 1
      ;;
  esac
done

HOST=$HOSTNAME
ADMIN_ROUTE="${ADMIN_URL}/api/servers/${HOST}/services/config.pp"
CONFIG_DIR="/etc/oio/sds/oio-puppetapply"
LOCK="/run/oio-puppetapply.lock"
LOCK_TIMEOUT=1000

if [ -e "$LOCK" ]; then
  now= date +"%s" &> /dev/null
  last= stat -c "%Y" $LOCK &> /dev/null
  if [ $((now-last)) -ge $LOCK_TIMEOUT ]; then
    log "INFO" $LOCK" file timeout, removing file"
  else
    log "ERROR" "Cannot run: "$LOCK" - file exists"
    exit 1
  fi
fi


if [ -z "$(/usr/bin/puppet)" ]; then
  log "ERROR" "No puppet binary found."
  exit 1
fi

# Lock
touch $LOCK
mkdir -p "$CONFIG_DIR"

# Download config file
/usr/bin/curl -XGET ${ADMIN_ROUTE} -s -o "$CONFIG_DIR/config_tmp.pp" &> /dev/null

# Format the string inside the file
awk '{print substr($0,2,length()-2);}' $CONFIG_DIR/config_tmp.pp > $CONFIG_DIR/config.pp

# Validate the configuration file
res=$(/usr/bin/puppet parser validate $CONFIG_DIR/config.pp)



if [ -n "$res" ]; then
   log "ERROR" "Invalid configuration file: \n {$res}"
   /usr/bin/rm -f "$LOCK" "$CONFIG_DIR/config.pp" "$CONFIG_DIR/config_tmp.pp"
   exit 1
else
  log "INFO" "[SUCCESS] Configuration applied"
fi
# Apply configuration (add --noop --show_diff for DRY RUN)
log "INFO" `/usr/bin/puppet apply --verbose --no-stringify_facts "$CONFIG_DIR/config.pp"`

# Restart the conscienceagent service
/usr/bin/gridinit_cmd restart @conscienceagent &> /dev/null

rm -f "$LOCK" "$CONFIG_DIR/config.pp" "$CONFIG_DIR/config_tmp.pp"
