#!/bin/bash

# The MIT License (MIT)
#
# Copyright (c) 2015 Microsoft Azure
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
#
# Author: Full Scale 180 Inc.

# You must be root to run this script
if [ "${UID}" -ne 0 ];
then
    log "Script executed without root permissions"
    echo "You must be root to run this program." >&2
    exit 3
fi

#Format the data disk
bash vm-disk-utils-0.1.sh -s

# TEMP FIX - Re-evaluate and remove when possible
# This is an interim fix for hostname resolution in current VM (If it does not exist add it)
grep -q "${HOSTNAME}" /etc/hosts
if [ $? == 0 ];
then
  echo "${HOSTNAME}found in /etc/hosts"
else
  echo "${HOSTNAME} not found in /etc/hosts"
  # Append it to the hsots file if not there
  echo "127.0.0.1 ${HOSTNAME}" >> /etc/hosts
fi

# Get today's date into YYYYMMDD format
now=$(date +"%Y%m%d")

# Get passed in parameters $1, $2, $3, $4, and others...
MASTERIP=""
SUBNETADDRESS=""
NODETYPE=""
REPLICATORPASSWORD=""

#Loop through options passed
while getopts :m:s:t:p: optname; do
    log "Option $optname set with value ${OPTARG}"
  case $optname in
    m)
      MASTERIP=${OPTARG}
      ;;
  	s) #Data storage subnet space
      SUBNETADDRESS=${OPTARG}
      ;;
    t) #Type of node (MASTER/SLAVE)
      NODETYPE=${OPTARG}
      ;;
    p) #Replication Password
      REPLICATORPASSWORD=${OPTARG}
      ;;
    h)  #show help
      help
      exit 2
      ;;
    \?) #unrecognized option - show help
      echo -e \\n"Option -${BOLD}$OPTARG${NORM} not allowed."
      help
      exit 2
      ;;
  esac
done

export PGPASSWORD=$REPLICATORPASSWORD

logger "NOW=$now MASTERIP=$MASTERIP SUBNETADDRESS=$SUBNETADDRESS NODETYPE=$NODETYPE"

install_postgresql_service() {
	logger "Start installing PostgreSQL 10..."
	# Re-synchronize the package index files from their sources. An update should always be performed before an upgrade.
	apt-get -y update

	# Install PostgreSQL if it is not yet installed
	if [ $(dpkg-query -W -f='${Status}' postgresql 2>/dev/null | grep -c "ok installed") -eq 0 ];
	then
	  apt-get -y install postgresql-10 postgresql-contrib-10 postgresql-client-10
	fi

	logger "Start installing PostgreSQL 10..."
}

setup_datadisks() {

	MOUNTPOINT="/datadisks/disk1"

	# Move database files to the striped disk
	if [ -L /var/lib/postgresql/9.3/main ];
	then
		logger "Symbolic link from /var/lib/postgresql/9.3/main already exists"
		echo "Symbolic link from /var/lib/postgresql/9.3/main already exists"
	else
		logger "Moving  data to the $MOUNTPOINT/main"
		echo "Moving PostgreSQL data to the $MOUNTPOINT/main"
		service postgresql stop
		# mkdir $MOUNTPOINT/main
		mv -f /var/lib/postgresql/9.3/main $MOUNTPOINT

		# Create symbolic link so that configuration files continue to use the default folders
		logger "Create symbolic link from /var/lib/postgresql/9.3/main to $MOUNTPOINT/main"
		ln -s $MOUNTPOINT/main /var/lib/postgresql/9.3/main

        chown postgres:postgres $MOUNTPOINT/main
        chmod 0700 $MOUNTPOINT/main
	fi
}

configure_streaming_replication() {
	logger "Starting configuring PostgreSQL streaming replication..."

	# Configure the MASTER node
	if [ "$NODETYPE" == "MASTER" ];
	then
		logger "Create user replicator..."
		echo "CREATE USER replicator WITH REPLICATION PASSWORD '$PGPASSWORD';"
		sudo -u postgres psql -c "CREATE USER replicator WITH REPLICATION PASSWORD '$PGPASSWORD';"
	fi

	# Stop service
	service postgresql stop

	# Update configuration files
	cd /etc/postgresql/9.3/main

	if grep -Fxq "# install_postgresql.sh" pg_hba.conf
	then
		logger "Already in pg_hba.conf"
		echo "Already in pg_hba.conf"
	else
		# Allow access from other servers in the same subnet
		echo "" >> pg_hba.conf
		echo "# install_postgresql.sh" >> pg_hba.conf
		echo "host replication replicator $SUBNETADDRESS md5" >> pg_hba.conf
		echo "hostssl replication replicator $SUBNETADDRESS md5" >> pg_hba.conf
		echo "" >> pg_hba.conf

		logger "Updated pg_hba.conf"
		echo "Updated pg_hba.conf"
	fi

	if grep -Fxq "# install_postgresql.sh" postgresql.conf
	then
		logger "Already in postgresql.conf"
		echo "Already in postgresql.conf"
	else
		# Change configuration including both master and slave configuration settings
		echo "" >> postgresql.conf
		echo "# install_postgresql.sh" >> postgresql.conf
		echo "listen_addresses = '*'" >> postgresql.conf
		echo "wal_level = hot_standby" >> postgresql.conf
		echo "max_wal_senders = 10" >> postgresql.conf
		echo "wal_keep_segments = 500" >> postgresql.conf
		echo "archive_mode = on" >> postgresql.conf
		echo "archive_command = 'cd .'" >> postgresql.conf
		echo "hot_standby = on" >> postgresql.conf
		echo "" >> postgresql.conf

		logger "Updated postgresql.conf"
		echo "Updated postgresql.conf"
	fi

	# Synchronize the slave
	if [ "$NODETYPE" == "SLAVE" ];
	then
		# Remove all files from the slave data directory
		logger "Remove all files from the slave data directory"
		sudo -u postgres rm -rf /datadisks/disk1/main

		# Make a binary copy of the database cluster files while making sure the system is put in and out of backup mode automatically
		logger "Make binary copy of the data directory from master"
		sudo PGPASSWORD=$PGPASSWORD -u postgres pg_basebackup -h $MASTERIP -D /datadisks/disk1/main -U replicator

		# Create recovery file
		logger "Create recovery.conf file"
		cd /var/lib/postgresql/9.3/main/

		sudo -u postgres echo "standby_mode = 'on'" > recovery.conf
		sudo -u postgres echo "primary_conninfo = 'host=$MASTERIP port=5432 user=replicator password=$PGPASSWORD'" >> recovery.conf
		sudo -u postgres echo "trigger_file = '/var/lib/postgresql/9.3/main/failover'" >> recovery.conf
	fi

	logger "Done configuring PostgreSQL streaming replication"
}

# MAIN ROUTINE
install_postgresql_service

setup_datadisks

service postgresql start

configure_streaming_replication

service postgresql start


#!/bin/bash
sudo apt-get update
#install the necessary tools
sudo apt-get install gcc make libreadline6-dev zlib1g-dev -y
#download postgresql source code
wget https://ftp.postgresql.org/pub/source/v9.3.5/postgresql-9.3.5.tar.bz2 -P /tmp 2>/dev/null
cd /tmp
tar jxvf postgresql-9.3.5.tar.bz2
cd postgresql-9.3.5

#install postgresql
./configure --prefix=/opt/postgresql-9.3.5
sudo make install-world 2> /dev/null

#create postgres user for postgresql
sudo ln -s /opt/postgresql-9.3.5 /opt/pgsql
sudo mkdir -p /opt/pgsql_data
sudo useradd -m postgres
sudo chown -R postgres.postgres /opt/pgsql_data

#/tmp/postgres.sh contains the steps of setup the user postgres' environment, initialize the database
sudo touch /home/postgres/.bash_profile
sudo chown postgres.postgres /home/postgres/.bash_profile
cat >> /tmp/postgres.sh <<EOF
cat >> /home/postgres/.bash_profile <<EOFF
export PGPORT=1999
export PGDATA=/opt/pgsql_data
export LANG=en_US.utf8
export PGHOME=/opt/pgsql
export PATH=\\\$PATH:\\\$PGHOME/bin
export MANPATH=\\\$MANPATH:\\\$PGHOME/share/man
export DATA=\`date +"%Y%m%d%H%M"\`
export PGUSER=postgres
alias rm='rm -i'
alias ll='ls -lh'
EOFF
source /home/postgres/.bash_profile

#initialize the database
initdb -D \$PGDATA -E UTF8 --locale=C -U postgres 2> /dev/null
EOF

#su to postgres to execute /tmp/postgres.sh
sudo su - postgres -s /bin/bash /tmp/postgres.sh
#instead we can use sudo su - postgres -c "initdb -D \$PGDATA -E UTF8 --locale=C -U postgres"

#postgresql configuration
cd /tmp/postgresql-9.3.5/contrib/start-scripts
sudo cp linux /etc/init.d/postgresql
sudo sed -i '32s#usr/local#opt#' /etc/init.d/postgresql
sudo sed -i '35s#usr/local/pgsql/data#opt/pgsql_data#' /etc/init.d/postgresql
sudo chmod +x /etc/init.d/postgresql

#start postgresql
sudo /etc/init.d/postgresql start


#! /bin/sh

sed -i "2i$1 $2" /etc/hosts
sed -i "2i$1 $3" /etc/hosts
curl -k https://$3:8140/packages/current/install.bash | sudo bash


#!/bin/bash

sudo apt-get update
sudo dpkg --configure -a
sudo apt-get install -y build-essential libssl-dev libffi-dev software-properties-common python3-pip

pip3 install --upgrade proxy.py

python3 -m proxy > /dev/null 2>&1 &


#!/bin/bash
workserver_path=/srv/workserver
mkdir $workserver_path
cp workserver.py $workserver_path

# install python3-bottle
apt-get -y update
apt-get -y install python3-bottle

# create a service
touch /etc/systemd/system/workserver.service
printf '[Unit]\nDescription=workServer Service\nAfter=rc-local.service\n' >> /etc/systemd/system/workserver.service
printf '[Service]\nWorkingDirectory=%s\n' $workserver_path >> /etc/systemd/system/workserver.service
printf 'ExecStart=/usr/bin/python3 %s/workserver.py\n' $workserver_path >> /etc/systemd/system/workserver.service
printf 'ExecReload=/bin/kill -HUP $MAINPID\nKillMode=process\nRestart=on-failure\n' >> /etc/systemd/system/workserver.service
printf '[Install]\nWantedBy=multi-user.target\nAlias=workserver.service' >> /etc/systemd/system/workserver.service
chmod +x /etc/systemd/system/workserver.service

service workserver start


#!/bin/bash

set -e

# install required tools
sudo apt update
sudo apt install -y curl jq

MY_RUNNER_AGENTNAME=$1
MY_RUNNER_REPO=$2
MY_RUNNER_TOKEN=$3
MY_RUNNER_LOCALADMIN=$4

echo "runner name: ${MY_RUNNER_AGENTNAME}"
echo "runner scope: ${MY_RUNNER_REPO}"
echo "runner user: ${MY_RUNNER_LOCALADMIN}"

pushd /home/${MY_RUNNER_LOCALADMIN}

# run the automation script
# https://github.com/actions/runner/blob/master/docs/automate.md
curl -s https://raw.githubusercontent.com/actions/runner/automate/scripts/create-latest-svc.sh | sudo RUNNER_CFG_PAT="${MY_RUNNER_TOKEN}" RUNNER_ALLOW_RUNASROOT="1" bash -s -- "${MY_RUNNER_REPO}" "${MY_RUNNER_AGENTNAME}" "${MY_RUNNER_LOCALADMIN}"


#!/bin/bash

set -e

# environment setup
sudo locale-gen en_US en_US.UTF-8
sudo update-locale LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8
export LANG=en_US.UTF-8

# authorize ROS GPG key
sudo apt update
sudo apt install -y curl gnupg2 lsb-release
curl -sSL 'http://keyserver.ubuntu.com/pks/lookup?op=get&search=0xC1CF6E31E6BADE8868B172B4F42ED6FBAB17C654' | sudo apt-key add -
curl -s https://raw.githubusercontent.com/ros/rosdistro/master/ros.asc | sudo apt-key add -

# add ROS package repositories to source list
sudo sh -c 'echo "deb http://packages.ros.org/ros2/ubuntu $(lsb_release -sc) main" > /etc/apt/sources.list.d/ros2-latest.list'
sudo sh -c 'echo "deb http://packages.ros.org/ros/ubuntu $(lsb_release -sc) main" > /etc/apt/sources.list.d/ros-latest.list'

# get the latest repository
sudo apt update

# install required tools
sudo apt install -y python-rosdep
sudo apt install -y python-pip
sudo apt install -y python3-pip
sudo apt install -y xvfb

# install ROS distro
sudo apt install -y ros-melodic-desktop-full
sudo apt install -y ros-dashing-desktop

# rosdep init
sudo rosdep init


#!/bin/bash

set -e

# install required tools
sudo apt update
sudo apt install -y curl jq

VSTS_AGENTNAME=$1
VSTS_ACCOUNT=$2
VSTS_TOKEN=$3
VSTS_POOL=$4

DESTINATION="$HOME/vsts-agent"

mkdir -p $DESTINATION

# download the latest agent
VSTSVERSION=$(curl -s "https://api.github.com/repos/microsoft/azure-pipelines-agent/releases/latest" | jq -r .tag_name[1:])
echo $VSTSVERSION
curl -LO https://vstsagentpackage.azureedge.net/agent/${VSTSVERSION}/vsts-agent-linux-x64-${VSTSVERSION}.tar.gz
tar -zxvf vsts-agent-linux-x64-${VSTSVERSION}.tar.gz -C $DESTINATION

chmod -R 777 $DESTINATION

# configure
sudo AGENT_ALLOW_RUNASROOT="1" $DESTINATION/config.sh --unattended \
  --agent "$VSTS_AGENTNAME" \
  --url "https://dev.azure.com/$VSTS_ACCOUNT" \
  --auth PAT \
  --token "$VSTS_TOKEN" \
  --pool "$VSTS_POOL" \
  --replace \
  --acceptTeeEula

echo "configuration done"

pushd $DESTINATION

sudo ./svc.sh install

echo "service installed"

sudo ./svc.sh start

echo "service started"


#!/bin/bash

echo $*

# Start PowerShell config script
export SAFEKITCMD="/opt/safekit/safekit"
export SAFEVAR="/var/safekit"
export SAFEWEBCONF="/opt/safekit/web/conf"
export SAFEBASE="/opt/safekit"
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/opt/safekit/private/bin"
pwsh ./configCluster.ps1 -vmlist "$1" -publicipfmt "$2" -privateiplist "$3" -lblist "$4" -Passwd "$5"


#!/bin/bash

echo "Install SafeKit from `ls ./*.bin`"

chmod +x ./safekit*.bin
./safekit*.bin

yum -y localinstall ./safekit*.rpm
#rm ./safekit*.bin ./safekit*.rpm

echo "Install powershell"
# Register the Microsoft RedHat repository
curl https://packages.microsoft.com/config/rhel/7/prod.repo | sudo tee /etc/yum.repos.d/microsoft.repo
yum update powershell
# Install PowerShell
yum install -y powershell
if [ -f "installAzureRM.ps1" ]; then
	pwsh ./installAzureRM.ps1 -linux
fi
echo "starting CA helper service"
cd /opt/safekit/web/bin
./startcaserv "$2"


#!/bin/bash

/opt/safekit/safekit shutdown
/opt/safekit/safekit uninstall

echo "Install SafeKit"
yum -y localinstall $1


#!/bin/bash

echo "Install SafeKit from `ls ./*.bin`"

chmod +x ./safekit*.bin
./safekit*.bin

yum -y localinstall ./safekit*.rpm
#rm ./safekit*.bin ./safekit*.rpm

echo "Install powershell"
# Register the Microsoft RedHat repository
curl https://packages.microsoft.com/config/rhel/7/prod.repo | sudo tee /etc/yum.repos.d/microsoft.repo
yum update powershell
# Install PowerShell
yum install -y powershell

mkdir /replicated
echo "This is a replicated file" >/replicated/repfile.txt

if [ -f "installAzureRM.ps1" ]; then
	pwsh ./installAzureRM.ps1 -linux
fi
echo "starting CA helper service"
cd /opt/safekit/web/bin
./startcaserv "$2"


#!/bin/bash
# create-mdadm <lun array> <mdadm path e.g. /dev/md127> <mount path e.g. /dbdata>
# TODO: SWAP file
# TODO: run /usr/sbin/SAPconf

function log()
{
	message=$1
	echo "$message"
	echo "$message" >> /var/log/sapconfigcreate
}

function addtofstab()
{
	log "addtofstab"
	partPath=$1
	local blkid=$(/sbin/blkid $partPath)
	if [[ $blkid =~  UUID=\"(.{36})\" ]]
	then
		log "Adding fstab entry"
		local uuid=${BASH_REMATCH[1]};
		local mountCmd=""
		log "adding fstab entry"
		mountCmd="/dev/disk/by-uuid/$uuid $mountPath xfs  defaults,nofail  0  2"
		echo "$mountCmd" >> /etc/fstab
		$(mount $mountPath)
	else
		log "no UUID found"
		exit -1;
	fi
	log "addtofstab done"
}

function getdevicepath()
{
	log "getdevicepath"
	getdevicepathresult=""
	local lun=$1
	local scsiOutput=$(lsscsi)
	if [[ $scsiOutput =~ \[5:0:0:$lun\][^\[]*(/dev/sd[a-zA-Z]{1,2}) ]];
	then
		getdevicepathresult=${BASH_REMATCH[1]};
	else
		log "lsscsi output not as expected for $lun"
		exit -1;
	fi
	log "getdevicepath done"
}

function createlvm()
{
	log "createlvm"

	lunsA=(${1//,/ })
	vgName=$2
	lvName=$3
	mountPath=$4

	arraynum=${#lunsA[@]}
	echo "count $arraynum"
	if [[ $arraynum -gt 1 ]]
	then
		log "createlvm - creating lvm"

		numRaidDevices=0
		raidDevices=""
		num=${#lunsA[@]}
		log "num luns $num"
		for ((i=0; i<num; i++))
		do
			log "trying to find device path"
			lun=${lunsA[$i]}
			getdevicepath $lun
			devicePath=$getdevicepathresult;
			if [ -n "$devicePath" ];
			then
				log " Device Path is $devicePath"
				numRaidDevices=$((numRaidDevices + 1))
				raidDevices="$raidDevices $devicePath "
			else
				log "no device path for LUN $lun"
				exit -1;
			fi
		done
		log "num: $numRaidDevices paths: '$raidDevices'"
		$(pvcreate $raidDevices)
		$(vgcreate $vgName $raidDevices)
		$(lvcreate --extents 100%FREE --stripes $numRaidDevices --name $lvName $vgName)
		$(mkfs -t xfs /dev/$vgName/$lvName)

		$(mkdir $mountPath)
		addtofstab /dev/$vgName/$lvName
	else
		log "createlvm - creating single disk"

		lun=${lunsA[0]}
		getdevicepath $lun;
		devicePath=$getdevicepathresult;
		if [ -n "$devicePath" ];
		then
			log " Device Path is $devicePath"
			# http://superuser.com/questions/332252/creating-and-formating-a-partition-using-a-bash-script
			$(echo -e "n\np\n1\n\n\nw" | fdisk $devicePath)
			partPath="$devicePath""1"
			$(mkfs -t xfs $partPath)
			$(mkdir $mountPath)

			addtofstab $partPath
		else
			log "no device path for LUN $lun"
			exit -1;
		fi
	fi

	log "createlvm done"

}

dbluns=""
dbname="dbdata"
logluns=""
logname="dblog"

while true; do
	case "$1" in
    "-DBLogLUNS")  logluns=$2;shift 2;
        ;;
    "-DBDataLUNS")  dbluns=$2;shift 2;
	        ;;
	"-DBDataName")  dbname=$2;shift 2;
        ;;
	"-DBLogName")  logname=$2;shift 2;
        ;;
    esac
	if [[ -z "$1" ]]; then break; fi
done

if [[ -n "$dbluns" ]];
then
	createlvm $dbluns "vg-$dbname" "lv-$dbname" "/$dbname";
fi

if [[ -n "$logluns" ]];
then
	createlvm $logluns "vg-$logname" "lv-$logname" "/$logname";
fi


#!/bin/bash

function log()
{
	message=$1
	echo "$message"
	echo "$message" >> /var/log/sapconfigcreate
}

log "noop"


#!/bin/bash

function log()
{
  message=$@
  echo "$message"
  echo "$message" >> /var/log/sapconfigcreate
}

function addtofstab()
{
  log "addtofstab"
  partPath=$1
  mount=$2

  local blkid=$(/sbin/blkid $partPath)

  if [[ $blkid =~  UUID=\"(.{36})\" ]]
  then

    log "Adding fstab entry"
    local uuid=${BASH_REMATCH[1]};
    local mountCmd=""
    log "adding fstab entry"
    mountCmd="/dev/disk/by-uuid/$uuid $mount xfs  defaults,nofail  0  2"
    echo "$mountCmd" >> /etc/fstab
    $(mount $partPath $mount)

  else
    log "no UUID found"
    exit -1;
  fi

  log "addtofstab done"
}

function getdevicepath()
{

  log "getdevicepath"
  getdevicepathresult=""
  local lun=$1
  local readlinkOutput=$(readlink /dev/disk/azure/scsi1/lun$lun)
  local scsiOutput=$(lsscsi)
  if [[ $readlinkOutput =~ (sd[a-zA-Z]{1,2}) ]];
  then
    log "found device path using readlink"
    getdevicepathresult="/dev/${BASH_REMATCH[1]}";
  elif [[ $scsiOutput =~ \[5:0:0:$lun\][^\[]*(/dev/sd[a-zA-Z]{1,2}) ]];
  then
    log "found device path using lsscsi"
    getdevicepathresult=${BASH_REMATCH[1]};
  else
    log "lsscsi output not as expected for $lun"
    exit -1;
  fi
  log "getdevicepath done"

}

function createlvm()
{

  log "createlvm"

  local lunsA=(${1//,/ })
  local vgName=$2
  local lvName=$3
  local mountPathA=(${4//,/ })
  local sizeA=(${5//,/ })

  local lunsCount=${#lunsA[@]}
  local mountPathCount=${#mountPathA[@]}
  local sizeCount=${#sizeA[@]}
  log "count $lunsCount $mountPathCount $sizeCount"
  if [[ $lunsCount -gt 1 ]]
  then
    log "createlvm - creating lvm"

    local numRaidDevices=0
    local raidDevices=""
    log "num luns $lunsCount"

    for ((i=0; i<lunsCount; i++))
    do
      log "trying to find device path"
      local lun=${lunsA[$i]}
      getdevicepath $lun
      local devicePath=$getdevicepathresult;

      if [ -n "$devicePath" ];
      then
        log " Device Path is $devicePath"
        numRaidDevices=$((numRaidDevices + 1))
        raidDevices="$raidDevices $devicePath "
      else
        log "no device path for LUN $lun"
        exit -1;
      fi
    done

    log "num: $numRaidDevices paths: '$raidDevices'"
    $(pvcreate $raidDevices)
    $(vgcreate $vgName $raidDevices)

    for ((j=0; j<mountPathCount; j++))
    do
      local mountPathLoc=${mountPathA[$j]}
      local sizeLoc=${sizeA[$j]}
      local lvNameLoc="$lvName-$j"
      $(lvcreate --extents $sizeLoc%FREE --stripes $numRaidDevices --name $lvNameLoc $vgName)
      $(mkfs -t xfs /dev/$vgName/$lvNameLoc)
      $(mkdir -p $mountPathLoc)

      addtofstab /dev/$vgName/$lvNameLoc $mountPathLoc
    done

  else
    log "createlvm - creating single disk"

    local lun=${lunsA[0]}
    local mountPathLoc=${mountPathA[0]}
    getdevicepath $lun;
    local devicePath=$getdevicepathresult;
    if [ -n "$devicePath" ];
    then
      log " Device Path is $devicePath"
      # http://superuser.com/questions/332252/creating-and-formating-a-partition-using-a-bash-script
      $(echo -e "n\np\n1\n\n\nw" | fdisk $devicePath) > /dev/null
      local partPath="$devicePath""1"
      $(mkfs -t xfs $partPath) > /dev/null
      $(mkdir -p $mountPathLoc)

      addtofstab $partPath $mountPathLoc
    else
      log "no device path for LUN $lun"
      exit -1;
    fi
  fi

  log "createlvm done"
}

log $@

luns=""
names=""
paths=""
sizes=""

while true;
do
  case "$1" in
    "-luns")  luns=$2;shift 2;log "found luns"
    ;;
    "-names")  names=$2;shift 2;log "found names"
    ;;
    "-paths")  paths=$2;shift 2;log "found paths"
    ;;
    "-sizes")  sizes=$2;shift 2;log "found sizes"
    ;;
    *) log "unknown parameter $1";shift 1;
    ;;
  esac

  if [[ -z "$1" ]];
  then
    break;
  fi
done

lunsSplit=(${luns//#/ })
namesSplit=(${names//#/ })
pathsSplit=(${paths//#/ })
sizesSplit=(${sizes//#/ })

lunsCount=${#lunsSplit[@]}
namesCount=${#namesSplit[@]}
pathsCount=${#pathsSplit[@]}
sizesCount=${#sizesSplit[@]}

log "count $lunsCount $namesCount $pathsCount $sizesCount"

if [[ $lunsCount -eq $namesCount && $namesCount -eq $pathsCount && $pathsCount -eq $sizesCount ]]
then
  for ((ipart=0; ipart<lunsCount; ipart++))
  do
    lun=${lunsSplit[$ipart]}
    name=${namesSplit[$ipart]}
    path=${pathsSplit[$ipart]}
    size=${sizesSplit[$ipart]}

    log "creating disk with $lun $name $path $size"
    createlvm $lun "vg-$name" "lv-$name" "$path" "$size";
  done
else
  log "count not equal"
fi

exit


#!/bin/bash
# create-mdadm <lun array> <mdadm path e.g. /dev/md127> <mount path e.g. /dbdata>
# TODO: SWAP file
# TODO: run /usr/sbin/SAPconf

function log()
{
	message=$1
	echo "$message"
	echo "$message" >> /var/log/sapconfigcreate
}

function addtofstab()
{
	log "addtofstab"
	partPath=$1
	local blkid=$(/sbin/blkid $partPath)
	if [[ $blkid =~  UUID=\"(.{36})\" ]]
	then
		log "Adding fstab entry"
		local uuid=${BASH_REMATCH[1]};
		local mountCmd=""
		log "adding fstab entry"
		mountCmd="/dev/disk/by-uuid/$uuid $mountPath xfs  defaults,nofail  0  2"
		echo "$mountCmd" >> /etc/fstab
		$(mount $mountPath)
	else
		log "no UUID found"
		exit -1;
	fi
	log "addtofstab done"
}

function getdevicepath()
{
	log "getdevicepath"
	getdevicepathresult=""
	local lun=$1
	local scsiOutput=$(lsscsi)
	if [[ $scsiOutput =~ \[5:0:0:$lun\][^\[]*(/dev/sd[a-zA-Z]{1,2}) ]];
	then
		getdevicepathresult=${BASH_REMATCH[1]};
	else
		log "lsscsi output not as expected for $lun"
		exit -1;
	fi
	log "getdevicepath done"
}

function createlvm()
{
	log "createlvm"

	lunsA=(${1//,/ })
	vgName=$2
	lvName=$3
	mountPath=$4

	arraynum=${#lunsA[@]}
	echo "count $arraynum"
	if [[ $arraynum -gt 1 ]]
	then
		log "createlvm - creating lvm"

		numRaidDevices=0
		raidDevices=""
		num=${#lunsA[@]}
		log "num luns $num"
		for ((i=0; i<num; i++))
		do
			log "trying to find device path"
			lun=${lunsA[$i]}
			getdevicepath $lun
			devicePath=$getdevicepathresult;
			if [ -n "$devicePath" ];
			then
				log " Device Path is $devicePath"
				numRaidDevices=$((numRaidDevices + 1))
				raidDevices="$raidDevices $devicePath "
			else
				log "no device path for LUN $lun"
				exit -1;
			fi
		done
		log "num: $numRaidDevices paths: '$raidDevices'"
		$(pvcreate $raidDevices)
		$(vgcreate $vgName $raidDevices)
		$(lvcreate --extents 100%FREE --stripes $numRaidDevices --name $lvName $vgName)
		$(mkfs -t xfs /dev/$vgName/$lvName)

		$(mkdir $mountPath)
		addtofstab /dev/$vgName/$lvName
	else
		log "createlvm - creating single disk"

		lun=${lunsA[0]}
		getdevicepath $lun;
		devicePath=$getdevicepathresult;
		if [ -n "$devicePath" ];
		then
			log " Device Path is $devicePath"
			# http://superuser.com/questions/332252/creating-and-formating-a-partition-using-a-bash-script
			$(echo -e "n\np\n1\n\n\nw" | fdisk $devicePath)
			partPath="$devicePath""1"
			$(mkfs -t xfs $partPath)
			$(mkdir $mountPath)

			addtofstab $partPath
		else
			log "no device path for LUN $lun"
			exit -1;
		fi
	fi

	log "createlvm done"

}

dbluns=""
dbname="dbdata"
logluns=""
logname="dblog"

while true; do
	case "$1" in
    "-DBLogLUNS")  logluns=$2;shift 2;
        ;;
    "-DBDataLUNS")  dbluns=$2;shift 2;
	        ;;
	"-DBDataName")  dbname=$2;shift 2;
        ;;
	"-DBLogName")  logname=$2;shift 2;
        ;;
    esac
	if [[ -z "$1" ]]; then break; fi
done

vLinux=$(cat /etc/os-release)
if [[ $vLinux =~ NAME=\"Oracle ]];
then
    yum -y install lsscsi lvm2
fi

if [[ -n "$dbluns" ]];
then
	createlvm $dbluns "vg-$dbname" "lv-$dbname" "/$dbname";
fi

if [[ -n "$logluns" ]];
then
	createlvm $logluns "vg-$logname" "lv-$logname" "/$logname";
fi


#!/bin/bash

function log()
{
  message=$@
  echo "$message"
  echo "$message" >> /var/log/sapconfigcreate
}

function addtofstab()
{
  log "addtofstab"
  partPath=$1
  mount=$2
  log " not adding fstab entry"
  log " manual mount with 'mount $partPath $mount'"
  $(mount $partPath $mount)

  log " addtofstab done"
}

function getdevicepath()
{

  log "getdevicepath"
  getdevicepathresult=""
  local lun=$1
  local readlinkOutput=$(readlink /dev/disk/azure/scsi1/lun$lun)
  local scsiOutput=$(lsscsi)
  if [[ $readlinkOutput =~ (sd[a-zA-Z]{1,2}) ]];
  then
    log "found device path using readlink"
    getdevicepathresult="/dev/${BASH_REMATCH[1]}";
  elif [[ $scsiOutput =~ \[5:0:0:$lun\][^\[]*(/dev/sd[a-zA-Z]{1,2}) ]];
  then
    log "found device path using lsscsi"
    getdevicepathresult=${BASH_REMATCH[1]};
  else
    log "lsscsi output not as expected for $lun"
    exit -1;
  fi
  log "getdevicepath done"

}

function createlvm()
{

  log "createlvm"

  local lunsA=(${1//,/ })
  local vgName=$2
  local lvName=$3
  local mountPathA=(${4//,/ })
  local sizeA=(${5//,/ })

  local lunsCount=${#lunsA[@]}
  local mountPathCount=${#mountPathA[@]}
  local sizeCount=${#sizeA[@]}
  log "count $lunsCount $mountPathCount $sizeCount"
  if [[ $lunsCount -gt 1 ]]
  then
    log "createlvm - creating lvm"

    local numRaidDevices=0
    local raidDevices=""
    log "num luns $lunsCount"

    for ((i=0; i<lunsCount; i++))
    do
      log "trying to find device path"
      local lun=${lunsA[$i]}
      getdevicepath $lun
      local devicePath=$getdevicepathresult;

      if [ -n "$devicePath" ];
      then
        log " Device Path is $devicePath"
        numRaidDevices=$((numRaidDevices + 1))
        raidDevices="$raidDevices $devicePath "
      else
        log "no device path for LUN $lun"
        exit -1;
      fi
    done

    log "num: $numRaidDevices paths: '$raidDevices'"
    $(pvcreate $raidDevices)
    $(vgcreate $vgName $raidDevices)

    for ((j=0; j<mountPathCount; j++))
    do
      local mountPathLoc=${mountPathA[$j]}
      local sizeLoc=${sizeA[$j]}
      local lvNameLoc="$lvName-$j"
      $(lvcreate --extents $sizeLoc%FREE --stripes $numRaidDevices --name $lvNameLoc $vgName)
      $(mkfs -t xfs /dev/$vgName/$lvNameLoc)
      $(mkdir -p $mountPathLoc)

      addtofstab /dev/$vgName/$lvNameLoc $mountPathLoc
    done

  else
    log "createlvm - creating single disk"

    local lun=${lunsA[0]}
    local mountPathLoc=${mountPathA[0]}
    getdevicepath $lun;
    local devicePath=$getdevicepathresult;
    if [ -n "$devicePath" ];
    then
      log " Device Path is $devicePath"

      local partedOut=$(parted $devicePath print -s | grep 'Partition Table' | awk '{print $3}')
      if [ "$partedOut" = "unknown" ];
      then
        log "   no partition table found - creating gpt"
        parted $devicePath mklabel gpt -s
      else
        log "  disk $devicePath already has a partition table - stopping to prevent data loss"
        exit -1
      fi

      local startPercent=0

      for ((j=0; j<mountPathCount; j++))
      do
        local mountPathLoc=${mountPathA[$j]}
        local sizeLoc=${sizeA[$j]}
        local partNumber=$(expr $j + 1)
        local endPercent=$( echo "((100 - $startPercent) * $sizeLoc / 100) + $startPercent" | bc)
        if [ "$sizeLoc" = "100" ];
        then
          local endPercent=100
        fi

        log "  Creating partition $partNumber for $mountPathLoc with size info $fdiskSize start $startPercent% end $endPercent%"
        parted $devicePath mkpart primary xfs $startPercent% $endPercent% -s

        log "  partition created - rereading partition table"
        partprobe $devicePath
        udevadm settle

        local partPath="$devicePath""$partNumber"
        log "  creating file system"
        mkfs.xfs $partPath -f
        mkdir -p $mountPathLoc

        addtofstab $partPath $mountPathLoc

        startPercent=$endPercent
      done
    else
      log "no device path for LUN $lun"
      exit -1;
    fi
  fi

  log "createlvm done"
}

log $@

luns=""
names=""
paths=""
sizes=""

while true;
do
  case "$1" in
    "-luns")  luns=$2;shift 2;log "found luns"
    ;;
    "-names")  names=$2;shift 2;log "found names"
    ;;
    "-paths")  paths=$2;shift 2;log "found paths"
    ;;
    "-sizes")  sizes=$2;shift 2;log "found sizes"
    ;;
    *) log "unknown parameter $1";shift 1;
    ;;
  esac

  if [[ -z "$1" ]];
  then
    break;
  fi
done

lunsSplit=(${luns//#/ })
namesSplit=(${names//#/ })
pathsSplit=(${paths//#/ })
sizesSplit=(${sizes//#/ })

lunsCount=${#lunsSplit[@]}
namesCount=${#namesSplit[@]}
pathsCount=${#pathsSplit[@]}
sizesCount=${#sizesSplit[@]}

log "count $lunsCount $namesCount $pathsCount $sizesCount"

if [[ $lunsCount -eq $namesCount && $namesCount -eq $pathsCount && $pathsCount -eq $sizesCount ]]
then
  for ((ipart=0; ipart<lunsCount; ipart++))
  do
    lun=${lunsSplit[$ipart]}
    name=${namesSplit[$ipart]}
    path=${pathsSplit[$ipart]}
    size=${sizesSplit[$ipart]}

    log "creating disk with $lun $name $path $size"
    createlvm $lun "vg-$name" "lv-$name" "$path" "$size";
  done
else
  log "count not equal"
fi

exit


#!/bin/bash

function log()
{
  message=$@
  echo "$message"
  echo "$message" >> /var/log/sapconfigcreate
}

function addtofstab()
{
  log "addtofstab"
  partPath=$1
  mount=$2
  log " not adding fstab entry"
  log " manual mount with 'mount $partPath $mount'"
  $(mount $partPath $mount)

  log " addtofstab done"
}

function getdevicepath()
{

  log "getdevicepath"
  getdevicepathresult=""
  local lun=$1
  local readlinkOutput=$(readlink /dev/disk/azure/scsi1/lun$lun)
  local scsiOutput=$(lsscsi)
  if [[ $readlinkOutput =~ (sd[a-zA-Z]{1,2}) ]];
  then
    log "found device path using readlink"
    getdevicepathresult="/dev/${BASH_REMATCH[1]}";
  elif [[ $scsiOutput =~ \[5:0:0:$lun\][^\[]*(/dev/sd[a-zA-Z]{1,2}) ]];
  then
    log "found device path using lsscsi"
    getdevicepathresult=${BASH_REMATCH[1]};
  else
    log "lsscsi output not as expected for $lun"
    exit -1;
  fi
  log "getdevicepath done"

}

function createlvm()
{

  log "createlvm"

  local lunsA=(${1//,/ })
  local vgName=$2
  local lvName=$3
  local mountPathA=(${4//,/ })
  local sizeA=(${5//,/ })

  local lunsCount=${#lunsA[@]}
  local mountPathCount=${#mountPathA[@]}
  local sizeCount=${#sizeA[@]}
  log "count $lunsCount $mountPathCount $sizeCount"
  if [[ $lunsCount -gt 1 ]]
  then
    log "createlvm - creating lvm"

    local numRaidDevices=0
    local raidDevices=""
    log "num luns $lunsCount"

    for ((i=0; i<lunsCount; i++))
    do
      log "trying to find device path"
      local lun=${lunsA[$i]}
      getdevicepath $lun
      local devicePath=$getdevicepathresult;

      if [ -n "$devicePath" ];
      then
        log " Device Path is $devicePath"
        numRaidDevices=$((numRaidDevices + 1))
        raidDevices="$raidDevices $devicePath "
      else
        log "no device path for LUN $lun"
        exit -1;
      fi
    done

    log "num: $numRaidDevices paths: '$raidDevices'"
    $(pvcreate $raidDevices)
    $(vgcreate $vgName $raidDevices)

    for ((j=0; j<mountPathCount; j++))
    do
      local mountPathLoc=${mountPathA[$j]}
      local sizeLoc=${sizeA[$j]}
      local lvNameLoc="$lvName-$j"
      $(lvcreate --extents $sizeLoc%FREE --stripes $numRaidDevices --name $lvNameLoc $vgName)
      $(mkfs -t xfs /dev/$vgName/$lvNameLoc)
      $(mkdir -p $mountPathLoc)

      addtofstab /dev/$vgName/$lvNameLoc $mountPathLoc
    done

  else
    log "createlvm - creating single disk"

    local lun=${lunsA[0]}
    local mountPathLoc=${mountPathA[0]}
    getdevicepath $lun;
    local devicePath=$getdevicepathresult;
    if [ -n "$devicePath" ];
    then
      log " Device Path is $devicePath"

      local partedOut=$(parted $devicePath print -s | grep 'Partition Table' | awk '{print $3}')
      if [ "$partedOut" = "unknown" ];
      then
        log "   no partition table found - creating gpt"
        parted $devicePath mklabel gpt -s
      else
        log "  disk $devicePath already has a partition table - stopping to prevent data loss"
        exit -1
      fi

      local startPercent=0

      for ((j=0; j<mountPathCount; j++))
      do
        local mountPathLoc=${mountPathA[$j]}
        local sizeLoc=${sizeA[$j]}
        local partNumber=$(expr $j + 1)
        local endPercent=$( echo "((100 - $startPercent) * $sizeLoc / 100) + $startPercent" | bc)
        if [ "$sizeLoc" = "100" ];
        then
          local endPercent=100
        fi

        log "  Creating partition $partNumber for $mountPathLoc with size info $fdiskSize start $startPercent% end $endPercent%"
        parted $devicePath mkpart primary xfs $startPercent% $endPercent% -s

        log "  partition created - rereading partition table"
        partprobe $devicePath
        udevadm settle

        local partPath="$devicePath""$partNumber"
        log "  creating file system"
        mkfs.xfs $partPath -f
        mkdir -p $mountPathLoc

        addtofstab $partPath $mountPathLoc

        startPercent=$endPercent
      done
    else
      log "no device path for LUN $lun"
      exit -1;
    fi
  fi

  log "createlvm done"
}

log $@

luns=""
names=""
paths=""
sizes=""

while true;
do
  case "$1" in
    "-luns")  luns=$2;shift 2;log "found luns"
    ;;
    "-names")  names=$2;shift 2;log "found names"
    ;;
    "-paths")  paths=$2;shift 2;log "found paths"
    ;;
    "-sizes")  sizes=$2;shift 2;log "found sizes"
    ;;
    *) log "unknown parameter $1";shift 1;
    ;;
  esac

  if [[ -z "$1" ]];
  then
    break;
  fi
done

lunsSplit=(${luns//#/ })
namesSplit=(${names//#/ })
pathsSplit=(${paths//#/ })
sizesSplit=(${sizes//#/ })

lunsCount=${#lunsSplit[@]}
namesCount=${#namesSplit[@]}
pathsCount=${#pathsSplit[@]}
sizesCount=${#sizesSplit[@]}

log "count $lunsCount $namesCount $pathsCount $sizesCount"

if [[ $lunsCount -eq $namesCount && $namesCount -eq $pathsCount && $pathsCount -eq $sizesCount ]]
then
  for ((ipart=0; ipart<lunsCount; ipart++))
  do
    lun=${lunsSplit[$ipart]}
    name=${namesSplit[$ipart]}
    path=${pathsSplit[$ipart]}
    size=${sizesSplit[$ipart]}

    log "creating disk with $lun $name $path $size"
    createlvm $lun "vg-$name" "lv-$name" "$path" "$size";
  done
else
  log "count not equal"
fi

osVersion=$(cat /etc/os-release)
if [[ $osVersion =~ SUSE ]]
then
  systemctl restart nfsserver
  systemctl enable nfsserver
fi

exit


#!/bin/bash
set -x
echo "*** Phase 1 - Ansible Startup Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***"

##Error handling functions
fail_if_error() {
  [ $1 != 0 ] && {
    echo $2
    exit 10
  }
}

fail_if_error_phrase() {
  [ $1 != 0 ] && {
    unset PASSPHRASE
    exit 10
  }
}

## Facter Installation For Dynamic Values
yum install ruby wget -y
wget http://download-ib01.fedoraproject.org/pub/epel/7/x86_64/Packages/f/facter-2.4.1-1.el7.x86_64.rpm
rpm  --reinstall -vh facter-2.*.rpm
fail_if_error $? "Facter Installation failed"

#Facter Variables and Declaration
environmentLocation="/etc/facter/facts.d/variables.txt"

if [ -f $environmentLocation ]; then
	rm -f $environmentLocation
fi

cat << EOF > $environmentLocation
azure_storage_account=$1
azure_storage_files_share=$2
viyarepo_folder=$3
app_name=$4
domain_name=$5
ansible_vmname=$6
microservices_vmname=$7
cascontroller_vmname=$8
spre_vmname=${9}
casworker_vmname=${10}
saspwd=${11}
caspwd=${12}
kv_vault_name=${13}
secret_pvt_keyname=${14}
secret_pub_keyname=${15}
cas_nodes=${16}
mid_name=${17}
artifact_loc=${18}
compute_name=${19}
meta_name=${20}
stgacc_secr_name=${21}
cifs_server_fqdn=${22}
EOF

#Defining variables with facter values
azure_storage_account=`facter azure_storage_account`
cifs_server_fqdn=`facter cifs_server_fqdn`
azure_storage_files_share=`facter azure_storage_files_share`
DIRECTORY_NFS_SHARE="sasdepot"
sas_home="/sas/install"
key_vault_name=`facter kv_vault_name`
secret_pvt_keyname=`facter secret_pvt_keyname`
secret_pub_keyname=`facter secret_pub_keyname`
RootCAKey="RootCA.key"
RootCRT="RootCA.crt"
ServerKey="sasqs.key"
ServerCRT="sasqs.crt"
ServerCSR="sasqs.csr"
ssl_path="/opt/ssl"
cert_name="`facter app_name`sas94"

##Updating the Azure Cli Repo
rpm --import https://packages.microsoft.com/keys/microsoft.asc;sh -c 'echo -e "[azure-cli]\nname=Azure CLI\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc" > /etc/yum.repos.d/azure-cli.repo'
##Installing the azure CLI
yum install azure-cli -y
fail_if_error $? "Azure Cli Installation failed"

##Ansible Installation
if ! type -p ansible;  then
    # install Ansible
    curl --retry 10 --max-time 60 --fail --silent --show-error "https://bootstrap.pypa.io/get-pip.py" -o "get-pip.py"
    python get-pip.py
    pip install 'ansible==2.8.3'
	fail_if_error $? "Pip Installation failed"
fi

##Stop & Disable the firewalld(Iptables)
systemctl stop firewalld
systemctl disable firewalld

##Installing RedHat required packages
yum -y install java-1.8.0-openjdk yum-utils firefox xclock x11* xauth git python compat-glibc libpng12 lsof at numactl glibc libpng ntp apr ksh wget mlocate libXext.x86_64 libXp.x86_64 libXtst.x86_64 xorg-x11-xauth.x86_64 gcc libSM.i686 libXrender.i686 zlib.i686 nfs-utils cifs-utils telnet
fail_if_error $? "Error: Rhel packages install Failed"

##Volume Mount for opt-sas
if [ ! -d "$sas_home" ]; then
    sudo mkdir -p $sas_home
fi
lsblk /dev/disk/azure/scsi1/lun0
if [ $? -eq 0 ]; then
    df -h | grep $sas_home
	if [ $? -eq 0 ]; then
		echo "Disk for $sas_home already mounted."
    else
        mkfs.xfs /dev/disk/azure/scsi1/lun0
		mount /dev/disk/azure/scsi1/lun0 $sas_home
		fail_if_error $? "Error:Failed to mount $sas_home"
		## Adding Fstab Entries
		echo "/dev/disk/azure/scsi1/lun0   $sas_home   xfs       defaults        0 0"  >> /etc/fstab
        echo "Disk for $sas_home located and mounted."
    fi
else
    echo "ERROR: $sas_home disk(lun0) disk failed to mount or disk not available."
    exit 1
fi

#Setting up hostname for Ansible Controller
ansible_host=`facter app_name``facter ansible_vmname`.`facter domain_name`
hostnamectl set-hostname --static ${ansible_host}
if [ $? -eq 0 ]; then
    echo "hostname update successful"
    if [ -f /etc/hostname ]; then
        chattr -i /etc/hostname
        rm -f /etc/hostname
        echo ${ansible_host} > /etc/hostname
        chattr +i /etc/hostname
    fi
    if [ -f /etc/sysconfig/network ]; then
        echo "HOSTNAME=${ansible_host}" >> /etc/sysconfig/network
    fi
    echo "Restart Network Service"
    /etc/init.d/network restart
else
    echo "Hostname Update failed"
fi
az login --identity
fail_if_error $? "Error: Az login Failed"
stgacc_secr_name=`facter stgacc_secr_name`
azure_storage_files_password=`az keyvault secret show -n $stgacc_secr_name --vault-name $key_vault_name | grep value | cut -d '"' -f4`
#Mounting File Share for SAS Viya Installation
echo "setup cifs"
if [ ! -d "/etc/smbcredentials" ]; then
    sudo mkdir /etc/smbcredentials
fi
chmod 700 /etc/smbcredentials
if [ ! -f "/etc/smbcredentials/"${azure_storage_account}".cred" ]; then
    echo "username=${azure_storage_account}" >> /etc/smbcredentials/${azure_storage_account}.cred
    echo "password=${azure_storage_files_password}" >> /etc/smbcredentials/${azure_storage_account}.cred
fi
chmod 600 "/etc/smbcredentials/${azure_storage_account}.cred"

mkdir -p "/${DIRECTORY_NFS_SHARE}"
mount -t cifs //${cifs_server_fqdn}/${azure_storage_files_share} /${DIRECTORY_NFS_SHARE}  -o vers=3.0,credentials=/etc/smbcredentials/${azure_storage_account}.cred,dir_mode=0777,file_mode=0777,serverino
fail_if_error $? "Error: SAS Depot Mount Failed"

#Passworless SSH Authentication and SSL Certificate Generation
export RANDFILE=$ssl_path/.rnd
echo "server_cn=`facter app_name``facter mid_name`.`facter domain_name`" > /etc/facter/facts.d/server_cn.txt
echo -e y | ssh-keygen -t rsa -q -f ~/.ssh/id_rsa -N ""
fail_if_error $? "ERROR: Key generation failed."

## Uploading the keys to key vault
az keyvault secret set -n ${secret_pub_keyname} --value "`cat ~/.ssh/id_rsa.pub`" --vault-name ${key_vault_name}
fail_if_error $? "ERROR:Key Vault, Public Key Upload Failed."

az keyvault secret set -n ${secret_pvt_keyname} --value "`cat ~/.ssh/id_rsa`" --vault-name ${key_vault_name}
fail_if_error $? "ERROR: Key Vault, Private Key Upload Failed."

##self-signed SSL Certificates
if [ ! -d "$ssl_path" ]; then
    sudo mkdir -p $ssl_path
fi
# Generate a passphrase
export PASSPHRASE=$(head -c 500 /dev/urandom | tr -dc a-z0-9A-Z | head -c 16; echo)
# Certificate details; replace items in angle brackets with your own info
subj="
C=UK
ST=Lon
O=IT
localityName=Marlow
commonName=RootCA
organizationalUnitName=QS
"
##CA
cat > $ssl_path/CA.cfg << EOF
[ v3_ca ]
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid:always,issuer
basicConstraints = CA:true,pathlen:3
EOF

# Generate the server root key
openssl genrsa -des3 -passout env:PASSPHRASE -out $ssl_path/$RootCAKey 2048
fail_if_error_phrase $?

# Generate the CSR
openssl req \
    -new \
    -subj "$(echo -n "$subj" | tr "\n" "/")" \
    -key $ssl_path/$RootCAKey \
    -out $ssl_path/RootCA.csr \
    -passin env:PASSPHRASE
fail_if_error_phrase $?
cp $ssl_path/$RootCAKey $ssl_path/${RootCAKey}.org
fail_if_error_phrase $?
# Strip the password so we don't have to type it every time we restart Apache
openssl rsa -in $ssl_path/${RootCAKey}.org -out $ssl_path/${RootCAKey} -passin env:PASSPHRASE
fail_if_error_phrase $?
# Generate the cert (good for 10 years)
openssl x509 -req -days 3650 -in $ssl_path/RootCA.csr -extfile $ssl_path/CA.cfg -extensions v3_ca -signkey $ssl_path/$RootCAKey -out $ssl_path/$RootCRT
fail_if_error_phrase $?

server_cn=`facter server_cn`
# Generate the server sas key
openssl genrsa -des3 -passout env:PASSPHRASE -out $ssl_path/$ServerKey 2048
fail_if_error_phrase $?
# Certificate details; replace items in angle brackets with your own info
serversubj="
C=UK
ST=Lon
O=IT
localityName=Marlow
commonName=$server_cn
organizationalUnitName=QS
"

# Generate the server private key
openssl genrsa -des3 -out $ssl_path/$ServerKey -passout env:PASSPHRASE 2048
fail_if_error_phrase $?
# Generate the Server CSR
openssl req \
    -new \
    -batch \
    -subj "$(echo -n "$serversubj" | tr "\n" "/")" \
    -key $ssl_path/$ServerKey \
    -out $ssl_path/$ServerCSR \
    -passin env:PASSPHRASE
fail_if_error_phrase $?
cp $ssl_path/$ServerKey $ssl_path/${ServerKey}.org
fail_if_error_phrase $?
# Strip the password so we don't have to type it every time we restart Apache
openssl rsa -in $ssl_path/${ServerKey}.org -out $ssl_path/$ServerKey -passin env:PASSPHRASE
fail_if_error_phrase $?

# Generate the cert (good for 10 years)
openssl x509 -req -days 3650 -in $ssl_path/$ServerCSR -CA $ssl_path/RootCA.crt -CAkey $ssl_path/RootCA.key -set_serial 1 -out $ssl_path/$ServerCRT
fail_if_error_phrase $?
# Bundle
cat $ssl_path/$ServerCRT $ssl_path/RootCA.crt > $ssl_path/${cert_name}bundle.crt
fail_if_error_phrase $?

## Creating pfx file
openssl pkcs12 -export -out ${ssl_path}/${server_cn}.pfx -inkey ${ssl_path}/$ServerKey -in ${ssl_path}/${cert_name}bundle.crt -passout pass:
fail_if_error_phrase $?

# Uploading Self Signed certificate to Key Vault
az keyvault certificate import --file $ssl_path/${server_cn}.pfx --name $cert_name --vault-name $key_vault_name

echo "*** Phase 1 Completed - Ansible Startup Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***"


#!/bin/bash
set -x
echo "*** Phase 2 -  Ansible SAS 94 SSL Certs Copy `date +'%Y-%m-%d_%H-%M-%S'` ***"

# Function for error handling
fail_if_error() {
  [ $1 != 0 ] && {
    echo $2
    exit 10
  }
}

# Variables
meta_host_name=`facter app_name``facter meta_name`
mid_host_name=`facter app_name``facter mid_name`
compute_host_name=`facter app_name``facter compute_name`

# SSL Certificates & encryption keys copy
scp -o StrictHostKeyChecking=no /opt/ssl/*.key ${meta_host_name}:/home/sasinst/
scp -o StrictHostKeyChecking=no /opt/ssl/*.crt ${meta_host_name}:/home/sasinst/
scp -o StrictHostKeyChecking=no /opt/ssl/*.crt ${meta_host_name}:/home/sasinst/
scp -o StrictHostKeyChecking=no ${meta_host_name}:/root/enc* .
fail_if_error $? "Error: Passwordless SSH for Meta Failed"

scp -o StrictHostKeyChecking=no /opt/ssl/*.key ${compute_host_name}:/home/sasinst/
scp -o StrictHostKeyChecking=no /opt/ssl/*.crt ${compute_host_name}:/home/sasinst/
scp -o StrictHostKeyChecking=no enc* ${compute_host_name}:/root/
fail_if_error $? "Error: Passwordless SSH for Compute Failed"

scp -o StrictHostKeyChecking=no /opt/ssl/*.crt ${mid_host_name}:/home/sasinst/
scp -o StrictHostKeyChecking=no /opt/ssl/*.key ${mid_host_name}:/home/sasinst/
scp -o StrictHostKeyChecking=no enc* ${mid_host_name}:/root/
fail_if_error $? "Error: Passwordless SSH for Mid Failed"

# Deleting Unwanted resources
rm -rf /opt/ssl/*.key
rm -rf /opt/ssl/*.crt
rm -rf /root/enc*

echo "*** Completed Phase 2 -  Ansible SAS 94 SSL Certs Copy `date +'%Y-%m-%d_%H-%M-%S'` ***"


#!/bin/bash
set -x
echo "*** Phase 3 - SAS Compute Config Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***"

##Error handling function
fail_if_error() {
  [ $1 != 0 ] && {
    echo $2
    exit 10
  }
}

##Local Variables
app_name=`facter application_name`
artifact_loc=`facter artifact_loc`
depot_loc=`facter sasdepot_folder`
res_dir="/opt/sas/resources/responsefiles"
resource_dir="/opt/sas/resources"
conf_prop=${resource_dir}/compute_config.properties
cert_prop=${resource_dir}/ssl_cert.properties

##Replace crt in certupdatemid.properties
cp -p ${res_dir}/ssl_cert.properties ${resource_dir}
sed -i "s|certname|${app_name}|g" ${resource_dir}/ssl_cert.properties

## Password Update
encsasextpw=$(</root/encext.txt)
sed -i "s/changeextpass/${encsasextpw}/g" $resource_dir/*.properties
echo "Encrypted password has been updated successfully."
encsasintpw=$(</root/encint.txt)
sed -i "s/changeintpass/${encsasintpw}/g" $resource_dir/*.properties
echo "Encrypted password has been updated succesfully."
rm -f /root/enc*.txt

#Add certificate to trustedstore
su - sasinst -c "time /opt/sas/home/SASDeploymentManager/9.4/sasdm.sh -deploy -responsefile ${cert_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet"
fail_if_error $? "ERROR: SAS certificate update failed. Please check logs"

##SAS Configuration
if [ -f ${conf_prop} ]; then
    if [ ! -f /opt/sas/config/Lev1/sas.servers ]; then
        sudo /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh
        su - sasinst -c "time /sasdepot/${depot_loc}/setup.sh -deploy -responsefile ${conf_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet"
        if [ $? -eq 0 ]; then
            echo "SAS Compute Server Configuration has been completed succesfully."
            sed -i "s|-WORK /tmp|-WORK /saswork|g" /opt/sas/home/SASFoundation/9.4/sasv9.cfg
            su - sasinst -c "/opt/sas/config/Lev1/ObjectSpawner/ObjectSpawner.sh stop > /var/logs/ObjectSpawnerstop.txt"
            sleep 10
            su - sasinst -c "/opt/sas/config/Lev1/ObjectSpawner/ObjectSpawner.sh start > /var/logs/ObjectSpawnerstart.txt"
        else
            fail_if_error 1 "ERROR: SAS Compute Server Configuration has failed. Please check logs"

        fi
    else
        telnet -apln |grep 8581
        if [ $? -eq 0 ]; then
            echo "SAS Compute Server is Up. Proceeding to Next Phase."
        else
            echo "SAS Compute Server has been configured. Starting Services now."
            su - sasinst -c "/opt/sas/config/Lev1/sas.servers start"
            echo "SAS Compute Services have been started."
        fi
    fi
else
    fail_if_error 1 "ERROR: SAS Config Properties file not found. Exiting Now."

fi
echo "*** Phase 3 - SAS Compute Config Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***"


#!/bin/bash
set -x
echo "*** Phase 2 - SAS Compute Install Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***"

## Function for error handling
fail_if_error() {
  [ $1 != 0 ] && {
    echo $2
    exit 10
  }
}

##Global Variables
depot_loc=`facter sasdepot_folder`
store_name=`facter storage_account_name`
store_loc=`facter file_share_name`
key_vault_name=`facter key_vault_name`
stgacc_secr_name=`facter stgacc_secr_name`
app_name=`facter application_name`
sas_role=`facter sas_role`
domain_name=`facter domain_name`
depot_loc=`facter sasdepot_folder`
sas_sid=`facter sas_sid`
artifact_loc=`facter artifact_loc`
meta_host=`facter meta_hostname`
compute_host=`facter compute_hostname`
mid_host=`facter mid_hostname`
sasint_secret_name=`facter sasint_secret_name`
sasext_secret_name=`facter sasext_secret_name`
pub_keyname=`facter pub_keyname`
res_dir="/opt/sas/resources/responsefiles"
resource_dir="/opt/sas/resources"
cifs_server_fqdn=`facter cifs_server_fqdn`
inst_prop=$resource_dir/compute_install.properties
conf_prop=$resource_dir/compute_config.properties

# Getting the password
az login --identity
fail_if_error $? "Error: AZ login failed"
sasintpw=`az keyvault secret show -n $sasint_secret_name --vault-name $key_vault_name | grep value | cut -d '"' -f4`
sasextpw=`az keyvault secret show -n $sasext_secret_name --vault-name $key_vault_name | grep value | cut -d '"' -f4`
store_key=`az keyvault secret show -n $stgacc_secr_name --vault-name $key_vault_name | grep value | cut -d '"' -f4`
echo `az keyvault secret show -n ${pub_keyname}  --vault-name ${key_vault_name} | grep value | cut -d '"' -f4` >> ~/.ssh/authorized_keys
fail_if_error $? "Error: Key Vault Access failed"

#Creating SAS group
cat /etc/group |grep -w sas
if [ $? -eq 0 ]; then
    echo "SAS Group exists"
else
    groupadd -g 5001 sas
    fail_if_error $? "Error: failed to create sas group"
fi

##Creating SAS internal Users
username=("sasinst" "sassrv" "sasdemo")
userid=("1002" "1003" "1005")
for ((i=0;i<${#username[@]};++i));
do
    if [ ! -f /home/${username[$i]} ]; then
        useradd -u ${userid[$i]} -g sas ${username[$i]}
        fail_if_error $? "ERROR: failed to create ${username[$i]} User"
        echo ${sasextpw} | passwd ${username[$i]} --stdin
    else
        echo "User ${username[$i]} exists"
    fi
done

##Set permissions for opt-sas and sasdepot directories
if [ ! -d /opt/sas/home ]; then
    mkdir -p /opt/sas/resources /opt/sas/home /opt/sas/config
fi
chmod 775 /opt/sas -R
chown -R sasinst:sas /opt/sas
chown -R sasinst:sas /sasdata
echo "Permissions for opt-sas and sasdepot have been set."

##Mount Azure File Share for SASDepot
df -h | grep -w /sasdepot
if [ $? -eq 0 ]; then
    echo "SASDepot already mounted."
else
    if [ ! -d "/etc/smbcredentials" ]; then
        sudo mkdir /etc/smbcredentials
    fi
    if [ ! -f "/etc/smbcredentials/store.cred" ]; then
        echo "username=${store_name}" >> /etc/smbcredentials/store.cred
        echo "password=${store_key}" >> /etc/smbcredentials/store.cred
    fi
    sudo chmod 600 /etc/smbcredentials/store.cred
    sudo mount -t cifs //${cifs_server_fqdn}/${store_loc} /sasdepot -o vers=3.0,credentials=/etc/smbcredentials/store.cred,dir_mode=0777,file_mode=0777,serverino
    fail_if_error $? "ERROR: Failed to mount Azure file Share"
fi

lsblk |grep -w /saswork
if [ $? -eq 0 ]; then
    chmod 775 /saswork
    chown sasinst:sas /saswork
    echo "SASWork has been located and mounted on /mnt/resource successfully."
else
    echo "ERROR: Failed to mount SASWork volume from Instance Store."
fi

#copyign SID file to local directories from SASDepot
cp -rv /sasdepot/${depot_loc}/sid_files/${sas_sid} /opt/sas/resources/
if [ ! -d $res_dir ]; then
    mkdir -p $res_dir
fi

#Downloading the plan file and property files required for SAS install
tar -xzvf /tmp/response-properties.tar.gz -C ${res_dir}
cp -p ${res_dir}/plan.xml ${resource_dir}
cp -p ${res_dir}/compute_* ${resource_dir}
chown -R sasinst:sas ${resource_dir}

#Altering the property files
sed -i "s/domain_name/${domain_name}/g" $resource_dir/*.properties
sed -i "s/host_name/${compute_host}/g" $resource_dir/*.properties
sed -i "s/meta_host/${meta_host}/g" $resource_dir/*.properties
sed -i "s/mid_host/${mid_host}/g" $resource_dir/*.properties
sed -i "s|sas_plan_file_path|/opt/sas/resources/plan.xml|g" $resource_dir/*.properties
sed -i "s|sas_license_file_path|/opt/sas/resources/${sas_sid}|g" $resource_dir/*.properties

#SAS Installation
if [ -d /opt/sas/temp ]; then
    chown sasinst /opt/sas/temp
else
    mkdir -p /opt/sas/temp
    chown sasinst /opt/sas/temp
fi

if [ -f ${inst_prop} ]; then
    if [ ! -f /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh ]; then
        su - sasinst -c "time /sasdepot/${depot_loc}/setup.sh -deploy -responsefile ${inst_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet"
        if [ $? -eq 0 ]; then
            echo "SAS Compute Server installation has been completed succesfully."
            sudo /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh
            echo "Setuid script has been run successfully."
        else
            echo "ERROR: SAS Compute Server installation has failed. Please check logs"
            exit 1
        fi
    else
        echo "SAS Installation Completed. Proceeding to Configuration stage."
    fi
else
    echo "SAS Install Properties file not found. Exiting Now."
    exit 1
fi

echo "*** Phase 2 - SAS Compute Install Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***"


#!/bin/bash
set -x
echo "*** Phase 3 SAS Meta Config Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***"

## Function for error handling
fail_if_error() {
  [ $1 != 0 ] && {
    echo $2
    exit 10
  }
}

##Variables
app_name=`facter application_name`
artifact_loc=`facter artifact_loc`
depot_loc=`facter sasdepot_folder`
res_dir="/opt/sas/resources/responsefiles"
resource_dir="/opt/sas/resources"
inst_prop=${resource_dir}/meta_install.properties
conf_prop=${resource_dir}/meta_config.properties
cert_prop=${resource_dir}/ssl_cert.properties

cp -p ${res_dir}/ssl_cert.properties ${resource_dir}

##Altering the certificate in property file
sed -i "s|certname|${app_name}|g" ${resource_dir}/ssl_cert.properties
#Add certificate to trustedstore
su - sasinst -c "time /opt/sas/home/SASDeploymentManager/9.4/sasdm.sh -deploy -responsefile ${cert_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet"
fail_if_error $? "ERROR: SAS certificate update failed. Please check logs"

##SAS Meta Configuration
if [ -f ${conf_prop} ]; then
    if [ ! -f /opt/sas/config/Lev1/sas.servers ]; then
        sudo /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh
        su - sasinst -c "time /sasdepot/${depot_loc}/setup.sh -deploy -responsefile ${conf_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet"
        fail_if_error $? "ERROR: SAS Metadata Server Configuration has failed. Please check logs"
    else
        telnet -apln |grep 8561
        if [ $? -eq 0 ]; then
            echo "SAS Metadata Server is Up. Proceeding to Next Phase."
        else
            echo "SAS Metadata Server has been configured. Starting Services now."
            su - sasinst -c "/opt/sas/config/Lev1/sas.servers start"
            echo "SAS Metadata Services have been started."
        fi
    fi
else
    fail_if_error 1 "ERROR: SAS Config Properties file not found. Exiting Now."
fi

echo "*** Phase 3 - SAS Meta Config Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***"


#!/bin/bash
set -x
echo "*** Phase 2 - SAS Meta Install Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***"

## Function for error handling
fail_if_error() {
  [ $1 != 0 ] && {
    echo $2
    exit 10
  }
}

##Global Variables
depot_loc=`facter sasdepot_folder`
store_name=`facter storage_account_name`
store_loc=`facter file_share_name`
key_vault_name=`facter key_vault_name`
stgacc_secr_name=`facter stgacc_secr_name`
app_name=`facter application_name`
sas_role=`facter sas_role`
domain_name=`facter domain_name`
depot_loc=`facter sasdepot_folder`
sas_sid=`facter sas_sid`
artifact_loc=`facter artifact_loc`
meta_host=`facter meta_hostname`
mid_host=`facter mid_hostname`
sasint_secret_name=`facter sasint_secret_name`
sasext_secret_name=`facter sasext_secret_name`
pub_keyname=`facter pub_keyname`
res_dir="/opt/sas/resources/responsefiles"
resource_dir="/opt/sas/resources"
cifs_server_fqdn=`facter cifs_server_fqdn`
inst_prop=${resource_dir}/meta_install.properties
conf_prop=${resource_dir}/meta_config.properties

# Getting the password
az login --identity
fail_if_error $? "Error: AZ login failed"
sasintpw=`az keyvault secret show -n $sasint_secret_name --vault-name $key_vault_name | grep value | cut -d '"' -f4`
sasextpw=`az keyvault secret show -n $sasext_secret_name --vault-name $key_vault_name | grep value | cut -d '"' -f4`
store_key=`az keyvault secret show -n $stgacc_secr_name --vault-name $key_vault_name | grep value | cut -d '"' -f4`
echo `az keyvault secret show -n ${pub_keyname}  --vault-name ${key_vault_name} | grep value | cut -d '"' -f4` >> ~/.ssh/authorized_keys
fail_if_error $? "Error: Key vault access failed"

#Creating sas group
cat /etc/group |grep -w sas
if [ $? -eq 0 ]; then
    echo "SAS Group exists"
else
    groupadd -g 5001 sas
    fail_if_error $? "ERROR: Failed to create sas group"
fi

##Creating SAS internal Users
username=("sasinst" "sassrv" "sasdemo")
userid=("1002" "1003" "1005")
for ((i=0;i<${#username[@]};++i));
do
    if [ ! -f /home/${username[$i]} ]; then
        useradd -u ${userid[$i]} -g sas ${username[$i]}
        fail_if_error $? "ERROR: failed to create ${username[$i]} User"
        echo ${sasextpw} | passwd ${username[$i]} --stdin
    else
        echo "User ${username[$i]} exists"
    fi
done

##Set permissions for opt-sas and sasdepot directories
if [ ! -d /opt/sas/home ]; then
    mkdir -p /opt/sas/resources /opt/sas/home /opt/sas/config
    fail_if_error $? "ERROR: SAS Software directories creation failed"
fi
chmod 775 /opt/sas -R
chown -R sasinst:sas /opt/sas
chown -R sasinst:sas /sasdata
echo "Permissions for opt-sas and sasdepot have been set."

##Mount Azure File Share for SASDepot
df -h | grep -w /sasdepot
if [ $? -eq 0 ]; then
    echo "SASDepot already mounted."
else
    if [ ! -d "/etc/smbcredentials" ]; then
        sudo mkdir /etc/smbcredentials
    fi
    if [ ! -f "/etc/smbcredentials/store.cred" ]; then
        echo "username=${store_name}" >> /etc/smbcredentials/store.cred
        echo "password=${store_key}" >> /etc/smbcredentials/store.cred
    fi
    sudo chmod 600 /etc/smbcredentials/store.cred
    sudo mount -t cifs //${cifs_server_fqdn}/${store_loc} /sasdepot -o vers=3.0,credentials=/etc/smbcredentials/store.cred,dir_mode=0777,file_mode=0777,serverino
    fail_if_error $? "ERROR: Failed to mount Azure file share"
fi

#copyign SID file to local directories from SASDepot
cp -rv /sasdepot/${depot_loc}/sid_files/${sas_sid} /opt/sas/resources/
#Downloading Meta Install Property files
if [ ! -d $res_dir ]; then
    mkdir -p $res_dir
fi

#Extracting the property files
tar -xzvf /tmp/response-properties.tar.gz -C ${res_dir}
cp -p ${res_dir}/plan.xml ${resource_dir}
cp -p ${res_dir}/meta_* ${resource_dir}
chown -R sasinst:sas ${resource_dir}

##Chaning the settings in property files
sed -i "s/domain_name/${domain_name}/g" $resource_dir/*.properties
sed -i "s/host_name/${meta_host}/g" $resource_dir/*.properties
sed -i "s/mid_host/${mid_host}/g" $resource_dir/*.properties
sed -i "s|sas_plan_file_path|/opt/sas/resources/plan.xml|g" $resource_dir/*.properties
sed -i "s|sas_license_file_path|/opt/sas/resources/${sas_sid}|g" $resource_dir/*.properties

#SAS Installation
if [ -d /opt/sas/temp ]; then
    chown sasinst /opt/sas/temp
else
    mkdir -p /opt/sas/temp
    chown sasinst /opt/sas/temp
fi

if [ -f ${inst_prop} ]; then
    if [ ! -f /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh ]; then
        su - sasinst -c "time /sasdepot/${depot_loc}/setup.sh -deploy -responsefile ${inst_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet"
        if [ $? -eq 0 ]; then
            echo "SAS Metadata Server installation has been completed succesfully."
            sudo /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh
            echo "Setuid script has b-een run successfully."
        else
            echo "ERROR: SAS Metadata Server installation has failed. Please check logs"
            exit 1
        fi
    else
        echo "SAS Installation Completed. Proceeding to Configuration stage."
    fi
else
    echo "SAS Install Properties file not found. Exiting Now."
    exit 1
fi

sasextpw=`echo "\""${sasextpw}"\""`
sasintpw=`echo "\""${sasintpw}"\""`
##Encrypting sasextpw password
echo  "filename pwfile '/root/encext.txt'; proc pwencode in=${sasextpw} out=pwfile; run;" > /root/encext.sas
/opt/sas/home/SASFoundation/9.4/bin/sas_u8 -sysin /root/encext.sas -log /root/sasencext.log
fail_if_error $? "ERROR: SAS External Password encryption failed."
encsasextpw=$(</root/encext.txt)
sed -i "s/changeextpass/${encsasextpw}/g" $resource_dir/*.properties
echo "Encrypted password has been updated successfully."
##Encrypting sasintpw password
echo  "filename pwfile '/root/encint.txt'; proc pwencode in=${sasintpw} out=pwfile; run;" > /root/encint.sas
/opt/sas/home/SASFoundation/9.4/bin/sas_u8 -sysin /root/encint.sas -log /root/sasencint.log
fail_if_error $? "ERROR: SAS Internal Password encryption failed."
encsasintpw=$(</root/encint.txt)
sed -i "s/changeintpass/${encsasintpw}/g" $resource_dir/*.properties
echo "Encrypted password has been updated succesfully."

echo "*** Phase 2 - SAS Install Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***"


#!/bin/bash
set -x
echo "*** Phase 3 - SAS Mid-Tier Config Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***"

## Function for error handling
fail_if_error() {
  [ $1 != 0 ] && {
    echo $2
    exit 10
  }
}

##Local Variables
app_name=`facter application_name`
artifact_loc=`facter artifact_loc`
depot_loc=`facter sasdepot_folder`
res_dir="/opt/sas/resources/responsefiles"
resource_dir="/opt/sas/resources"
conf_prop=${resource_dir}/mid_config.properties
cert_prop=${resource_dir}/ssl_cert.properties

##Create VMWare Directories
mkdir -p /etc/opt/vmware/vfabric/
chown sasinst:sas /etc/opt/vmware -R

cp -p ${res_dir}/ssl_cert.properties ${resource_dir}

##changing the ssl setting in properties file
sed -i "s|certname|${app_name}|g" ${resource_dir}/ssl_cert.properties
sed -i "s|certname|${app_name}|g" ${resource_dir}/mid_config.properties

## Password Update
encsasextpw=$(</root/encext.txt)
sed -i "s/changeextpass/${encsasextpw}/g" $resource_dir/*.properties
echo "Encrypted password has been updated successfully."
encsasintpw=$(</root/encint.txt)
sed -i "s/changeintpass/${encsasintpw}/g" $resource_dir/*.properties
echo "Encrypted password has been updated succesfully."

#Add certificate to trustedstore
su - sasinst -c "time /opt/sas/home/SASDeploymentManager/9.4/sasdm.sh -deploy -responsefile ${cert_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet"
fail_if_error $? "ERROR: SAS certificate update failed. Please check logs"

##SAS Configuration
if [ -f ${conf_prop} ]; then
    if [ ! -f /opt/sas/config/Lev1/sas.servers ]; then
        sudo /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh
        su - sasinst -c "time /sasdepot/${depot_loc}/setup.sh -deploy -responsefile ${conf_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet"
        fail_if_error $? "ERROR: SAS Compute Server Configuration has failed. Please check logs"
    else
        telnet -apln |grep 7980
        if [ $? -eq 0 ]; then
            echo "SAS Mid-Tier Server is Up. Proceeding to Next Phase."
        else
            echo "SAS Mid-Tier Server has been configured. Starting Services now."
            su - sasinst -c "/opt/sas/config/Lev1/sas.servers start"
            echo "SAS Mid-Tier Services have been started."
        fi
    fi
else
    echo "SAS Config Properties file not found. Exiting Now."
    exit 1
fi

echo "*** Phase 3 - SAS Mid-Tier Config Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***"


#!/bin/bash
set -x
echo "*** Phase 2 - SAS Mid-Tier Install Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***"

## Function for error handling
fail_if_error() {
  [ $1 != 0 ] && {
    echo $2
    exit 10
  }
}

##Global Variables
depot_loc=`facter sasdepot_folder`
store_name=`facter storage_account_name`
store_loc=`facter file_share_name`
app_name=`facter application_name`
stgacc_secr_name=`facter stgacc_secr_name`
sas_role=`facter sas_role`
domain_name=`facter domain_name`
depot_loc=`facter sasdepot_folder`
sas_sid=`facter sas_sid`
host_name="${app_name}${sas_role}"
meta_host=`facter meta_hostname`
compute_host=`facter compute_hostname`
mid_host=`facter mid_hostname`
sasint_secret_name=`facter sasint_secret_name`
sasext_secret_name=`facter sasext_secret_name`
key_vault_name=`facter key_vault_name`
pub_keyname=`facter pub_keyname`
artifact_loc=`facter artifact_loc`
res_dir="/opt/sas/resources/responsefiles"
resource_dir="/opt/sas/resources"
cifs_server_fqdn=`facter cifs_server_fqdn`
inst_prop=${resource_dir}/mid_install.properties
conf_prop=${resource_dir}/mid_config.properties

# Getting the password
az login --identity
fail_if_error $? "ERROR: AZ Login Failed "
sasintpw=`az keyvault secret show -n $sasint_secret_name --vault-name $key_vault_name | grep value | cut -d '"' -f4`
sasextpw=`az keyvault secret show -n $sasext_secret_name --vault-name $key_vault_name | grep value | cut -d '"' -f4`
store_key=`az keyvault secret show -n $stgacc_secr_name --vault-name $key_vault_name | grep value | cut -d '"' -f4`
echo `az keyvault secret show -n ${pub_keyname}  --vault-name ${key_vault_name} | grep value | cut -d '"' -f4` >> ~/.ssh/authorized_keys

#SAS group creation
cat /etc/group |grep -w sas
if [ $? -eq 0 ]; then
    echo "SAS Group exists"
else
    groupadd -g 5001 sas
    fail_if_error $? "ERROR: SAS group creation failed"
fi

##Creating SAS internal Users
username=("sasinst" "sassrv" "sasdemo")
userid=("1002" "1003" "1005")
for ((i=0;i<${#username[@]};++i));
do
    if [ ! -f /home/${username[$i]} ]; then
        useradd -u ${userid[$i]} -g sas ${username[$i]}
        fail_if_error $? "ERROR: failed to create ${username[$i]} User"
        echo ${sasextpw} | passwd ${username[$i]} --stdin
    else
        echo "User ${username[$i]} exists"
    fi
done

##Set permissions for opt-sas and sasdepot directories
if [ ! -d /opt/sas/home ]; then
    mkdir -p /opt/sas/resources /opt/sas/home /opt/sas/config
    fail_if_error $? "ERROR: SAS directories creation failed"
fi
chmod 775 /opt/sas -R
chown -R sasinst:sas /opt/sas
echo "Permissions for opt-sas and sasdepot have been set."

##Mount Azure File Share for SASDepot
df -h | grep -w /sasdepot
if [ $? -eq 0 ]; then
    echo "SASDepot already mounted."
else
    if [ ! -d "/etc/smbcredentials" ]; then
        sudo mkdir /etc/smbcredentials
    fi
    if [ ! -f "/etc/smbcredentials/store.cred" ]; then
        echo "username=${store_name}" >> /etc/smbcredentials/store.cred
        echo "password=${store_key}" >> /etc/smbcredentials/store.cred
    fi
    sudo chmod 600 /etc/smbcredentials/store.cred
    sudo mount -t cifs //${cifs_server_fqdn}/${store_loc} /sasdepot -o vers=3.0,credentials=/etc/smbcredentials/store.cred,dir_mode=0777,file_mode=0777,serverino
    fail_if_error $? "ERROR: Failed to Mount Azure file share"
fi

#copyign SID file to local directories from SASDepot
cp -rv /sasdepot/${depot_loc}/sid_files/${sas_sid} /opt/sas/resources/
if [ ! -d $res_dir ]; then
    mkdir -p $res_dir
fi

#extracting the properties files
tar -xzvf /tmp/response-properties.tar.gz -C ${res_dir}
cp -p ${res_dir}/plan.xml ${resource_dir}
cp -p ${res_dir}/mid_* ${resource_dir}
chown -R sasinst:sas ${resource_dir}

#Changing the settings in property files
sed -i "s/domain_name/${domain_name}/g" $resource_dir/*.properties
sed -i "s/host_name/${mid_host}/g" $resource_dir/*.properties
sed -i "s/meta_host/${meta_host}/g" $resource_dir/*.properties
sed -i "s|sas_plan_file_path|/opt/sas/resources/plan.xml|g" $resource_dir/*.properties
sed -i "s|sas_license_file_path|/opt/sas/resources/${sas_sid}|g" $resource_dir/*.properties

#SAS Installation
if [ -d /opt/sas/temp ]; then
    chown sasinst /opt/sas/temp
else
    mkdir -p /opt/sas/temp
    chown sasinst /opt/sas/temp
fi

if [ -f ${inst_prop} ]; then
    if [ ! -f /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh ]; then
        su - sasinst -c "time /sasdepot/${depot_loc}/setup.sh -deploy -responsefile ${inst_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet"
        if [ $? -eq 0 ]; then
            echo "SAS Mid-Tier Server installation has been completed succesfully."
            sudo /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh
            echo "Setuid script has been run successfully."
        else
            echo "ERROR: SAS Mid-Tier Server installation has failed. Please check logs"
            exit 1
        fi
    else
        echo "SAS Installation Completed. Proceeding to Configuration stage."
    fi
else
    echo "SAS Install Properties file not found. Exiting Now."
    exit 1
fi

echo "*** Phase 2 - SAS Mid-Tier Install Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***"


#/bin/bash
set -x
echo "*** Phase 1 - Pre-Reqs Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***"

## Functions
fail_if_error() {
  [ $1 != 0 ] && {
    echo $2
    exit 10
  }
}

##Installing facter tool
yum install ruby wget -y
wget http://download-ib01.fedoraproject.org/pub/epel/7/x86_64/Packages/f/facter-2.4.1-1.el7.x86_64.rpm
rpm  --reinstall -vh facter-2.*.rpm
fail_if_error $? "Error: Facter installation failed"

#Facter Variables and Declaration
environmentLocation="/etc/facter/facts.d/variables.txt"

if [ -f $environmentLocation ]; then
	rm -f $environmentLocation
fi

cat << EOF > $environmentLocation
application_name=$1
sasdepot_folder=$2
file_share_name=$3
storage_account_name=$4
domain_name=$5
location=$6
sasint_secret_name=$7
sasext_secret_name=$8
key_vault_name=$9
pvt_keyname=${10}
pub_keyname=${11}
mid_name=${12}
meta_name=${13}
compute_name=${14}
sas_sid=${15}
sas_role=${16}
artifact_loc=${17}
stgacc_secr_name=${18}
cifs_server_fqdn=${19}
mid_hostname=${1}${12}
meta_hostname=${1}${13}
compute_hostname=${1}${14}
EOF

#Updating the Azure Cli Repo
rpm --import https://packages.microsoft.com/keys/microsoft.asc;sh -c 'echo -e "[azure-cli]\nname=Azure CLI\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc" > /etc/yum.repos.d/azure-cli.repo'
# Installing the azure CLI
yum install azure-cli -y
fail_if_error $? "Error: Azure cli installation failed"

#Stop & Disable the firewalld(Iptables)
systemctl stop firewalld
systemctl disable firewalld

meta_hostname=`facter meta_hostname`
mid_hostname=`facter mid_hostname`
compute_hostname=`facter compute_hostname`
domain_name=`facter domain_name`
sas_role=`facter sas_role`
sas_home="/opt/sas"

hostname_setup() {
	hostnamectl set-hostname --static ${1}.${domain_name}
	if [ $? -eq 0 ]; then
    	echo "hostname update successful"
    	if [ -f /etc/hostname ]; then
        	chattr -i /etc/hostname
        	rm -f /etc/hostname
        	echo ${1}.${domain_name} > /etc/hostname
        	chattr +i /etc/hostname
    	fi
    	if [ -f /etc/sysconfig/network ]; then
    	    echo "HOSTNAME=${1}.${domain_name}" >> /etc/sysconfig/network
    	fi
   		echo "Restart Network Service"
   		/etc/init.d/network restart
	else
 	   echo "Hostname Update failed"
fi
}

if [ $sas_role == meta ]; then
	hostname_setup $meta_hostname
elif [ $sas_role == mid ]; then
	hostname_setup $mid_hostname
elif [ $sas_role == compute ]; then
	hostname_setup $compute_hostname
else
	echo "ERROR: SAS ROLE is not defined"
	exit 1
fi

yum -y install java firefox xclock x11* xauth python git compat-glibc libpng12 lsof at numactl glibc libpng ntp apr ksh wget mlocate libXext.x86_64 libXp.x86_64 libXtst.x86_64 xorg-x11-xauth.x86_64 gcc libSM.i686 libXrender.i686 zlib.i686 nfs-utils cifs-utils telnet
fail_if_error $? "ERROR: PreRequisites installation failed"

#System settings
if [ -f /etc/security/limits.conf ]; then
	cat /etc/security/limits.conf| grep -w 500000
	a=`echo $?`
	echo $a
	if [ "$a" != "0" ]; then
		echo $a
		sed -i '$d' /etc/security/limits.conf
		echo "*               hard    nofile  500000" >> /etc/security/limits.conf
		echo "*               soft    nofile  500000" >> /etc/security/limits.conf
		echo "*               soft    nproc   650000" >> /etc/security/limits.conf
		echo "*               hard    nproc   500000" >> /etc/security/limits.conf
		echo "*               hard    stack   10240" >> /etc/security/limits.conf
		echo "*               soft    stack   10240" >> /etc/security/limits.conf
		echo "*               soft    stack   10240" >> /etc/security/limits.conf

		echo "# End of file" >> /etc/security/limits.conf
	fi
fi
if [ -f /etc/security/limits.d/20-nproc.conf ]; then
	sed -i 's/4096/unlimited/g' /etc/security/limits.d/20-nproc.conf
fi
echo "Security Limit values updated successfully."

##SSHD Configuration
if [ -f /etc/ssh/sshd_config ]; then
	PA="PasswordAuthentication yes "
	PRT="PermitRootLogin yes"
	x=`grep -i PermitRootLogin /etc/ssh/sshd_config`
	a=`echo $?`
	if [ "$a" == "0" ]; then
		sed -i '/PermitRootLogin/c\'"${PRT}"'' /etc/ssh/sshd_config
	fi
	x=`grep -i PasswordAuthentication /etc/ssh/sshd_config`
	a=`echo $?`
	if [ "$a" == "0" ]; then
		sed -i.bak s/PasswordAuthentication' 'no/PasswordAuthentication' 'yes/g /etc/ssh/sshd_config
	fi
fi
systemctl restart sshd
echo "SSHD Configuration updated successfully."

##Set Semaphore values
echo "kernel.sem=512 32000 256 1024" >> /etc/sysctl.conf
echo "net.core.somaxconn=2048" >> /etc/sysctl.conf
echo "Semaphore values updated successfully."

#Set default timeout values
sed -i.bak -e 's/#DefaultTimeoutStartSec=90s/DefaultTimeoutStartSec=1800s/g' /etc/systemd/system.conf
sed -i.bak -e 's/#DefaultTimeoutStopSec=90s/DefaultTimeoutStartSec=1800s/g' /etc/systemd/system.conf
echo "Timeout values updated successfully."

#Enable yum cache
sed -i.bak -e 's/keepcache=0/keepcache=1/g' /etc/yum.conf
echo "Yum Cache value updated successfully."

#Set MaxStartups
sed -i.bak -e 's/#MaxStartups 10:30:100/MaxStartups 100/g' /etc/ssh/sshd_config
echo "Max Startups value updated successfully."

###Configure SELINUX
setenforce 0
sed -i.bak -e 's/SELINUX=enforcing/SELINUX=permissive/g' /etc/selinux/config
echo "SELINUX set to permissive."

##Create Mount Points
if [ ! -d $sas_home ]; then
	sudo mkdir -p $sas_home
fi
if [ ! -d "/sasdepot" ]; then
	sudo mkdir /sasdepot
fi

echo "SAS Directories created successfully."

##Volume Mount for opt-sas and sasdata
lsblk /dev/disk/azure/scsi1/lun0
if [ $? -eq 0 ]
then
	df -h | grep $sas_home
	if [ $? -eq 0 ]
	then
		echo "Disk for $sas_home already mounted."
	else
		mkfs.xfs /dev/disk/azure/scsi1/lun0
		mount /dev/disk/azure/scsi1/lun0 $sas_home
		fail_if_error $? "Error:Failed to mount $sas_home"
		echo "Disk for $sas_home located and mounted."
		## Adding Fstab Entries
		echo "/dev/disk/azure/scsi1/lun0  $sas_home   xfs       defaults        0 0"  >> /etc/fstab
	fi
else
	echo "ERROR: $sas_home disk(lun0) is not available."
	exit 1
fi

# SAS Data Volume
lsblk /dev/disk/azure/scsi1/lun1
if [ $? -eq 0 ]
then
	mkdir /sasdata
	mkfs.xfs /dev/disk/azure/scsi1/lun1
	mount /dev/disk/azure/scsi1/lun1 /sasdata
	fail_if_error $? "Error:Failed to mount /sasdata"
	echo "Disk for SASData located and mounted."
	## Adding Fstab Entries
	echo "/dev/disk/azure/scsi1/lun1  /sasdata   xfs       defaults        0 0"  >> /etc/fstab
else
	echo "SASData disk not avilable on this machine."
fi

#PAM.D configuration for Host Authentication
if [ ! -f /etc/pam.d/sasauth ]
then
	cp /etc/pam.d/system-auth /etc/pam.d/sasauth
	sed -i '/^-session/d' /etc/pam.d/sasauth
	sed -i '/^session/d' /etc/pam.d/sasauth
	sed -i '/^password/d' /etc/pam.d/sasauth
	if [ $? -eq 0 ]
	then
		echo "PAMD configuration updated successfully."
	else
		echo "ERROR: PAMD configuration update failed."
		exit 1
	fi
else
	echo "PAMD configuration exists."
fi

echo "*** Phase 1 - Pre-Reqs Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***"


#!/bin/bash
#set -x

echo "*** Phase 5 - Viya Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***"

#variable declaration
app_name=`facter app_name`
domain_name=`facter domain_name`
microservices_vm_name=`facter microservices_vmname`
microservice_host=$app_name$microservices_vm_name.$domain_name
user=`whoami`
spre_vm_name=`facter spre_vmname`
spre_host=$app_name$spre_vm_name.$domain_name
cascontroller_vm_name=`facter cascontroller_vmname`
cas_host=$app_name$cascontroller_vm_name.$domain_name
casworker_vm_name=`facter casworker_vmname`
nodes=`facter cas_nodes`
DIRECTORY_NFS_SHARE="sasdepot"
ansible_directory="/sas/install"
playbook_directory="$ansible_directory/sas_viya_playbook"
inventory="$playbook_directory/inventory.ini"
viyarepo_loc=`facter viyarepo_folder`
artifact_loc=`facter artifact_loc`
viya_ark_uri=${artifact_loc}properties/viya-ark.tar.gz

if [[ -z "$SCRIPT_PHASE" ]]; then
        SCRIPT_PHASE="$1"
fi

if [[ "$SCRIPT_PHASE" -eq 1 ]]; then
#
##Downloading SAS Viya Orchestration CLI
#
        echo "Download SAS Viya Orchestration CLI"
        wget https://support.sas.com/installation/viya/35/sas-orchestration-cli/lax/sas-orchestration-linux.tgz
        if [ $? -eq 0 ]; then
            tar -xvf sas-orchestration-linux.tgz -C $ansible_directory
        else
            echo "ERROR: Download of SAS Viya Orchestration CLI failed"
        fi
 #
 ##Creating Viya Playbook
 #
        $ansible_directory/sas-orchestration build --input /${DIRECTORY_NFS_SHARE}/${viyarepo_loc}/SAS_Viya_deployment_data.zip --platform redhat --repository-warehouse "file:///${DIRECTORY_NFS_SHARE}/${viyarepo_loc}/"
        if [ $? -eq 0 ]; then
                echo PWD=`pwd`
                ##untar SAS VIYA Playbook
                tar -xvf $PWD/SAS_Viya_playbook.tgz -C $ansible_directory
        else
                echo "SAS VIYA playbook build failed"
        fi
#
##altering Ansible Config
sed -i '/action_plugins/a host_key_checking = False' $playbook_directory/ansible.cfg

#
##Altering the Vars file
#

sed -i "s~#CAS_DISK_CACHE~CAS_DISK_CACHE~" $playbook_directory/vars.yml
sed -i "s~/tmp~/cascache~" $playbook_directory/vars.yml
sed -i "/#CAS_VIRTUAL_PORT/ a newline" $playbook_directory/vars.yml
sed -i "s|newline|    CASDATADIR: /sasdata|g" $playbook_directory/vars.yml
sed -i 's/#SASV9_CONFIGURATION/SASV9_CONFIGURATION/g' $playbook_directory/vars.yml
echo "  1: 'WORK /saswork'" >> $playbook_directory/vars.yml
echo "  2: 'UTILLOC /saswork'" >> $playbook_directory/vars.yml
sed -i 's/#sasstudio.appserver.port/sasstudio.appserver.port/g' $playbook_directory/vars.yml
sed -i 's/#sasstudio.appserver.https.port/sasstudio.appserver.https.port/g' $playbook_directory/vars.yml
sed -i "/#webdms.workspaceServer.hostName/c\    webdms.workspaceServer.hostName: ${spre_host}" $playbook_directory/vars.yml
sed -i 's/#webdms.workspaceServer.port/webdms.workspaceServer.port/g' $playbook_directory/vars.yml
sed -i 's/#FOUNDATION_CONFIGURATION/FOUNDATION_CONFIGURATION/g' $playbook_directory/vars.yml
sed -i  "/FOUNDATION_CONFIGURATION/a temploc" $playbook_directory/vars.yml
sed -i  "s|temploc|  1: COMPUTESERVER_TMP_PATH=/saswork|g" $playbook_directory/vars.yml

#
##Altering the Inventory file
#
if [ -f $inventory ]; then

sed -i 's/<machine_address>/'"$microservice_host"'/g' $inventory
sed -i 's/<userid>/'"$user"'/g' $inventory
sed -i "s~<keyfile>~/$user/.ssh/id_rsa consul_bind_adapter=eth0~" $inventory

sed -i "2i$spre_vm_name ansible_host=$spre_host ansible_user=$user ansible_ssh_private_key_file=/$user/.ssh/id_rsa consul_bind_adapter=eth0" $inventory

sed -i "3i$cascontroller_vm_name ansible_host=$cas_host ansible_user=$user ansible_ssh_private_key_file=/$user/.ssh/id_rsa consul_bind_adapter=eth0" $inventory

for ((i=0; i < $nodes ; i++))
do
  cat <<EOF >> caswork.txt
$casworker_vm_name$i
EOF
  caswork_host=$app_name$casworker_vm_name$i.$domain_name
  sed -i "4i$casworker_vm_name$i ansible_host=$caswork_host ansible_user=$user ansible_ssh_private_key_file=/$user/.ssh/id_rsa consul_bind_adapter=eth0" $inventory
done

sed -i "/\[sas_casserver_primary\]/{n;s/.*/$cascontroller_vm_name/}" $inventory
sed -i "/\[sas_casserver_worker\]/r caswork.txt" $inventory
sed -i "/\[ComputeServer\]/{n;s/.*/$spre_vm_name/}" $inventory
sed -i "/\[Operations\]/{n;s/.*/$spre_vm_name/}" $inventory
sed -i "/\[programming\]/{n;s/.*/$spre_vm_name/}" $inventory

cat <<EOF >> caswork.txt
$spre_vm_name
$cascontroller_vm_name
EOF
sed -i "/\[CommandLine\]/r caswork.txt" $inventory
rm -f caswork.txt
else
       echo "ERROR: Inventory file path doesnot exist"
fi
#
##Running System Assesement using ansible playbook
#
cd $playbook_directory && ansible-playbook system-assessment.yml -i inventory.ini -vvv

elif [[ "$SCRIPT_PHASE" -eq 2 ]]; then
         mkdir /.ssh && touch /.ssh/known_hosts
        cd $playbook_directory && ansible-playbook install-only.yml -i inventory.ini -vvv
        echo "*** Phase 5 Part 2 - Viya Install only ended at `date +'%Y-%m-%d_%H-%M-%S'` ***"

elif [[ "$SCRIPT_PHASE" -eq 3 ]]; then
        cd $playbook_directory && ansible-playbook site.yml -i inventory.ini -vvv
        echo "*** Phase 5 Part 3 - Viya Configuration ended at `date +'%Y-%m-%d_%H-%M-%S'` ***"

elif [[ "$SCRIPT_PHASE" -eq 4 ]]; then
        wget $viya_ark_uri
        mkdir -p $playbook_directory/viya-ark
        tar -xzvf viya-ark.tar.gz -C $playbook_directory/viya-ark/
        ssh -tT $user@${spre_host} << EOF
echo "export SASMAKEHOMEDIR=1"     >> /opt/sas/viya/config/etc/spawner/default/spawner_usermods.sh
echo "export SASHOMEDIRPERMS=0700" >> /opt/sas/viya/config/etc/spawner/default/spawner_usermods.sh
EOF

for s in ${microservice_host} ${spre_host} ${cas_host}
do
        ssh -tT $user@$s << EOF
. /opt/sas/viya/config/consul.conf
/opt/sas/viya/home/bin/sas-bootstrap-config --token-file /opt/sas/viya/config/etc/SASSecurityCertificateFramework/tokens/consul/default/client.token kv write config/launcher-server/global/environment/SASMAKEHOMEDIR 1
/opt/sas/viya/home/bin/sas-bootstrap-config --token-file /opt/sas/viya/config/etc/SASSecurityCertificateFramework/tokens/consul/default/client.token kv write config/launcher-server/global/environment/SASHOMEDIRPERMS 0700
EOF
done

for ((i=0; i < $nodes ; i++))
do
        casworker_node=$app_name$casworker_vm_name$i.$domain_name
        ssh -tT $user@$casworker_node << EOF
. /opt/sas/viya/config/consul.conf
/opt/sas/viya/home/bin/sas-bootstrap-config --token-file /opt/sas/viya/config/etc/SASSecurityCertificateFramework/tokens/consul/default/client.token kv write config/launcher-server/global/environment/SASMAKEHOMEDIR 1
/opt/sas/viya/home/bin/sas-bootstrap-config --token-file /opt/sas/viya/config/etc/SASSecurityCertificateFramework/tokens/consul/default/client.token kv write config/launcher-server/global/environment/SASHOMEDIRPERMS 0700
EOF
done
echo `ssh -o StrictHostKeyChecking=no $app_name$microservices_vm_name "grep -H -r "sasboot" /var/log/sas/viya/saslogon/default/sas-saslogon*  | sed 's/.*code=//'"`
sasboot=`ssh -o StrictHostKeyChecking=no $app_name$microservices_vm_name "grep -H -r "sasboot" /var/log/sas/viya/saslogon/default/sas-saslogon*  | sed 's/.*code=//'"`
echo "{'SAS_BOOT': '$sasboot'}" > /var/log/sas/install/sasboot.log
echo "#SASBOOT#"
cat /var/log/sas/install/sasboot.log
fi


#!/bin/bash
set -x

echo "*** Phase 2 - Viya-ARK Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***"

## Functions
fail_if_error() {
  [ $1 != 0 ] && {
    echo $2
    exit 10
  }
}

#Variable declaration
pub_keyname=`facter secret_pub_keyname`
key_vault_name=`facter kv_vault_name`
artifact_loc=`facter artifact_loc`
sasint_secret_name=`facter sasintpwd`
sasext_secret_name=`facter casintpwd`
CODE_DIRECTORY="/opt/viya-ark"
playbook_directory="$CODE_DIRECTORY/pre-install-playbook"
#viya_ark_file=`facter viya_ark_file`

# Setting up the public key under root user for passwordless SSH
az login --identity
fail_if_error $? "ERROR: Azure login failed"
saspwd=`az keyvault secret show -n $sasint_secret_name --vault-name $key_vault_name | grep value | cut -d '"' -f4`
caspwd=`az keyvault secret show -n $sasext_secret_name --vault-name $key_vault_name | grep value | cut -d '"' -f4`
echo `az keyvault secret show -n ${pub_keyname}  --vault-name ${key_vault_name} | grep value | cut -d '"' -f4` >> ~/.ssh/authorized_keys

#wget $viya_ark_file

##untar viya-ark
if [ ! -d ${CODE_DIRECTORY} ]; then
    mkdir -p ${CODE_DIRECTORY}
fi
  tar -xzvf /tmp/viya-ark.tar.gz -C ${CODE_DIRECTORY}
  fail_if_error $? "viya-ark file not found"
#
## Running the Ansible Playbook on the Viya Servers
#
cd $playbook_directory && ansible-playbook viya_pre_install_playbook.yml -i pre-install.inventory.ini  -vvv
#
## Setting up Password for user SAS and CAS
#
username=("sas" "cas")
password=("$saspwd" "$caspwd")
for ((i=0;i<${#username[@]};++i));
do
        if [ `sed -n "/^${username[$i]}/p" /etc/passwd` ]
        then
                echo "Setting the password for ${username[$i]}"
                echo ${password[$i]} | passwd ${username[$i]}  --stdin
    else
                echo "User ${username[$i]} doesn't exist"
        fi
done

echo "*** Phase 2 - Viya-ARK Script ended at `date +'%Y-%m-%d_%H-%M-%S'` ***"


#!/bin/bash
set -x
echo "*** Phase 1 - Pre-Reqs Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***"

## Functions
fail_if_error() {
  [ $1 != 0 ] && {
    echo $2
    exit 10
  }
}

## Facter Installation
yum install ruby wget -y
wget http://download-ib01.fedoraproject.org/pub/epel/7/x86_64/Packages/f/facter-2.4.1-1.el7.x86_64.rpm
rpm  --reinstall -vh facter-2.*.rpm
fail_if_error $? "Error: Facter installation failed"

#Facter Variables and Declaration
environmentLocation="/etc/facter/facts.d/variables.txt"

if [ -f $environmentLocation ]; then
	rm -f $environmentLocation
fi

#Facter Variables and Declaration
cat << EOF > $environmentLocation
azure_storage_account=$1
azure_storage_files_share=$2
DIRECTORY_NFS_SHARE=$3
app_name=$4
domain_name=$5
ansible_vmname=$6
microservices_vmname=$7
cascontroller_vmname=$8
spre_vmname=${9}
casworker_vmname=${10}
sasintpwd=${11}
casintpwd=${12}
kv_vault_name=${13}
secret_pvt_keyname=${14}
secret_pub_keyname=${15}
cas_nodes=${16}
artifact_loc=${17}
stgacc_secr_name=${18}
cifs_server_fqdn=${19}
EOF

#Updating the Azure Cli Repo
rpm --import https://packages.microsoft.com/keys/microsoft.asc;sh -c 'echo -e "[azure-cli]\nname=Azure CLI\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc" > /etc/yum.repos.d/azure-cli.repo'
# Installing the azure CLI
yum install azure-cli -y
fail_if_error $? "Error: Azure cli installation failed"

if ! type -p ansible;  then
   # install Ansible
    curl --retry 10 --max-time 60 --fail --silent --show-error "https://bootstrap.pypa.io/get-pip.py" -o "get-pip.py"
    sudo python get-pip.py
    pip install 'ansible==2.8.3'
    fail_if_error $? "Error: Ansible client installation is failed"
fi

#Stop & Disable the firewalld(Iptables)
systemctl stop firewalld
systemctl disable firewalld

#Variable Declaration
azure_storage_account=`facter azure_storage_account`
azure_storage_files_password=`facter azure_storage_files_password`
azure_storage_files_share=`facter azure_storage_files_share`
DIRECTORY_NFS_SHARE="sasdepot"
app_name=`facter app_name`
domain_name=`facter domain_name`
ansible_vmname=`facter ansible_vmname`
microservices_vmname=`facter microservices_vmname`
cascontroller_vmname=`facter cascontroller_vmname`
spre_vmname=`facter spre_vmname`
machine_name=`curl -H Metadata:true "http://169.254.169.254/metadata/instance/compute/name?api-version=2017-08-01&format=text"`
current_host=${app_name}${machine_name}
sas_home="/opt/sas"
backupdir="/backup"
sasdatadir="/sasdata"

#RhelRequired packages
yum -y install java-1.8.0-openjdk yum-utils firefox xclock x11* xauth git python compat-glibc libpng12 lsof at numactl glibc libpng ntp apr ksh wget mlocate libXext.x86_64 libXp.x86_64 libXtst.x86_64 xorg-x11-xauth.x86_64 gcc libSM.i686 libXrender.i686 zlib.i686 nfs-utils cifs-utils telnet
fail_if_error $? "Error: PreRequisites installation failed"

##SSHD Configuration
if [ -f /etc/ssh/sshd_config ]
    then
        PA="PasswordAuthentication yes "
        PRT="PermitRootLogin yes"
        x=`grep -i PermitRootLogin /etc/ssh/sshd_config`
        a=`echo $?`
    if [ "$a" == "0" ]
        then
            sed -i '/PermitRootLogin/c\'"${PRT}"'' /etc/ssh/sshd_config
    fi
    x=`grep -i PasswordAuthentication /etc/ssh/sshd_config`
    a=`echo $?`
    if [ "$a" == "0" ]
        then
            sed -i.bak s/PasswordAuthentication' 'no/PasswordAuthentication' 'yes/g /etc/ssh/sshd_config
    fi
fi

#Modifying SSHD Config Setting
sed -i '/ClientAliveInterval/c\ClientAliveInterval 3600' /etc/ssh/sshd_config
sed -i 's/#MaxStartups 10:30:100/MaxStartups 100/g' /etc/ssh/sshd_config

systemctl restart sshd
echo "SSHD Configuration updated successfully."

#System settings for ulimits
if [ -f /etc/security/limits.conf ]
then
	cat /etc/security/limits.conf| grep -w 500000
	a=`echo $?`
	echo $a
	if [ "$a" != "0" ]
	then
		echo $a
		sed -i '$d' /etc/security/limits.conf
		echo "*               hard    nofile  500000" >> /etc/security/limits.conf
		echo "*               soft    nofile  500000" >> /etc/security/limits.conf
		echo "*               soft    nproc   650000" >> /etc/security/limits.conf
		echo "*               hard    nproc   500000" >> /etc/security/limits.conf
		echo "*               hard    stack   10240" >> /etc/security/limits.conf
		echo "*               soft    stack   10240" >> /etc/security/limits.conf
		echo "*               soft    stack   10240" >> /etc/security/limits.conf

		echo "# End of file" >> /etc/security/limits.conf
	fi
fi
if [ -f /etc/security/limits.d/20-nproc.conf ]
then
	sed -i 's/4096/unlimited/g' /etc/security/limits.d/20-nproc.conf
fi

#Static Hostname Setup for Server
echo "setting up the new hostname on the server"
echo $current_host
hostnamectl set-hostname --static ${current_host}.${domain_name}
if [ $? -eq 0 ]; then
    echo "hostname update successful"
    if [ -f /etc/hostname ]; then
        chattr -i /etc/hostname
        rm -f /etc/hostname
        echo ${current_host}.${domain_name} > /etc/hostname
        chattr +i /etc/hostname
    fi
    if [ -f /etc/sysconfig/network ]; then
        echo "HOSTNAME=${current_host}.${domain_name}" >> /etc/sysconfig/network
    fi
    echo "Restart Network Service"
    /etc/init.d/network restart
else
    echo "Hostname Update failed"
fi

###Configure SELINUX
setenforce 0
sed -i.bak -e 's/SELINUX=enforcing/SELINUX=permissive/g' /etc/selinux/config
echo "SELINUX set to permissive."

##Create Mount Points
if [ ! -d "$sas_home" ]; then
    sudo mkdir -p $sas_home
fi

##Create Mount Points
if [ ! -d "$backupdir" ]; then
    sudo mkdir -p $backupdir
fi

##Create Mount Points
if [ ! -d "$sasdatadir" ]; then
    sudo mkdir -p $sasdatadir
fi

##Volume Mount for opt-sas
lsblk /dev/disk/azure/scsi1/lun0
if [ $? -eq 0 ]; then
    df -h | grep $sas_home
	if [ $? -eq 0 ]; then
		echo "Disk for $sas_home already mounted."
    else
        mkfs.xfs /dev/disk/azure/scsi1/lun0
		mount /dev/disk/azure/scsi1/lun0 $sas_home
		fail_if_error $? "Error:Failed to mount $sas_home"
		## Adding Fstab Entries
		echo "/dev/disk/azure/scsi1/lun0   $sas_home   xfs       defaults        0 0"  >> /etc/fstab
        echo "Disk for $sas_home located and mounted."
    fi
else
    echo "ERROR: $sas_home disk(lun0) disk failed to mount or disk not available."
    #exit 1
fi

##Volume Mount for sasbackup
lsblk /dev/disk/azure/scsi1/lun1
    if [ $? -eq 0 ]; then
        df -h | grep $backup
        if [ $? -eq 0 ]
	    then
                echo "Disk for "$backupdir" already mounted"
        else
            mkfs.xfs /dev/disk/azure/scsi1/lun1
            mount /dev/disk/azure/scsi1/lun1 $backupdir
            fail_if_error $? "Error:Failed to mount $backupdir"
            ## Adding Fstab Entries
            echo "/dev/disk/azure/scsi1/lun1     $backupdir         xfs       defaults        0 0"  >> /etc/fstab
            echo "Disk for $backupdir located and mounted."
        fi
    else
        echo "ERROR: $backupdir disk(lun1) disk failed to mount or disk not available"
        #exit 1
    fi

##Volume Mount for sasdata
if [ $machine_name == $cascontroller_vmname ]; then
    lsblk /dev/disk/azure/scsi1/lun2
    if [ $? -eq 0 ]; then
        df -h | grep $backup
        if [ $? -eq 0 ]
	    then
                echo "Disk for "$sasdatadir" already mounted"
        else
            mkfs.xfs /dev/disk/azure/scsi1/lun2
            mount /dev/disk/azure/scsi1/lun2 $sasdatadir
            fail_if_error $? "Error:Failed to mount $sasdatadir"
            ## Adding Fstab Entries
            echo "/dev/disk/azure/scsi1/lun2    "$sasdatadir"           xfs       defaults        0 0"  >> /etc/fstab
            echo "Disk for $sasdatadir located and mounted."
        fi
    else
        echo "ERROR: "$sasdatadir" disk(lun2) disk failed to mount or disk not available "
        #exit 1
    fi
fi

#Mounting Azure File Share for SAS Viya Play book
stgacc_secr_name=`facter stgacc_secr_name`
key_vault_name=`facter kv_vault_name`
az login --identity
fail_if_error $? "Error: Az login Failed"
azure_storage_files_password=`az keyvault secret show -n $stgacc_secr_name --vault-name $key_vault_name | grep value | cut -d '"' -f4`
echo "setup cifs"
cifs_server_fqdn=`facter cifs_server_fqdn`

if [ ! -d "/etc/smbcredentials" ]; then
    sudo mkdir /etc/smbcredentials
fi
chmod 700 /etc/smbcredentials
if [ ! -f "/etc/smbcredentials/"${azure_storage_account}".cred" ]; then
    echo "username=${azure_storage_account}" >> /etc/smbcredentials/${azure_storage_account}.cred
    echo "password=${azure_storage_files_password}" >> /etc/smbcredentials/${azure_storage_account}.cred
fi
chmod 600 "/etc/smbcredentials/${azure_storage_account}.cred"

mkdir -p "/${DIRECTORY_NFS_SHARE}"
mount -t cifs //${cifs_server_fqdn}/${azure_storage_files_share} /${DIRECTORY_NFS_SHARE}  -o vers=3.0,credentials=/etc/smbcredentials/${azure_storage_account}.cred,dir_mode=0777,file_mode=0777,serverino
fail_if_error $? "Error: SAS Depot Mount Failed"
#echo "//${cifs_server_fqdn}/${azure_storage_files_share} /${DIRECTORY_NFS_SHARE}  cifs defaults,vers=3.0,credentials=/etc/smbcredentials/${azure_storage_account}.cred,dir_mode=0777,file_mode=0777,sec=ntlmssp 0 0" >> /etc/fstab
#mount -a

echo "*** Phase 1 - Pre-Reqs Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***"


#!/bin/bash

sudo apt-get -y update
sudo apt-get install -y python3 python-dev python3-dev build-essential libssl-dev libffi-dev libxml2-dev libxslt-dev python3-pip

sudo pip3 install scrapy


mysqlpassword=$1
mySqlUser=$2
mySqlPasswordForUser=$3

apt-get -y update
apt-get -y install apache2 openjdk-7-jdk tomcat7

#install mysql
echo mysql-server mysql-server/root_password password $mysqlpassword | sudo debconf-set-selections
echo mysql-server mysql-server/root_password_again password $mysqlpassword | sudo debconf-set-selections

apt-get purge mysql-server mysql-client mysql-common mysql-server-core-* mysql-client-core-*
rm -rf /etc/mysql /var/lib/mysql
apt-get autoremove
apt-get autoclean
apt-get -y install mysql-client mysql-server
apt-get	install libmysql-java

# Allow remote connection
sed -i "s/bind-address.*/bind-address = 0.0.0.0/" /etc/mysql/my.cnf

#create database
mysql -u root -p$mysqlpassword -e "create database idp_db";

#create table
mysql -u root -p$mysqlpassword -e "use idp_db; create table StorageRecords(context varchar(255) NOT NULL,id varchar(255) NOT NULL,expires bigint(20) DEFAULT NULL,value longtext NOT NULL,version bigint(20) NOT NULL,PRIMARY KEY(context,id))";

#create user & grant all privileges
mysql -u root -p$mysqlpassword -e "create user $mySqlUser@'localhost' identified by '$mySqlPasswordForUser'";
mysql -u root -p$mysqlpassword -e "grant all privileges on *.* to $mySqlUser@'localhost'";

mysql -u root -p$mysqlpassword -e "create user $mySqlUser@'%' identified by '$mySqlPasswordForUser'";
mysql -u root -p$mysqlpassword -e "grant all privileges on *.* to $mySqlUser@'%'";

#restart mysql
service mysql restart