#!/bin/bash

function print_usage() {
  cat <<EOF
Command
  $0
Arguments
  --jenkins_url|-j                [Required]: Jenkins URL
  --jenkins_username|-ju          [Required]: Jenkins user name
  --jenkins_password|-jp                    : Jenkins password. If not specified and the user name is "admin", the initialAdminPassword will be used
  --git_url|-g                    [Required]: Git URL with a Dockerfile in it's root
  --registry|-r                   [Required]: Registry url targeted by the pipeline
  --registry_user_name|-ru        [Required]: Registry user name
  --registry_password|-rp         [Required]: Registry password
  --repository|-rr                          : Repository targeted by the pipeline
  --aks_resource_group_name|-agn  [Required]: Name of the resource group which contains the AKS
  --aks_cluster_name|-acn         [Required]: Name of the AKS cluster
  --mongodb_uri|-mu               [Required]: URI of the MongoDB
  --credentials_id|-ci                      : Desired Jenkins credentials id
  --credentials_desc|-cd                    : Desired Jenkins credentials description
  --job_short_name|-jsn                     : Desired Jenkins job short name
  --job_display_name|-jdn                   : Desired Jenkins job display name
  --job_description|-jd                     : Desired Jenkins job description
  --scm_poll_schedule|-sps                  : cron style schedule for SCM polling
  --scm_poll_ignore_commit_hooks|spi        : Ignore changes notified by SCM post-commit hooks. (Will be ignore if the poll schedule is not defined)
  --artifacts_location|-al                  : Url used to reference other scripts/artifacts.
  --sas_token|-st                           : A sas token needed if the artifacts location is private.
EOF
}

function throw_if_empty() {
  local name="$1"
  local value="$2"
  if [ -z "$value" ]; then
    echo "Parameter '$name' cannot be empty." 1>&2
    print_usage
    exit -1
  fi
}

function run_util_script() {
  local script_path="$1"
  shift
  curl --silent "${artifacts_location}${script_path}${artifacts_location_sas_token}" | sudo bash -s -- "$@"
  local return_value=$?
  if [ $return_value -ne 0 ]; then
    >&2 echo "Failed while executing script '$script_path'."
    exit $return_value
  fi
}

#set defaults
credentials_id="docker_credentials"
credentials_desc="Docker Container Registry Credentials"
job_short_name="basic-docker-build"
job_display_name="Basic Docker Build"
job_description="A basic pipeline that builds a Docker container. The job expects a Dockerfile at the root of the git repository"
repository="${USER}/myfirstapp"
scm_poll_schedule=""
scm_poll_ignore_commit_hooks="0"

while [[ $# > 0 ]]
do
  key="$1"
  shift
  case $key in
    --jenkins_url|-j)
      jenkins_url="$1"
      shift
      ;;
    --jenkins_username|-ju)
      jenkins_username="$1"
      shift
      ;;
    --jenkins_password|-jp)
      jenkins_password="$1"
      shift
      ;;
    --git_url|-g)
      git_url="$1"
      shift
      ;;
    --registry|-r)
      registry="$1"
      shift
      ;;
    --registry_user_name|-ru)
      registry_user_name="$1"
      shift
      ;;
    --registry_password|-rp)
      registry_password="$1"
      shift
      ;;
    --repository|-rr)
      repository="$1"
      shift
      ;;
    --aks_resource_group_name|-agn)
      aks_resource_group_name="$1"
      shift
      ;;
    --aks_cluster_name|-acn)
      aks_cluster_name="$1"
      shift
      ;;
    --mongodb_uri|-mu)
      mongodb_uri="$1"
      shift
      ;;
    --credentials_id|-ci)
      credentials_id="$1"
      shift
      ;;
    --credentials_desc|-cd)
      credentials_desc="$1"
      shift
      ;;
    --job_short_name|-jsn)
      job_short_name="$1"
      shift
      ;;
    --job_display_name|-jdn)
      job_display_name="$1"
      shift
      ;;
    --job_description|-jd)
      job_description="$1"
      shift
      ;;
   --scm_poll_schedule|-sps)
      scm_poll_schedule="$1"
      shift
      ;;
  --scm_poll_ignore_commit_hooks|-spi)
      scm_poll_ignore_commit_hooks="$1"
      shift
      ;;
    --artifacts_location|-al)
      artifacts_location="$1"
      shift
      ;;
    --sas_token|-st)
      artifacts_location_sas_token="$1"
      shift
      ;;
    --help|-help|-h)
      print_usage
      exit 13
      ;;
    *)
      echo "ERROR: Unknown argument '$key' to script '$0'" 1>&2
      exit -1
  esac
done

throw_if_empty --jenkins_url $jenkins_url
throw_if_empty --jenkins_username $jenkins_username
if [ "$jenkins_username" != "admin" ]; then
  throw_if_empty --jenkins_password $jenkins_password
fi
throw_if_empty --git_url $git_url
throw_if_empty --registry $registry
throw_if_empty --registry_user_name $registry_user_name
throw_if_empty --registry_password $registry_password
throw_if_empty --aks_resource_group_name $aks_resource_group_name
throw_if_empty --aks_cluster_name $aks_cluster_name
throw_if_empty --mongodb_uri $mongodb_uri

#download dependencies
job_xml=$(curl -s ${artifacts_location}scripts/jenkins/basic-docker-build-job.xml${artifacts_location_sas_token})
credentials_xml=$(curl -s ${artifacts_location}scripts/jenkins/basic-user-pwd-credentials.xml${artifacts_location_sas_token})

#escape xml reserved characters
escapsed_credentials_id=$(xmlstarlet esc "$credentials_id")
escapsed_credentials_desc=$(xmlstarlet esc "$credentials_desc")
escapsed_registry_user_name=$(xmlstarlet esc "$registry_user_name")
escapsed_registry_password=$(xmlstarlet esc "$registry_password")

#prepare credentials.xml
credentials_xml=${credentials_xml//'{insert-credentials-id}'/${escapsed_credentials_id}}
credentials_xml=${credentials_xml//'{insert-credentials-description}'/${escapsed_credentials_desc}}
credentials_xml=${credentials_xml//'{insert-user-name}'/${escapsed_registry_user_name}}
credentials_xml=${credentials_xml//'{insert-user-password}'/${escapsed_registry_password}}

#escape xml reserved characters
escapsed_job_display_name=$(xmlstarlet esc "$job_display_name")
escapsed_job_description=$(xmlstarlet esc "$job_description")
escapsed_git_url=$(xmlstarlet esc "$git_url")
escapsed_registry=$(xmlstarlet esc "$registry")
escapsed_aks_resource_group_name=$(xmlstarlet esc "$aks_resource_group_name")
escapsed_aks_cluster_name=$(xmlstarlet esc "$aks_cluster_name")
escapsed_credentials_id=$(xmlstarlet esc "$credentials_id")
escapsed_repository=$(xmlstarlet esc "$repository")
escapsed_mongodb_uri=$(xmlstarlet esc "$mongodb_uri")

#prepare job.xml
job_xml=${job_xml//'{insert-job-display-name}'/${escapsed_job_display_name}}
job_xml=${job_xml//'{insert-job-description}'/${escapsed_job_description}}
job_xml=${job_xml//'{insert-git-url}'/${escapsed_git_url}}
job_xml=${job_xml//'{insert-registry}'/${escapsed_registry}}
job_xml=${job_xml//'{insert-aks-resource-group-name}'/${escapsed_aks_resource_group_name}}
job_xml=${job_xml//'{insert-aks-cluster-name}'/${escapsed_aks_cluster_name}}
job_xml=${job_xml//'{insert-docker-credentials}'/${escapsed_credentials_id}}
job_xml=${job_xml//'{insert-container-repository}'/${escapsed_repository}}
job_xml=${job_xml//'{insert-mongodb-uri}'/${escapsed_mongodb_uri}}

if [ -n "${scm_poll_schedule}" ]
then
  scm_poll_ignore_commit_hooks_bool="false"
  if [[ "${scm_poll_ignore_commit_hooks}" == "1" ]]
  then
    scm_poll_ignore_commit_hooks_bool="true"
  fi
  triggers_xml_node=$(cat <<EOF
<triggers>
  <hudson.triggers.SCMTrigger>
  <spec>${scm_poll_schedule}</spec>
  <ignorePostCommitHooks>${scm_poll_ignore_commit_hooks_bool}</ignorePostCommitHooks>
  </hudson.triggers.SCMTrigger>
</triggers>
EOF
)
  job_xml=${job_xml//'<triggers/>'/${triggers_xml_node}}
fi

job_xml=${job_xml//'{insert-groovy-script}'/"$(curl -s ${artifacts_location}scripts/jenkins/basic-docker-build.groovy${artifacts_location_sas_token})"}
echo "${job_xml}" > job.xml

#install the required plugins
run_util_script "scripts/jenkins/run-cli-command.sh" -j "$jenkins_url" -ju "$jenkins_username" -jp "$jenkins_password" -c "install-plugin credentials -deploy"
plugins=(docker-workflow git)
for plugin in "${plugins[@]}"; do
  run_util_script "scripts/jenkins/run-cli-command.sh" -j "$jenkins_url" -ju "$jenkins_username" -jp "$jenkins_password" -c "install-plugin $plugin -restart"
done

#wait for instance to be back online
run_util_script "scripts/jenkins/run-cli-command.sh" -j "$jenkins_url" -ju "$jenkins_username" -jp "$jenkins_password" -c "version"

echo "${credentials_xml}" > credentials.xml

#add user/pwd
run_util_script "scripts/jenkins/run-cli-command.sh" -j "$jenkins_url" -ju "$jenkins_username" -jp "$jenkins_password" -c 'create-credentials-by-xml SystemCredentialsProvider::SystemContextResolver::jenkins (global)' -cif "credentials.xml"

#add job
run_util_script "scripts/jenkins/run-cli-command.sh" -j "$jenkins_url" -ju "$jenkins_username" -jp "$jenkins_password" -c "create-job ${job_short_name}" -cif "job.xml"

#cleanup
rm credentials.xml
rm job.xml
rm jenkins-cli.jar


#!/bin/bash
echo $@
function print_usage() {
  cat <<EOF
Installs Jenkins and exposes it to the public through port 80 (login and cli are disabled)
Command
  $0
Arguments
  --jenkins_fqdn|-jf       [Required] : Jenkins FQDN
  --cluster_name|-cn       [Required] : Jenkins cluster name
  --cluster_version|-cv    [Required] : Jenkins cluster version
  --vm_private_ip|-pi                 : The VM private ip used to configure Jenkins URL. If missing, jenkins_fqdn will be used instead
  --jenkins_release_type|-jrt         : The Jenkins release type (LTS or weekly or verified). By default it's set to LTS
  --jenkins_version_location|-jvl     : Url used to specify the version of Jenkins.
  --service_principal_type|-sp        : The type of service principal: MSI or manual.
  --service_principal_id|-spid        : The service principal ID.
  --service_principal_secret|-ss      : The service principal secret.
  --subscription_id|-subid            : The subscription ID of the SP.
  --tenant_id|-tid                    : The tenant id of the SP.
  --artifacts_location|-al            : Url used to reference other scripts/artifacts.
  --sas_token|-st                     : A sas token needed if the artifacts location is private.
  --cloud_agents|-ca                  : The type of the cloud agents: aci, vm or no.
  --resource_group|-rg                : the resource group name.
  --location|-lo                      : the resource group location.
EOF
}

function throw_if_empty() {
  local name="$1"
  local value="$2"
  if [ -z "$value" ]; then
    echo "Parameter '$name' cannot be empty." 1>&2
    print_usage
    exit -1
  fi
}

function run_util_script() {
  local script_path="$1"
  shift
  curl --silent "${artifacts_location}${script_path}${artifacts_location_sas_token}" | sudo bash -s -- "$@"
  local return_value=$?
  if [ $return_value -ne 0 ]; then
    >&2 echo "Failed while executing script '$script_path'."
    exit $return_value
  fi
}

function retry_until_successful {
  counter=0
  "${@}"
  while [ $? -ne 0 ]; do
    if [[ "$counter" -gt 20 ]]; then
        exit 1
    else
        let counter++
    fi
    sleep 5
    "${@}"
  done;
}

#defaults
jenkins_version_location="${artifacts_location}scripts/jenkins/jenkins-verified-ver${artifacts_location_sas_token}"
azure_web_page_location="/usr/share/nginx/azure"
jenkins_release_type="LTS"

while [[ $# > 0 ]]
do
  key="$1"
  shift
  case $key in
    --jenkins_fqdn|-jf)
      jenkins_fqdn="$1"
      shift
      ;;
    --cluster_name|-cn)
      cluster_name="$1"
      shift
      ;;
    --cluster_version|-cv)
      cluster_version="$1"
      shift
      ;;
    --vm_private_ip|-pi)
      vm_private_ip="$1"
      shift
      ;;
    --jenkins_release_type|-jrt)
      jenkins_release_type="$1"
      shift
      ;;
    --jenkins_version_location|-jvl)
      jenkins_version_location="$1"
      shift
      ;;
    --service_principal_type|-sp)
      service_principal_type="$1"
      shift
      ;;
    --service_principal_id|-spid)
      service_principal_id="$1"
      shift
      ;;
    --service_principal_secret|-ss)
      service_principal_secret="$1"
      shift
      ;;
    --subscription_id|-subid)
      subscription_id="$1"
      shift
      ;;
    --tenant_id|-tid)
      tenant_id="$1"
      shift
      ;;
    --artifacts_location|-al)
      artifacts_location="$1"
      shift
      ;;
    --sas_token|-st)
      artifacts_location_sas_token="$1"
      shift
      ;;
    --cloud_agents|-ca)
      cloud_agents="$1"
      shift
      ;;
    --resource_group|-rg)
      resource_group="$1"
      shift
      ;;
    --location|-lo)
      location="$1"
      shift
      ;;
    --help|-help|-h)
      print_usage
      exit 13
      ;;
    *)
      echo "ERROR: Unknown argument '$key' to script '$0'" 1>&2
      exit -1
  esac
done

throw_if_empty --jenkins_fqdn $jenkins_fqdn
throw_if_empty --jenkins_release_type $jenkins_release_type
if [[ "$jenkins_release_type" != "LTS" ]] && [[ "$jenkins_release_type" != "weekly" ]] && [[ "$jenkins_release_type" != "verified" ]]; then
  echo "Parameter jenkins_release_type can only be 'LTS' or 'weekly' or 'verified'! Current value is '$jenkins_release_type'"
  exit 1
fi

if [ -z "$vm_private_ip" ]; then
    #use port 80 for public fqdn
    jenkins_url="http://${jenkins_fqdn}/"
else
    #use port 8080 for internal
    jenkins_url="http://${vm_private_ip}:8080/"
fi

jenkins_auth_matrix_conf=$(cat <<EOF
<authorizationStrategy class="hudson.security.ProjectMatrixAuthorizationStrategy">
    <permission>com.cloudbees.plugins.credentials.CredentialsProvider.Create:authenticated</permission>
    <permission>com.cloudbees.plugins.credentials.CredentialsProvider.Delete:authenticated</permission>
    <permission>com.cloudbees.plugins.credentials.CredentialsProvider.ManageDomains:authenticated</permission>
    <permission>com.cloudbees.plugins.credentials.CredentialsProvider.Update:authenticated</permission>
    <permission>com.cloudbees.plugins.credentials.CredentialsProvider.View:authenticated</permission>
    <permission>hudson.model.Computer.Build:authenticated</permission>
    <permission>hudson.model.Computer.Configure:authenticated</permission>
    <permission>hudson.model.Computer.Connect:authenticated</permission>
    <permission>hudson.model.Computer.Create:authenticated</permission>
    <permission>hudson.model.Computer.Delete:authenticated</permission>
    <permission>hudson.model.Computer.Disconnect:authenticated</permission>
    <permission>hudson.model.Hudson.Administer:authenticated</permission>
    <permission>hudson.model.Hudson.ConfigureUpdateCenter:authenticated</permission>
    <permission>hudson.model.Hudson.Read:authenticated</permission>
    <permission>hudson.model.Hudson.RunScripts:authenticated</permission>
    <permission>hudson.model.Hudson.UploadPlugins:authenticated</permission>
    <permission>hudson.model.Item.Build:authenticated</permission>
    <permission>hudson.model.Item.Cancel:authenticated</permission>
    <permission>hudson.model.Item.Configure:authenticated</permission>
    <permission>hudson.model.Item.Create:authenticated</permission>
    <permission>hudson.model.Item.Delete:authenticated</permission>
    <permission>hudson.model.Item.Discover:authenticated</permission>
    <permission>hudson.model.Item.Move:authenticated</permission>
    <permission>hudson.model.Item.Read:authenticated</permission>
    <permission>hudson.model.Item.Workspace:authenticated</permission>
    <permission>hudson.model.Run.Delete:authenticated</permission>
    <permission>hudson.model.Run.Replay:authenticated</permission>
    <permission>hudson.model.Run.Update:authenticated</permission>
    <permission>hudson.model.View.Configure:authenticated</permission>
    <permission>hudson.model.View.Create:authenticated</permission>
    <permission>hudson.model.View.Delete:authenticated</permission>
    <permission>hudson.model.View.Read:authenticated</permission>
    <permission>hudson.scm.SCM.Tag:authenticated</permission>
    <permission>hudson.model.Hudson.Read:anonymous</permission>
    <permission>hudson.model.Item.Discover:anonymous</permission>
    <permission>hudson.model.Item.Read:anonymous</permission>
</authorizationStrategy>
EOF
)

jenkins_location_conf=$(cat <<EOF
<?xml version='1.0' encoding='UTF-8'?>
<jenkins.model.JenkinsLocationConfiguration>
    <adminAddress>address not configured yet <nobody@nowhere></adminAddress>
    <jenkinsUrl>${jenkins_url}</jenkinsUrl>
</jenkins.model.JenkinsLocationConfiguration>
EOF
)

jenkins_disable_reverse_proxy_warning=$(cat <<EOF
<disabledAdministrativeMonitors>
    <string>hudson.diagnosis.ReverseProxySetupMonitor</string>
</disabledAdministrativeMonitors>
EOF
)

jenkins_agent_port="<slaveAgentPort>5378</slaveAgentPort>"

nginx_reverse_proxy_conf=$(cat <<EOF
server {
    listen 80;
    server_name ${jenkins_fqdn};
    error_page 403 /jenkins-on-azure;
    location / {
        proxy_set_header        Host \$host:\$server_port;
        proxy_set_header        X-Real-IP \$remote_addr;
        proxy_set_header        X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto \$scheme;

        # Fix the "It appears that your reverse proxy set up is broken" error.
        proxy_pass          http://localhost:8080;
        proxy_redirect      http://localhost:8080 http://${jenkins_fqdn};
        proxy_read_timeout  90;
    }
    location /cli {
        rewrite ^ /jenkins-on-azure permanent;
    }

    location ~ /login* {
        rewrite ^ /jenkins-on-azure permanent;
    }
    location /jenkins-on-azure {
      alias ${azure_web_page_location};
    }
}
EOF
)

#update apt repositories
wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -

if [ "$jenkins_release_type" == "weekly" ]; then
  sudo sh -c 'echo deb http://pkg.jenkins.io/debian binary/ > /etc/apt/sources.list.d/jenkins.list'
else
  sudo sh -c 'echo deb http://pkg.jenkins.io/debian-stable binary/ > /etc/apt/sources.list.d/jenkins.list'
fi

sudo add-apt-repository ppa:openjdk-r/ppa --yes

echo "deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/azure-cli/ wheezy main" | sudo tee /etc/apt/sources.list.d/azure-cli.list
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 417A0893
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EB3E94ADBE1229CF
sudo apt-get install apt-transport-https
sudo apt-get update --yes

#install openjdk8
sudo apt-get install openjdk-8-jre openjdk-8-jre-headless openjdk-8-jdk --yes

#install jenkins
if [[ ${jenkins_release_type} == 'verified' ]]; then
  jenkins_version=$(curl --silent "${jenkins_version_location}")
  deb_file=jenkins_${jenkins_version}_all.deb
  wget -q "https://pkg.jenkins.io/debian-stable/binary/${deb_file}"
  if [[ -f ${deb_file} ]]; then
    sudo dpkg -i ${deb_file}
    sudo apt-get install -f --yes
  else
    echo "Failed to download ${deb_file}. The initialization is terminated!"
    exit -1
  fi
else
  sudo apt-get install jenkins --yes
  sudo apt-get install jenkins --yes # sometime the first apt-get install jenkins command fails, so we try it twice
fi

retry_until_successful sudo test -f /var/lib/jenkins/secrets/initialAdminPassword
retry_until_successful run_util_script "scripts/jenkins/run-cli-command.sh" -c "version"

#We need to install workflow-aggregator so all the options in the auth matrix are valid
plugins=(azure-vm-agents windows-azure-storage matrix-auth workflow-aggregator azure-app-service azure-acs azure-container-agents)
for plugin in "${plugins[@]}"; do
  run_util_script "scripts/jenkins/run-cli-command.sh" -c "install-plugin $plugin -deploy"
done

#allow anonymous read access
inter_jenkins_config=$(sed -zr -e"s|<authorizationStrategy.*</authorizationStrategy>|{auth-strategy-token}|" /var/lib/jenkins/config.xml)
final_jenkins_config=${inter_jenkins_config//'{auth-strategy-token}'/${jenkins_auth_matrix_conf}}
echo "${final_jenkins_config}" | sudo tee /var/lib/jenkins/config.xml > /dev/null

#set up Jenkins URL to private_ip:8080 so JNLP connections can be established
echo "${jenkins_location_conf}" | sudo tee /var/lib/jenkins/jenkins.model.JenkinsLocationConfiguration.xml > /dev/null

#disable 'It appears that your reverse proxy set up is broken' warning.
# This is visible when connecting through SSH tunneling
inter_jenkins_config=$(sed -zr -e"s|<disabledAdministrativeMonitors/>|{disable-reverse-proxy-token}|" /var/lib/jenkins/config.xml)
final_jenkins_config=${inter_jenkins_config//'{disable-reverse-proxy-token}'/${jenkins_disable_reverse_proxy_warning}}
echo "${final_jenkins_config}" | sudo tee /var/lib/jenkins/config.xml > /dev/null

#Open a fixed port for JNLP
inter_jenkins_config=$(sed -zr -e"s|<slaveAgentPort.*</slaveAgentPort>|{slave-agent-port}|" /var/lib/jenkins/config.xml)
final_jenkins_config=${inter_jenkins_config//'{slave-agent-port}'/${jenkins_agent_port}}
echo "${final_jenkins_config}" | sudo tee /var/lib/jenkins/config.xml > /dev/null

#restart jenkins
sudo service jenkins restart

#install the service principal
msi_cred=$(cat <<EOF
<com.microsoft.azure.util.AzureMsiCredentials>
  <scope>GLOBAL</scope>
  <id>azure_service_principal</id>
  <description>Local MSI</description>
  <msiPort>50342</msiPort>
</com.microsoft.azure.util.AzureMsiCredentials>
EOF
)
sp_cred=$(cat <<EOF
<com.microsoft.azure.util.AzureCredentials>
  <scope>GLOBAL</scope>
  <id>azure_service_principal</id>
  <description>Manual Service Principal</description>
  <data>
    <subscriptionId>${subscription_id}</subscriptionId>
    <clientId>${service_principal_id}</clientId>
    <clientSecret>${service_principal_secret}</clientSecret>
    <oauth2TokenEndpoint>https://login.windows.net/${tenant_id}</oauth2TokenEndpoint>
    <serviceManagementURL>https://management.core.windows.net/</serviceManagementURL>
    <tenant>${tenant_id}</tenant>
    <authenticationEndpoint>https://login.microsoftonline.com/</authenticationEndpoint>
    <resourceManagerEndpoint>https://management.azure.com/</resourceManagerEndpoint>
    <graphEndpoint>https://graph.windows.net/</graphEndpoint>
  </data>
</com.microsoft.azure.util.AzureCredentials>
EOF
)

retry_until_successful run_util_script "scripts/jenkins/run-cli-command.sh" -c "version"

if [ "${service_principal_type}" == 'msi' ]; then
  echo "${msi_cred}" > msi_cred.xml
  run_util_script "scripts/jenkins/run-cli-command.sh" -c "create-credentials-by-xml system::system::jenkins _" -cif msi_cred.xml
  rm msi_cred.xml
else
  echo "${sp_cred}" > sp_cred.xml
  run_util_script "scripts/jenkins/run-cli-command.sh" -c "create-credentials-by-xml system::system::jenkins _" -cif sp_cred.xml
  rm sp_cred.xml
fi

#add cloud agents
vm_agent_conf=conf=$(cat <<EOF
<clouds>
  <com.microsoft.azure.vmagent.AzureVMCloud>
    <name>AzureVMAgents</name>
    <cloudName>AzureVMAgents</cloudName>
    <credentialsId>azure_service_principal</credentialsId>
    <maxVirtualMachinesLimit>10</maxVirtualMachinesLimit>
    <resourceGroupReferenceType>existing</resourceGroupReferenceType>
    <existingResourceGroupName>${resource_group}</existingResourceGroupName>
    <vmTemplates>
      <com.microsoft.azure.vmagent.AzureVMAgentTemplate>
        <templateName>win-agent</templateName>
        <labels>win</labels>
        <location>${location}</location>
        <virtualMachineSize>Standard_D1_v2</virtualMachineSize>
        <storageAccountNameReferenceType>new</storageAccountNameReferenceType>
        <diskType>managed</diskType>
        <storageAccountType>Standard_LRS</storageAccountType>
        <noOfParallelJobs>1</noOfParallelJobs>
        <usageMode>NORMAL</usageMode>
        <shutdownOnIdle>false</shutdownOnIdle>
        <imageTopLevelType>basic</imageTopLevelType>
        <builtInImage>Windows Server 2016</builtInImage>
        <credentialsId>agent_admin_account</credentialsId>
        <retentionTimeInMin>60</retentionTimeInMin>
      </com.microsoft.azure.vmagent.AzureVMAgentTemplate>
      <com.microsoft.azure.vmagent.AzureVMAgentTemplate>
        <templateName>linux-agent</templateName>
        <labels>linux</labels>
        <location>${location}</location>
        <virtualMachineSize>Standard_D1_v2</virtualMachineSize>
        <storageAccountNameReferenceType>new</storageAccountNameReferenceType>
        <diskType>managed</diskType>
        <storageAccountType>Standard_LRS</storageAccountType>
        <noOfParallelJobs>1</noOfParallelJobs>
        <usageMode>NORMAL</usageMode>
        <shutdownOnIdle>false</shutdownOnIdle>
        <imageTopLevelType>basic</imageTopLevelType>
        <builtInImage>Ubuntu 16.04 LTS</builtInImage>
        <credentialsId>agent_admin_account</credentialsId>
        <retentionTimeInMin>60</retentionTimeInMin>
      </com.microsoft.azure.vmagent.AzureVMAgentTemplate>
    </vmTemplates>
    <deploymentTimeout>1200</deploymentTimeout>
    <approximateVirtualMachineCount>0</approximateVirtualMachineCount>
  </com.microsoft.azure.vmagent.AzureVMCloud>
</clouds>
EOF
)

aci_agent_conf=$(cat <<EOF
<clouds>
  <com.microsoft.jenkins.containeragents.aci.AciCloud>
    <name>AciAgents</name>
    <credentialsId>azure_service_principal</credentialsId>
    <resourceGroup>${resource_group}</resourceGroup>
    <templates>
      <com.microsoft.jenkins.containeragents.aci.AciContainerTemplate>
        <name>aciagents</name>
        <image>jenkinsci/jnlp-slave</image>
        <osType>Linux</osType>
        <command>jenkins-slave -url \${rootUrl} \${secret} \${nodeName}</command>
        <rootFs>/home/jenkins</rootFs>
        <timeout>10</timeout>
        <cpu>1</cpu>
        <memory>1.5</memory>
        <retentionStrategy class="com.microsoft.jenkins.containeragents.strategy.ContainerOnceRetentionStrategy" />
      </com.microsoft.jenkins.containeragents.aci.AciContainerTemplate>
    </templates>
  </com.microsoft.jenkins.containeragents.aci.AciCloud>
</clouds>
EOF
)

agent_admin_password=$(head /dev/urandom | tr -dc A-Z | head -c 4)$(head /dev/urandom | tr -dc a-z | head -c 4)$(head /dev/urandom | tr -dc 0-9 | head -c 4)'!@'
agent_admin_cred=$(cat <<EOF
<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
  <scope>GLOBAL</scope>
  <id>agent_admin_account</id>
  <description>the admin account for the vm agents</description>
  <username>agentadmin</username>
  <password>${agent_admin_password}</password>
</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
EOF
)

if [ "${cloud_agents}" == 'vm' ]; then
  echo "${agent_admin_cred}" > agent_admin_cred.xml
  run_util_script "scripts/jenkins/run-cli-command.sh" -c "create-credentials-by-xml system::system::jenkins _" -cif agent_admin_cred.xml
  rm agent_admin_cred.xml
  inter_jenkins_config=$(sed -zr -e"s|<clouds/>|{clouds}|" /var/lib/jenkins/config.xml)
  final_jenkins_config=${inter_jenkins_config//'{clouds}'/${vm_agent_conf}}
  echo "${final_jenkins_config}" | sudo tee /var/lib/jenkins/config.xml > /dev/null
elif [ "${cloud_agents}" == 'aci' ]; then
  inter_jenkins_config=$(sed -zr -e"s|<clouds/>|{clouds}|" /var/lib/jenkins/config.xml)
  final_jenkins_config=${inter_jenkins_config//'{clouds}'/${aci_agent_conf}}
  echo "${final_jenkins_config}" | sudo tee /var/lib/jenkins/config.xml > /dev/null
fi

run_util_script "scripts/jenkins/run-cli-command.sh" -c "reload-configuration"

#install nginx
sudo apt-get install nginx --yes

#configure nginx
echo "${nginx_reverse_proxy_conf}" | sudo tee /etc/nginx/sites-enabled/default > /dev/null

#don't show version in headers
sudo sed -i "s|.*server_tokens.*|server_tokens off;|" /etc/nginx/nginx.conf

#install jenkins-on-azure web page
run_util_script "scripts/jenkins/jenkins-on-azure/install-web-page.sh" -u "${jenkins_fqdn}"  -l "${azure_web_page_location}" -al "${artifacts_location}" -st "${artifacts_location_sas_token}"

#restart nginx
sudo service nginx restart

#install common tools
sudo apt-get install git --yes
sudo apt-get install azure-cli --yes
sudo az aks install-cli --client-version ${cluster_version}
sudo apt-get install xmlstarlet


#!/bin/bash
function print_usage() {
  cat <<EOF
Command
  $0
Arguments
  --vm_user_name|-u               [Required] : VM user name
  --git_url|-g                    [Required] : Git URL with a Dockerfile in it's root
  --registry|-r                   [Required] : Registry url targeted by the pipeline
  --registry_user_name|-ru        [Required] : Registry user name
  --registry_password|-rp         [Required] : Registry password
  --repository|-rr                [Required] : Repository targeted by the pipeline
  --resource_group_name|-gn       [Required] : Name of the resource group which contains the AKS
  --cluster_name|-cn              [Required] : Name of the AKS cluster
  --cluster_version|-cv           [Required] : Version of the AKS cluster
  --jenkins_fqdn|-jf              [Required] : Jenkins FQDN
  --service_principal_id|-spid    [Required] : The service principal ID.
  --service_principal_secret|-ss  [Required] : The service principal secret.
  --subscription_id|-subid        [Required] : The subscription ID of the SP.
  --tenant_id|-tid                [Required] : The tenant id of the SP.
  --mongodb_uri|-mu               [Required] : URI of the MongoDB
  --artifacts_location|-al                   : Url used to reference other scripts/artifacts.
  --sas_token|-st                            : A sas token needed if the artifacts location is private.
EOF
}

function throw_if_empty() {
  local name="$1"
  local value="$2"
  if [ -z "$value" ]; then
    echo "Parameter '$name' cannot be empty." 1>&2
    print_usage
    exit -1
  fi
}

function run_util_script() {
  local script_path="$1"
  shift
  curl --silent "${artifacts_location}${script_path}${artifacts_location_sas_token}" | sudo bash -s -- "$@"
  local return_value=$?
  if [ $return_value -ne 0 ]; then
    >&2 echo "Failed while executing script '$script_path'."
    exit $return_value
  fi
}

#defaults
while [[ $# > 0 ]]
do
  key="$1"
  shift
  case $key in
    --vm_user_name|-u)
      vm_user_name="$1"
      shift
      ;;
    --git_url|-g)
      git_url="$1"
      shift
      ;;
    --registry|-r)
      registry="$1"
      shift
      ;;
    --registry_user_name|-ru)
      registry_user_name="$1"
      shift
      ;;
    --registry_password|-rp)
      registry_password="$1"
      shift
      ;;
    --repository|-rr)
      repository="$1"
      shift
      ;;
    --resource_group_name|-gn)
      resource_group_name="$1"
      shift
      ;;
    --cluster_name|-cn)
      cluster_name="$1"
      shift
      ;;
    --cluster_version|-cv)
      cluster_version="$1"
      shift
      ;;
    --jenkins_fqdn|-jf)
      jenkins_fqdn="$1"
      shift
      ;;
    --service_principal_id|-spid)
      service_principal_id="$1"
      shift
      ;;
    --service_principal_secret|-ss)
      service_principal_secret="$1"
      shift
      ;;
    --subscription_id|-subid)
      subscription_id="$1"
      shift
      ;;
    --tenant_id|-tid)
      tenant_id="$1"
      shift
      ;;
    --mongodb_uri|-mu)
      mongodb_uri="$1"
      shift
      ;;
    --artifacts_location|-al)
      artifacts_location="$1"
      shift
      ;;
    --sas_token|-st)
      artifacts_location_sas_token="$1"
      shift
      ;;
    --help|-help|-h)
      print_usage
      exit 13
      ;;
    *)
      echo "ERROR: Unknown argument '$key' to script '$0'" 1>&2
      exit -1
  esac
done

throw_if_empty --vm_user_name $vm_user_name
throw_if_empty --git_url $git_url
throw_if_empty --registry $registry
throw_if_empty --registry_user_name $registry_user_name
throw_if_empty --registry_password $registry_password
throw_if_empty --jenkins_fqdn $jenkins_fqdn
throw_if_empty --service_principal_id $service_principal_id
throw_if_empty --service_principal_secret $service_principal_secret
throw_if_empty --subscription_id $subscription_id
throw_if_empty --tenant_id $tenant_id
throw_if_empty --resource_group_name $resource_group_name
throw_if_empty --cluster_name $cluster_name
throw_if_empty --mongodb_uri $mongodb_uri

#install jenkins
run_util_script "scripts/jenkins/install_jenkins.sh" -jf "${jenkins_fqdn}" -cn "${cluster_name}" -cv "${cluster_version}" -spid "${service_principal_id}" -ss "${service_principal_secret}" -subid "${subscription_id}" -tid "${tenant_id}" -al "${artifacts_location}" -st "${artifacts_location_sas_token}"

#install git
sudo apt-get install git --yes

#install docker if not already installed
if !(command -v docker >/dev/null); then
  sudo curl -sSL https://get.docker.com/ | sh
fi

#make sure jenkins has access to docker cli
sudo gpasswd -a jenkins docker
skill -KILL -u jenkins
sudo service jenkins restart

if [ -z "$repository" ]; then
  repository="hello-world"
fi

job_short_name="hello-world"
job_display_name="Hello World Build & Deploy"
job_description="A pipeline that builds a Docker image, pushed built image to ACR, and deploy configurations to AKS."

echo "Including the pipeline"
run_util_script "scripts/jenkins/add-docker-build-job.sh" -j "http://localhost:8080/" -ju "admin" -jsn "${job_short_name}" -jdn "${job_display_name}" -jd "${job_description}" -g "${git_url}" -r "${registry}" -ru "${registry_user_name}" -rp "${registry_password}" -rr "$repository" -agn "${resource_group_name}" -acn "${cluster_name}" -mu "${mongodb_uri}" -sps "* * * * *" -al "$artifacts_location" -st "$artifacts_location_sas_token"


#!/bin/bash

function print_usage() {
  cat <<EOF
Command
  $0
Arguments
  --command|-c             [Required]: Jenkins cli command to run
  --command_input_file|-cif          : File path containing the input to the CLI command
  --jenkins_url|-j                   : Jenkins URL, defaulted to "http://localhost:8080/"
  --jenkins_username|-ju             : Jenkins user name, defaulted to "admin"
  --jenkins_password|-jp             : Jenkins password. If not specified and the user name is "admin", the initialAdminPassword will be used
EOF
}

function throw_if_empty() {
  local name="$1"
  local value="$2"
  if [ -z "$value" ]; then
    >&2 echo "Parameter '$name' cannot be empty."
    print_usage
    exit -1
  fi
}

#set defaults
jenkins_url="http://localhost:8080/"
jenkins_username="admin"

while [[ $# > 0 ]]
do
  key="$1"
  shift
  case $key in
    --command|-c)
      command="$1"
      shift
      ;;
    --command_input_file|-cif)
      command_input_file="$1"
      shift
      ;;
    --jenkins_url|-j)
      jenkins_url="$1"
      shift
      ;;
    --jenkins_username|-ju)
      jenkins_username="$1"
      shift
      ;;
    --jenkins_password|-jp)
      jenkins_password="$1"
      shift
      ;;
    --help|-help|-h)
      print_usage
      exit 13
      ;;
    *)
      >&2 echo "ERROR: Unknown argument '$key' to script '$0'"
      exit -1
  esac
done

throw_if_empty jenkins_username $jenkins_username
if [ "$jenkins_username" != "admin" ]; then
  throw_if_empty jenkins_password $jenkins_password
fi

function retry_until_successful {
  counter=0
  "${@}"
  while [ $? -ne 0 ]; do
    if [[ "$counter" -gt 20 ]]; then
        exit 1
    else
        let counter++
    fi
    sleep 5
    "${@}"
  done;
}

function retry_until_successful_with_input {
  input_file=$1
  shift
  counter=0
  cat "$input_file" | "${@}"
  while [ $? -ne 0 ]; do
    if [[ "$counter" -gt 20 ]]; then
        exit 1
    else
        let counter++
    fi
    sleep 5
    cat "$input_file" | "${@}"
  done;
}

if [ ! -e jenkins-cli.jar ]; then
  >&2 echo "Downloading Jenkins CLI..."
  retry_until_successful wget ${jenkins_url}jnlpJars/jenkins-cli.jar -O jenkins-cli.jar
fi

if [ -z "$jenkins_password" ]; then
  # NOTE: Intentionally setting this after the first retry_until_successful to ensure the initialAdminPassword file exists
  jenkins_password=`sudo cat /var/lib/jenkins/secrets/initialAdminPassword`
fi

>&2 echo "Running \"${command}\"..."
if [ -z "${command_input_file}" ]; then
  retry_until_successful java -jar jenkins-cli.jar -s "${jenkins_url}" -auth "${jenkins_username}":"${jenkins_password}" $command
else
  retry_until_successful_with_input "${command_input_file}" java -jar jenkins-cli.jar -s "${jenkins_url}" -auth "${jenkins_username}":"${jenkins_password}" $command
fi


#!/bin/bash
function print_usage() {
  cat <<EOF
Command
  $0
Arguments
  --location|-l            [Required] : The web page location
  --url|-u                 [Required] : Domain URL
  --artifacts_location|-al            : Url used to reference other scripts/artifacts.
  --sas_token|-st                     : A sas token needed if the artifacts location is private.
EOF
}

function throw_if_empty() {
  local name="$1"
  local value="$2"
  if [ -z "$value" ]; then
    echo "Parameter '$name' cannot be empty." 1>&2
    print_usage
    exit -1
  fi
}

while [[ $# > 0 ]]
do
  key="$1"
  shift
  case $key in
    --location|-l)
      location="$1"
      shift
      ;;
    --url|-u)
      url="$1"
      shift
      ;;
    --artifacts_location|-al)
      artifacts_location="$1"
      shift
      ;;
    --sas_token|-st)
      artifacts_location_sas_token="$1"
      shift
      ;;
    --help|-help|-h)
      print_usage
      exit 13
      ;;
    *)
      echo "ERROR: Unknown argument '$key' to script '$0'" 1>&2
      exit -1
  esac
done

throw_if_empty --location $location
throw_if_empty --url $url

#install jenkins-on-azure web page
sudo mkdir ${location}
artifacts=("headshot.png" "title.png" "azure.svg" "copy.png" "site.css" "site.js" "index.html")
for i in "${artifacts[@]}"; do
  if [[ $i =~ .*html.* ]]
  then
      raw_resource=$(curl --silent "${artifacts_location}scripts/jenkins/jenkins-on-azure/$i${artifacts_location_sas_token}")
      final_resource=${raw_resource//'{domain-name}'/${url}}
      echo "${final_resource}" | sudo tee ${location}/$i > /dev/null
    else
      curl --silent "${artifacts_location}scripts/jenkins/jenkins-on-azure/$i${artifacts_location_sas_token}" -o ${location}/$i
  fi
done


#!/bin/bash

function print_usage() {
  cat <<EOF
Command
  $0
Arguments
  --jenkins_fqdn|-jf               [Required] : Jenkins FQDN
  --jenkins_private_ip|-jpi                   : The VM private ip used to configure Jenkins URL. If missing, jenkins_fqdn will be used instead
  --jenkins_release_type|-jrt                 : The Jenkins release type (LTS or weekly or verified). By default it's set to LTS
  --jenkins_version_location|-jvl             : Url used to specify the version of Jenkins.
  --subscription|-su               [Required] : Azure subscription id
  --tenant|-t                      [Required] : Azure tenant id
  --clientid|-i                    [Required] : Azure service principal client id
  --clientsecret|-s                [Required] : Azure service principal client secret
  --resourcegroup|-rg              [Required] : Azure resource group for the components
  --location|-l                    [Required] : Azure resource group location for the components
  --image_resourcegroup|-irg       [Required] : Azure resource group for the VM image
  --image|-im                                 : VM image name
  --vm_dns|-vd                     [Required] : Unique DNS name for the Virtual Machine
  --vm_username|-vu                [Required] : Username for the Virtual Machine
  --vm_password|-vp                [Required] : Password for the Virtual Machine
  --repository|-rr                 [Required] : Repository targeted by the build
  --oms_workspace_id|-wi           [Required] : OMS workspace id
  --oms_workspace_key|-wk          [Required] : OMS workspace key
  --artifacts_location|-al                    : Url used to reference other scripts/artifacts.
  --sas_token|-st                             : A sas token needed if the artifacts location is private.
EOF
}

function throw_if_empty() {
  local name="$1"
  local value="$2"
  if [ -z "$value" ]; then
    >&2 echo "Parameter '$name' cannot be empty."
    print_usage
    exit -1
  fi
}

function ms_run_util_script() {
  local script_path="$1"
  shift
  curl --silent "${ms_artifacts_location}${script_path}${ms_artifacts_location_sas_token}" | sudo bash -s -- "$@"
  local return_value=$?
  if [ $return_value -ne 0 ]; then
    >&2 echo "Failed while executing script '$script_path'."
    exit $return_value
  fi
}

# set defaults
jenkins_url="http://localhost:8080/"
jenkins_username="admin"
jenkins_password=""
image="myPackerLinuxImage"
job_short_name="BuildVM"
credential_id="vmCred"
credential_description="VM credential"
ms_artifacts_location="https://raw.githubusercontent.com/Azure/azure-devops-utils/v0.28.1/"
ms_artifacts_location_sas_token=""

while [[ $# > 0 ]]
do
  key="$1"
  shift
  case $key in
    --jenkins_fqdn|-jf)
      jenkins_fqdn="$1"
      shift
      ;;
    --jenkins_private_ip|-jpi)
      jenkins_private_ip="$1"
      shift
      ;;
    --jenkins_release_type|-jrt)
      jenkins_release_type="$1"
      shift
      ;;
    --jenkins_version_location|-jvl)
      jenkins_version_location="$1"
      shift
      ;;
    --subscription|-su)
      subscription="$1"
      shift
      ;;
    --tenant|-t)
      tenant="$1"
      shift
      ;;
    --clientid|-i)
      clientid="$1"
      shift
      ;;
    --clientsecret|-s)
      clientsecret="$1"
      shift
      ;;
    --resourcegroup|-rg)
      resourcegroup="$1"
      shift
      ;;
    --location|-l)
      location="$1"
      shift
      ;;
    --image_resourcegroup|-irg)
      image_resourcegroup="$1"
      shift
      ;;
    --image|-im)
      image="$1"
      shift
      ;;
    --vm_dns|-vd)
      vm_dns="$1"
      shift
      ;;
    --vm_username|-vu)
      vm_username="$1"
      shift
      ;;
    --vm_password|-vp)
      vm_password="$1"
      shift
      ;;
    --repository|-rr)
      repository="$1"
      shift
      ;;
    --oms_workspace_id|-wi)
      oms_workspace_id="$1"
      shift
      ;;
    --oms_workspace_key|-wk)
      oms_workspace_key="$1"
      shift
      ;;
    --artifacts_location|-al)
      artifacts_location="$1"
      shift
      ;;
    --sas_token|-st)
      artifacts_location_sas_token="$1"
      shift
      ;;
    --help|-help|-h)
      print_usage
      exit 13
      ;;
    *)
      >&2 echo "ERROR: Unknown argument '$key' to script '$0'"
      exit -1
  esac
done

throw_if_empty jenkins_username $jenkins_username
if [ "$jenkins_username" != "admin" ]; then
  throw_if_empty jenkins_password $jenkins_password
fi
throw_if_empty --jenkins_fqdn $jenkins_fqdn
throw_if_empty --subscription $subscription
throw_if_empty --tenant $tenant
throw_if_empty --clientid $clientid
throw_if_empty --clientsecret $clientsecret
throw_if_empty --resourcegroup $resourcegroup
throw_if_empty --location $location
throw_if_empty --image_resourcegroup $image_resourcegroup
throw_if_empty --vm_dns $vm_dns
throw_if_empty --vm_username $vm_username
throw_if_empty --vm_password $vm_password
throw_if_empty --repository $repository
throw_if_empty --oms_workspace_id $oms_workspace_id
throw_if_empty --oms_workspace_key $oms_workspace_key

# install jenkins
ms_run_util_script "jenkins/install_jenkins.sh" -jf "${jenkins_fqdn}" -pi "${jenkins_private_ip}" -jrt "${jenkins_release_type}" -jvl "${jenkins_version_location}" -al "${ms_artifacts_location}" -st "${ms_artifacts_location_sas_token}"

# install required plugins
plugins=(credentials envinject)
for plugin in "${plugins[@]}"; do
  ms_run_util_script "jenkins/run-cli-command.sh" -j "$jenkins_url" -ju "$jenkins_username" -jp "$jenkins_password" -c "install-plugin $plugin -deploy"
done

# restart jenkins
sudo service jenkins restart

# wait for instance to be back online
ms_run_util_script "jenkins/run-cli-command.sh" -j "$jenkins_url" -ju "$jenkins_username" -jp "$jenkins_password" -c "version"

# download dependencies
job_xml=$(curl -s ${artifacts_location}/scripts/jenkins/jobs-build-vm.xml${artifacts_location_sas_token})
credentials_xml=$(curl -s ${artifacts_location}/scripts/jenkins/credentials-basic.xml${artifacts_location_sas_token})

# prepare job xml
job_xml=${job_xml//'{insert-repository-url}'/${repository}}
job_xml=${job_xml//'{insert-credentials-id}'/${credential_id}}
job_xml=${job_xml//'{insert-subscription-id}'/${subscription}}
job_xml=${job_xml//'{insert-tenant-id}'/${tenant}}
job_xml=${job_xml//'{insert-client-id}'/${clientid}}
job_xml=${job_xml//'{insert-client-secret}'/${clientsecret}}
job_xml=${job_xml//'{insert-resource-group}'/${resourcegroup}}
job_xml=${job_xml//'{insert-location}'/${location}}
job_xml=${job_xml//'{insert-image-resource-group}'/${image_resourcegroup}}
job_xml=${job_xml//'{insert-image-name}'/${image}}
job_xml=${job_xml//'{insert-dns-name}'/${vm_dns}}
job_xml=${job_xml//'{insert-repository-url}'/${repository}}
job_xml=${job_xml//'{insert-oms-workspace-id}'/${oms_workspace_id}}
job_xml=${job_xml//'{insert-oms-workspace-key}'/${oms_workspace_key}}

# prepare credential xml
credentials_xml=${credentials_xml//'{insert-credentials-id}'/${credential_id}}
credentials_xml=${credentials_xml//'{insert-credentials-description}'/${credential_description}}
credentials_xml=${credentials_xml//'{insert-user-name}'/${vm_username}}
credentials_xml=${credentials_xml//'{insert-user-password}'/${vm_password}}

# add job
echo "${job_xml}" > job.xml
ms_run_util_script "jenkins/run-cli-command.sh" -j "$jenkins_url" -ju "$jenkins_username" -jp "$jenkins_password" -c "create-job ${job_short_name}" -cif "job.xml"

# add credential
echo "${credentials_xml}" > credentials.xml
ms_run_util_script "jenkins/run-cli-command.sh" -j "$jenkins_url" -ju "$jenkins_username" -jp "$jenkins_password" -c "create-credentials-by-xml system::system::jenkins _" -cif "credentials.xml"

# install tools
sudo apt-get install unzip --yes

wget https://releases.hashicorp.com/packer/1.1.3/packer_1.1.3_linux_amd64.zip
unzip packer_1.1.3_linux_amd64.zip -d /usr/bin

wget https://releases.hashicorp.com/terraform/0.11.1/terraform_0.11.1_linux_amd64.zip
unzip terraform_0.11.1_linux_amd64.zip -d /usr/bin

# cleanup
rm job.xml
rm credentials.xml
rm jenkins-cli.jar
rm packer_1.1.3_linux_amd64.zip
rm terraform_0.11.1_linux_amd64.zip


#!/bin/bash

# Update apt-get package list
apt-get update

# Install Java
apt-get -y install openjdk-8-jdk

# https://devops.profitbricks.com/tutorials/how-to-install-and-configure-tomcat-8-on-ubuntu-1604/

# Create a tomcat group
groupadd tomcat
# Create a new tomcat user and make this user member of the tomcat group with home directory /opt/tomcat
useradd -s /bin/false -g tomcat -d /opt/tomcat tomcat

# Install Tomcat
wget https://archive.apache.org/dist/tomcat/tomcat-8/v8.5.24/bin/apache-tomcat-8.5.24.tar.gz
tar -xzvf apache-tomcat-8.5.24.tar.gz
mv apache-tomcat-8.5.24 /opt/tomcat

# Give proper permission to the tomcat user to access to the Tomcat installation.
chgrp -R tomcat /opt/tomcat
chown -R tomcat /opt/tomcat
chmod -R 755 /opt/tomcat

if [ ! -z "$repository_url" ];
then
    # Clone code
    cd /tmp
    git clone $repository_url

    # Deploy code to ROOT
    rm -rf /opt/tomcat/webapps/ROOT/*
    cp -r /tmp/azure-quickstart-templates/jenkins-cicd-vmss/HelloWorld/WebContent/* /opt/tomcat/webapps/ROOT
else
    echo 'ERROR: Repository URL is not provided'
fi

#echo 'export CATALINA_HOME="/opt/tomcat9"' >> /etc/environment
#echo 'export JAVA_HOME="/usr/lib/jvm/java-8-openjdk-amd64"' >> /etc/environment
#echo 'export JRE_HOME="/usr/lib/jvm/java-8-openjdk-amd64/jre"' >> /etc/environment

# Create a systemd Service File
echo "[Unit]
Description=Apache Tomcat Web Server
After=network.target

[Service]
Type=forking

Environment=JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/jre
Environment=CATALINA_PID=/opt/tomcat/temp/tomcat.pid
Environment=CATALINA_HOME=/opt/tomcat
Environment=CATALINA_BASE=/opt/tomcat
Environment='CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC'
Environment='JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom'

ExecStart=/opt/tomcat/bin/startup.sh
ExecStop=/opt/tomcat/bin/shutdown.sh

User=tomcat
Group=tomcat
UMask=0007
RestartSec=15
Restart=always

[Install]
WantedBy=multi-user.target" >> /etc/systemd/system/tomcat.service

# Reload the systemd daemon for the new service file above
systemctl daemon-reload
# Start the Tomcat service
systemctl start tomcat
# Configure the Tomcat service to start during boot
systemctl enable tomcat

# https://stackoverflow.com/questions/4756039/how-to-change-the-port-of-tomcat-from-8080-to-80
# https://dzone.com/articles/running-tomcat-port-80-user
# http://2ality.blogspot.com/2010/07/running-tomcat-on-port-80-in-user.html

# Change default port to 80 from 8080
sed -i 's/Connector port="8080"/Connector port="80"/g' /opt/tomcat/conf/server.xml
apt-get install authbind
touch /etc/authbind/byport/80
chmod 500 /etc/authbind/byport/80
chown tomcat /etc/authbind/byport/80
echo 'CATALINA_OPTS="-Djava.net.preferIPv4Stack=true"' >> /opt/tomcat/bin/setenv.sh
sed -i 's/exec "$PRGDIR"\/"$EXECUTABLE" start "$@"/exec authbind --deep "$PRGDIR"\/"$EXECUTABLE" start "$@"/g' /opt/tomcat/bin/startup.sh

/usr/sbin/waagent -force -deprovision+user && export HISTSIZE=0 && sync

if [ ! -z "$oms_workspace_id" -a ! -z "$oms_workspace_key" ];
then
    wget https://raw.githubusercontent.com/Microsoft/OMS-Agent-for-Linux/master/installer/scripts/onboard_agent.sh && sh onboard_agent.sh -w $oms_workspace_id -s $oms_workspace_key -d opinsights.azure.com
else
    echo 'ERROR: OMS workspace id or key is not provided'
fi


#!/bin/bash

function print_usage() {
  cat <<EOF
Command
  $0
Arguments
  --jenkins_fqdn|-jf              [Required] : Jenkins FQDN
  --jenkins_private_ip|-jpi                  : The VM private ip used to configure Jenkins URL. If missing, jenkins_fqdn will be used instead
  --jenkins_release_type|-jrt                : The Jenkins release type (LTS or weekly or verified). By default it's set to LTS
  --jenkins_version_location|-jvl            : Url used to specify the version of Jenkins.
  --subscription|-su               [Required]: Azure subscription id
  --tenant|-t                      [Required]: Azure tenant id
  --clientid|-i                    [Required]: Azure service principal client id
  --clientsecret|-s                [Required]: Azure service principal client secret
  --storage_account_name|-sn       [Required]: Azure storage account name
  --storage_account_key|-sk        [Required]: Azure storage account key
  --resourcegroup|-rg              [Required]: Azure resource group for the components
  --webapp|-w                      [Required]: Azure web app name
  --repository|-rr                 [Required]: Repository targeted by the build
  --artifacts_location|-al                   : Url used to reference other scripts/artifacts.
  --sas_token|-st                            : A sas token needed if the artifacts location is private.
EOF
}

function throw_if_empty() {
  local name="$1"
  local value="$2"
  if [ -z "$value" ]; then
    >&2 echo "Parameter '$name' cannot be empty."
    print_usage
    exit -1
  fi
}

function ms_run_util_script() {
  local script_path="$1"
  shift
  curl --silent "${ms_artifacts_location}${script_path}${ms_artifacts_location_sas_token}" | sudo bash -s -- "$@"
  local return_value=$?
  if [ $return_value -ne 0 ]; then
    >&2 echo "Failed while executing script '$script_path'."
    exit $return_value
  fi
}

# set defaults
jenkins_url="http://localhost:8080/"
jenkins_username="admin"
jenkins_password=""
jenkins_agent_port=5378
job_short_name="BuildWebApp"
credential_sp_id='mySP'
credential_sp_description='Azure Service Principal'
credential_storage_id='myStorage'
credential_storage_description='Microsoft Azure Storage	'
aci_container_name='ACI-container'
aci_container_image='cloudbees/jnlp-slave-with-java-build-tools'
ms_artifacts_location="https://raw.githubusercontent.com/Azure/azure-devops-utils/v0.28.1/"
ms_artifacts_location_sas_token=""

while [[ $# > 0 ]]
do
  key="$1"
  shift
  case $key in
    --jenkins_fqdn|-jf)
      jenkins_fqdn="$1"
      shift
      ;;
    --jenkins_private_ip|-jpi)
      jenkins_private_ip="$1"
      shift
      ;;
    --jenkins_release_type|-jrt)
      jenkins_release_type="$1"
      shift
      ;;
    --jenkins_version_location|-jvl)
      jenkins_version_location="$1"
      shift
      ;;
    --subscription|-su)
      subscription="$1"
      shift
      ;;
    --tenant|-t)
      tenant="$1"
      shift
      ;;
    --clientid|-i)
      clientid="$1"
      shift
      ;;
    --clientsecret|-s)
      clientsecret="$1"
      shift
      ;;
    --storage_account_name|-sn)
      storage_account_name="$1"
      shift
      ;;
    --storage_account_key|-sk)
      storage_account_key="$1"
      shift
      ;;
    --resourcegroup|-rg)
      resourcegroup="$1"
      shift
      ;;
    --webapp|-w)
      webapp="$1"
      shift
      ;;
    --repository|-rr)
      repository="$1"
      shift
      ;;
    --artifacts_location|-al)
      artifacts_location="$1"
      shift
      ;;
    --sas_token|-st)
      artifacts_location_sas_token="$1"
      shift
      ;;
    --help|-help|-h)
      print_usage
      exit 13
      ;;
    *)
      >&2 echo "ERROR: Unknown argument '$key' to script '$0'"
      exit -1
  esac
done

# ==================================== VALIDATION ====================================
throw_if_empty jenkins_username $jenkins_username
if [ "$jenkins_username" != "admin" ]; then
  throw_if_empty jenkins_password $jenkins_password
fi
throw_if_empty --jenkins_fqdn $jenkins_fqdn
throw_if_empty --subscription $subscription
throw_if_empty --tenant $tenant
throw_if_empty --clientid $clientid
throw_if_empty --clientsecret $clientsecret
throw_if_empty --storage_account_name $storage_account_name
throw_if_empty --storage_account_key $storage_account_key
throw_if_empty --resourcegroup $resourcegroup
throw_if_empty --webapp $webapp
throw_if_empty --repository $repository

# ==================================== INSTALL JENKINS ====================================
ms_run_util_script "jenkins/install_jenkins.sh" -jf "${jenkins_fqdn}" -pi "${jenkins_private_ip}" -jrt "${jenkins_release_type}" -jvl "${jenkins_version_location}" -al "${ms_artifacts_location}" -st "${ms_artifacts_location_sas_token}"

# ==================================== PLUGIN ====================================
# install required plugins
plugins=(credentials envinject)
for plugin in "${plugins[@]}"; do
  ms_run_util_script "jenkins/run-cli-command.sh" -j "$jenkins_url" -ju "$jenkins_username" -jp "$jenkins_password" -c "install-plugin $plugin -deploy"
done

# ==================================== JNLP ====================================
# open a fixed port for JNLP
inter_jenkins_config=$(sed -zr -e"s|<slaveAgentPort.*</slaveAgentPort>|<slaveAgentPort>{slave-agent-port}</slaveAgentPort>|" /var/lib/jenkins/config.xml)
final_jenkins_config=${inter_jenkins_config//'{slave-agent-port}'/${jenkins_agent_port}}
echo "${final_jenkins_config}" | sudo tee /var/lib/jenkins/config.xml > /dev/null

# ==================================== RESTART JENKINS ====================================
# restart jenkins
sudo service jenkins restart

# wait for instance to be back online
ms_run_util_script "jenkins/run-cli-command.sh" -j "$jenkins_url" -ju "$jenkins_username" -jp "$jenkins_password" -c "version"

# ==================================== CREDENTIAL ====================================
# download credential dependencies
credentials_sp_xml=$(curl -s ${artifacts_location}/scripts/jenkins/credentials-sp.xml${artifacts_location_sas_token})
credentials_storage_xml=$(curl -s ${artifacts_location}/scripts/jenkins/credentials-storage.xml${artifacts_location_sas_token})

# prepare credentials_sp.xml (service principal)
credentials_sp_xml=${credentials_sp_xml//'{insert-credentials-id}'/${credential_sp_id}}
credentials_sp_xml=${credentials_sp_xml//'{insert-credentials-description}'/${credential_sp_description}}
credentials_sp_xml=${credentials_sp_xml//'{insert-subscription-id}'/${subscription}}
credentials_sp_xml=${credentials_sp_xml//'{insert-client-id}'/${clientid}}
credentials_sp_xml=${credentials_sp_xml//'{insert-client-secret}'/${clientsecret}}
credentials_sp_xml=${credentials_sp_xml//'{insert-tenant-id}'/${tenant}}

# prepare credentials_storage.xml (storage account)
credentials_storage_xml=${credentials_storage_xml//'{insert-credentials-id}'/${credential_storage_id}}
credentials_storage_xml=${credentials_storage_xml//'{insert-credentials-description}'/${credential_storage_description}}
credentials_storage_xml=${credentials_storage_xml//'{insert-credentials-account-name}'/${storage_account_name}}
credentials_storage_xml=${credentials_storage_xml//'{insert-credentials-account-key}'/${storage_account_key}}

# add credentials
echo "${credentials_sp_xml}" > credentials_sp.xml
echo "${credentials_storage_xml}" > credentials_storage.xml
ms_run_util_script "jenkins/run-cli-command.sh" -j "$jenkins_url" -ju "$jenkins_username" -jp "$jenkins_password" -c "create-credentials-by-xml system::system::jenkins _" -cif "credentials_sp.xml"
ms_run_util_script "jenkins/run-cli-command.sh" -j "$jenkins_url" -ju "$jenkins_username" -jp "$jenkins_password" -c "create-credentials-by-xml system::system::jenkins _" -cif "credentials_storage.xml"

# ==================================== ACI AGENT ====================================
# download aci agent dependencies
configs_agent_aci_xml=$(curl -s ${artifacts_location}/scripts/jenkins/configs-agent-aci.xml${artifacts_location_sas_token})

# configure Azure Container Instance
configs_agent_aci_xml=${configs_agent_aci_xml//'{insert-credentials-id}'/${credential_sp_id}}
configs_agent_aci_xml=${configs_agent_aci_xml//'{insert-resourcegroup-name}'/${resourcegroup}}
configs_agent_aci_xml=${configs_agent_aci_xml//'{insert-aci-container-name}'/${aci_container_name}}
configs_agent_aci_xml=${configs_agent_aci_xml//'{insert-aci-container-image}'/${aci_container_image}}

inter_jenkins_config=$(sed -zr -e"s|<clouds/>|{clouds}|" /var/lib/jenkins/config.xml)
final_jenkins_config=${inter_jenkins_config//'{clouds}'/${configs_agent_aci_xml}}
echo "${final_jenkins_config}" | sudo tee /var/lib/jenkins/config.xml > /dev/null

# ==================================== RELOAD CONFIG ====================================
ms_run_util_script "jenkins/run-cli-command.sh" -c "reload-configuration"

# ==================================== JOB ====================================
# download job dependencies
job_xml=$(curl -s ${artifacts_location}/scripts/jenkins/jobs-build-webapp.xml${artifacts_location_sas_token})

# prepare job.xml
job_xml=${job_xml//'{insert-repository-url}'/${repository}}
job_xml=${job_xml//'{insert-aci-container}'/${aci_container_name}}
job_xml=${job_xml//'{insert-credentials-storage-id}'/${credential_storage_id}}
job_xml=${job_xml//'{insert-credentials-sp-id}'/${credential_sp_id}}
job_xml=${job_xml//'{insert-resourcegroup-name}'/${resourcegroup}}
job_xml=${job_xml//'{insert-webapp-name}'/${webapp}}

# add job
echo "${job_xml}" > job.xml
ms_run_util_script "jenkins/run-cli-command.sh" -j "$jenkins_url" -ju "$jenkins_username" -jp "$jenkins_password" -c "create-job ${job_short_name}" -cif "job.xml"

# ==================================== CLEANUP ====================================
rm job.xml
rm credentials_sp.xml
rm credentials_storage.xml
rm jenkins-cli.jar


wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -
sh -c 'echo deb https://pkg.jenkins.io/debian-stable binary/ >  /etc/apt/sources.list.d/jenkins.list'
apt update -y
apt install openjdk-8-jdk git maven docker.io  -y
apt install jenkins -y
systemctl enable jenkins
systemctl enable docker
usermod -aG docker jenkins
## Create the TOOLS directory
## Create TOOLS directory for jenkins
mkdir /opt/tools/
cd /opt/tools
## Install solar scanner
wget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.2.0.1873-linux.zip
jar -xvf sonar-scanner-cli-4.2.0.1873-linux.zip
mv sonar-scanner-4.2.0.1873-linux/ sonar/
rm sonar-scanner-cli-4.2.0.1873-linux.zip
### SONARQUBE SETUP
# Update kernel memory page limits and max files limits (MANDATORY FOR SONARQUBE)
sysctl -w vm.max_map_count=262144
sysctl -w fs.file-max=65536
ulimit -n 65536
ulimit -u 4096
# Download SonarQube 7.1 (Compatible with JDK 8)
wget https://binaries.sonarsource.com/Distribution/sonarqube/sonarqube-7.1.zip
jar -xvf sonarqube-7.1.zip
groupadd sonar
sudo useradd -c "user to run SonarQube" -d /opt/tools/sonarqube-7.1 -g sonar sonar
cd sonarqube-7.1/bin/linux-x86-64
# set RUN_AS_USER=sonar
sed -i 's/#RUN_AS_USER=/RUN_AS_USER=sonar/g' sonar.sh
chown -R jenkins:jenkins /opt/tools/


apt update -y
## Install JDK8, Git & Maven
apt install openjdk-8-jdk git maven  -y
## Install Docker-CE
apt install docker.io -y
## create new jenkins user
useradd -m -s /bin/bash jenkins
## Allow JENKINS user to access docker
usermod -aG docker jenkins
## Create TOOLS directory for jenkins
mkdir /opt/tools/
cd /opt/tools
## install solar-scanner
wget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.2.0.1873-linux.zip
jar -xvf sonar-scanner-cli-4.2.0.1873-linux.zip
mv sonar-scanner-4.2.0.1873-linux/ sonar/
rm sonar-scanner-cli-4.2.0.1873-linux.zip
## Change OWNER of tools to "jenkins"
chown -R jenkins:jenkins /opt/tools/


#!/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.
#
# Script: jenkMstrInstall.sh
#
# Author: Dennis Angeline (Full Scale 180 Inc)
#
# Description:
#    This script install Jenkins master on an Ubuntu VM image
#    and optionally configures tohe master with multiple dumb slave nodes.
#
# Parameters :
#    -n number of dumb slave nodes to configure
#    -h view this help content
#
# Note :
#    This script has only been tested on Ubuntu 14.04 LTS
#

help()
{

    echo "This script install Jenkins master on an Ubuntu VM image"
    echo "Parameters:"
    echo "-n number of slave nodes to configure on the master"
    echo "-h view this help content"
}

#Log method to control/redirect log output
log()
{
    echo "$1"
}

#Script Parameters
NODECNT=0

#Loop through options passed
while getopts :n:h optname; do
    log "Option $optname set with value ${OPTARG}"

  case $optname in
    n)  #set number of slave nodes
      NODECNT=${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

log "Begin execution of Jenkins install script on ${HOSTNAME} with ${NODECNT} slave nodes"

# Install openjdk-7
install_java()
{
    log "Installing openjdk-7"
    apt-get -y update > /dev/null
    apt-get -y install openjdk-7-jdk > /dev/null
    apt-get -y update > /dev/null
}

# Install jenkins master
install_jenkins()
{
    log "Installing Jenkins master"
    wget -q -O - https://jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add -
    sh -c 'echo deb http://pkg.jenkins-ci.org/debian binary/ > /etc/apt/sources.list.d/jenkins.list'
    apt-get -y update > /dev/null
    apt-get -y install jenkins > /dev/null

    log "Waiting for Jenkins master to start..."
    sleep 60
}

# Configure jenkins slave nodes
configure_slave_nodes()
{
    log "Configuring Jenkins master with $NODECNT dumb slave node(s)"

    if [ $NODECNT -gt 0 ]; then
        # Run groovy script to configure master with $NODECNT dumb slave node(s)
        sudo java -jar /var/cache/jenkins/war/WEB-INF/jenkins-cli.jar -s http://localhost:8080 groovy jenkAddNode.groovy $NODECNT
    fi
}

# Primary Install Tasks
install_java
install_jenkins
configure_slave_nodes
exit 0


#!/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.
#
# Script: jenkSlaveInstall.sh
#
# Author: Dennis Angeline (Full Scale 180 Inc)
#
# Description:
#    This script install Jenkins slave on an Ubuntu VM image
#
# Parameters :
#    -m The ip address of the master node
#    -s The name of THIS slave node as configured on the master
#    -h view this help content
#
# Note :
#    This script has only been tested on Ubuntu 14.04 LTS
#

help()
{

    echo "This script install Jenkins slave on an Ubuntu VM"
    echo "Parameters:"
    echo "-m The ip address of the master node"
    echo "-s The name of THIS slave node as configured on the master"
    echo "-h view this help content"
}

#Log method to control/redirect log output
log()
{
    echo "$1"
}

log "Begin execution of Jenkins slave install script on ${HOSTNAME}"

#Script Parameters
MASTERNODE="missing"
SLAVENAME="missing"

#Loop through options passed
while getopts :m:s:h optname; do
    log "Option $optname set with value ${OPTARG}"

  case $optname in
    m)  #set the ip address of the master
      MASTERNODE=${OPTARG}
      ;;
    s)  #set the name of this slave node
      SLAVENAME=${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

# Install openjdk-7
install_java()
{
    log "Installing openjdk-7"
    apt-get -y update > /dev/null
    apt-get -y install openjdk-7-jdk > /dev/null
    apt-get -y update > /dev/null
}

download_slave_jar()
{
    log "Downloading slave.jar from $MASTERNODE"
    wget http://$MASTERNODE:8080/jnlpJars/slave.jar -O ~/slave.jar > /dev/null
    chmod 777 ~/slave.jar
}

create_upstart_task()
{
    upstart_conf="/etc/init/jenkins_slave.conf"

    log "Creating Upstart conf file $upstart_conf"
    echo "# Jenkin Slave"                                                                                > $upstart_conf
    echo "description \"slave node for Jenkins Continuous Integration Service\""                             >> $upstart_conf
    echo ""                                                                                >> $upstart_conf
    echo "start on starting"                                                                                >> $upstart_conf
    echo "script"                                                                                >> $upstart_conf
    echo "  java -jar /root/slave.jar -jnlpUrl http://$MASTERNODE:8080/computer/$SLAVENAME/slave-agent.jnlp" >> $upstart_conf
    echo "end script"                                                                                >> $upstart_conf

    chmod +x $upstart_conf
}

start_slave()
{
    log "Executing slave.jar with http://$MASTERNODE:8080/computer/$SLAVENAME/slave-agent.jnlp"
    service jenkins_slave start
    # nohup java -jar ~/slave.jar -jnlpUrl http://$MASTERNODE:8080/computer/$SLAVENAME/slave-agent.jnlp &
}

# Primary Install Tasks

if [ $MASTERNODE == "missing" ]; then
    log "Master node not specified"
    exit 1
fi

if [ $SLAVENAME == "missing" ]; then
    log "Slave name not specified"
    exit 2
fi

install_java
download_slave_jar
create_upstart_task
start_slave
exit 0


#!/bin/bash

bootstrap.py | sudo python3 - --admin $1 >> /var/log/TLJH_install.log 2>&1


#!/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: Cognosys Technologies

###
### Warning! This script partitions and formats disk information be careful where you run it
###          This script is currently under development and has only been tested on Ubuntu images in Azure
###          This script is not currently idempotent and only works for provisioning at the moment

### Remaining work items
### -Alternate discovery options (Azure Storage)
### -Implement Idempotency and Configuration Change Support
### -Recovery Settings (These can be changed via API)

help()
{
    #TODO: Add help text here
    echo "This script installs kafka cluster on Ubuntu"
    echo "Parameters:"
    echo "-k kafka version like 0.8.2.1"
    echo "-b broker id"
    echo "-h view this help content"
    echo "-z zookeeper not kafka"
    echo "-i zookeeper Private IP address prefix"
}

log()
{
	# If you want to enable this logging add a un-comment the line below and add your account key
    	#curl -X POST -H "content-type:text/plain" --data-binary "$(date) | ${HOSTNAME} | $1" https://logs-01.loggly.com/inputs/[account-key]/tag/redis-extension,${HOSTNAME}
	echo "$1"
}

log "Begin execution of kafka script extension on ${HOSTNAME}"

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

# TEMP FIX - Re-evaluate and remove when possible
# This is an interim fix for hostname resolution in current VM
grep -q "${HOSTNAME}" /etc/hosts
if [ $? -eq $SUCCESS ];
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
  log "hostname ${HOSTNAME} added to /etc/hosts"
fi

#Script Parameters
KF_VERSION="0.8.2.1"
BROKER_ID=0
ZOOKEEPER1KAFKA0="0"

ZOOKEEPER_IP_PREFIX="10.0.0.4"
INSTANCE_COUNT=1
ZOOKEEPER_PORT="2181"

#Loop through options passed
while getopts :k:b:z:i:c:p:h optname; do
    log "Option $optname set with value ${OPTARG}"
  case $optname in
    k)  #kafka version
      KF_VERSION=${OPTARG}
      ;;
    b)  #broker id
      BROKER_ID=${OPTARG}
      ;;
    z)  #zookeeper not kafka
      ZOOKEEPER1KAFKA0=${OPTARG}
      ;;
    i)  #zookeeper Private IP address prefix
      ZOOKEEPER_IP_PREFIX=${OPTARG}
      ;;
    c) # Number of instances
	INSTANCE_COUNT=${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

# Install Oracle Java
install_java()
{
    log "Installing Java"
    apt-get update
    apt-get -y install openjdk-8-jdk
    export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
}

# Expand a list of successive IP range defined by a starting address prefix (e.g. 10.0.0.1) and the number of machines in the range
# 10.0.0.1-3 would be converted to "10.0.0.10 10.0.0.11 10.0.0.12"

expand_ip_range_for_server_properties() {
    IFS='-' read -a HOST_IPS <<< "$1"
    for (( n=0 ; n<("${HOST_IPS[1]}"+0) ; n++))
    do
        echo "server.$(expr ${n} + 1)=${HOST_IPS[0]}${n}:2888:3888" >> apache-zookeeper-3.6.3/conf/zoo.cfg
    done
}

function join { local IFS="$1"; shift; echo "$*"; }

expand_ip_range() {
    IFS='-' read -a HOST_IPS <<< "$1"

    declare -a EXPAND_STATICIP_RANGE_RESULTS=()

    for (( n=0 ; n<("${HOST_IPS[1]}"+0) ; n++))
    do
        HOST="${HOST_IPS[0]}${n}:${ZOOKEEPER_PORT}"
                EXPAND_STATICIP_RANGE_RESULTS+=($HOST)
    done

    echo "${EXPAND_STATICIP_RANGE_RESULTS[@]}"
}

# Install Zookeeper - can expose zookeeper version
install_zookeeper()
{
  apt-get update
	apt-get -y install zookeeperd
  mkdir /usr/local/zookeeper/data
  chmod -R 755 /usr/local/zookeeper/data

	echo "tickTime=2000" > /etc/zookeeper/conf/zoo.cfg
	echo "dataDir=/usr/local/zookeeper/data" > /etc/zookeeper/conf/zoo.cfg
	echo "clientPort=2181" > /etc/zookeeper/conf/zoo.cfg
	echo "initLimit=5" > /etc/zookeeper/conf/zoo.cfg
	echo "syncLimit=2" > /etc/zookeeper/conf/zoo.cfg
	$(expand_ip_range_for_server_properties "${ZOOKEEPER_IP_PREFIX}-${INSTANCE_COUNT}")

	echo $(($1+1)) >> /usr/share/zookeeper/myid

	/usr/share/zookeeper/bin/zkServer.sh start
}

# Install kafka
install_kafka()
{
	cd /usr/local
	name=kafka
	version=${KF_VERSION}
	#this Kafka version is prefix same used for all versions
	kafkaversion=2.10
	description="Apache Kafka is a distributed publish-subscribe messaging system."
	url="https://kafka.apache.org/"
	arch="all"
	section="misc"
	license="Apache Software License 2.0"
	package_version="-1"
	src_package="kafka_${kafkaversion}-${version}.tgz"
	download_url=http://mirror.sdunix.com/apache/kafka/${version}/${src_package}

	rm -rf kafka
	mkdir -p kafka
	cd kafka
	#_ MAIN _#
	if [[ ! -f "${src_package}" ]]; then
	  wget ${download_url}
	fi
	tar zxf ${src_package}
	cd kafka_${kafkaversion}-${version}

	sed -r -i "s/(broker.id)=(.*)/\1=${BROKER_ID}/g" config/server.properties
	sed -r -i "s/(zookeeper.connect)=(.*)/\1=$(join , $(expand_ip_range "${ZOOKEEPER_IP_PREFIX}-${INSTANCE_COUNT}"))/g" config/server.properties
#	cp config/server.properties config/server-1.properties
#	sed -r -i "s/(broker.id)=(.*)/\1=1/g" config/server-1.properties
#	sed -r -i "s/^(port)=(.*)/\1=9093/g" config/server-1.properties````
	chmod u+x /usr/local/kafka/kafka_${kafkaversion}-${version}/bin/kafka-server-start.sh
	/usr/local/kafka/kafka_${kafkaversion}-${version}/bin/kafka-server-start.sh /usr/local/kafka/kafka_${kafkaversion}-${version}/config/server.properties &
}

# Primary Install Tasks
#########################
#NOTE: These first three could be changed to run in parallel
#      Future enhancement - (export the functions and use background/wait to run in parallel)

#Install Oracle Java
#------------------------
install_java

if [ ${ZOOKEEPER1KAFKA0} -eq "1" ];
then
	#
	#Install zookeeper
	#-----------------------
	install_zookeeper
else
	#
	#Install kafka
	#-----------------------
	install_kafka
fi


#!/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: Cognosys Technologies

###
### Warning! This script partitions and formats disk information be careful where you run it
###          This script is currently under development and has only been tested on Ubuntu images in Azure
###          This script is not currently idempotent and only works for provisioning at the moment

### Remaining work items
### -Alternate discovery options (Azure Storage)
### -Implement Idempotency and Configuration Change Support
### -Recovery Settings (These can be changed via API)

help()
{
    #TODO: Add help text here
    echo "This script installs kafka cluster on Ubuntu"
    echo "Parameters:"
    echo "-k kafka version like 0.8.2.1"
    echo "-b broker id"
    echo "-h view this help content"
    echo "-z zookeeper not kafka"
    echo "-i zookeeper Private IP address prefix"
}

log()
{
	# If you want to enable this logging add a un-comment the line below and add your account key
    	#curl -X POST -H "content-type:text/plain" --data-binary "$(date) | ${HOSTNAME} | $1" https://logs-01.loggly.com/inputs/[account-key]/tag/redis-extension,${HOSTNAME}
	echo "$1"
}

log "Begin execution of kafka script extension on ${HOSTNAME}"

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
grep -q "${HOSTNAME}" /etc/hosts
if [ $? -eq $SUCCESS ];
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
  log "hostname ${HOSTNAME} added to /etc/hosts"
fi

#Script Parameters
KF_VERSION="0.8.2.1"
BROKER_ID=0
ZOOKEEPER1KAFKA0="0"

ZOOKEEPER_IP_PREFIX="10.0.1.10"
INSTANCE_COUNT=1
ZOOKEEPER_PORT="2181"
KAFKADIR="/var/lib/kafkadir"
# sed command issues need escape character \
KAFKADIRSED="\/var\/lib\/kafkadir"

#Loop through options passed
while getopts :k:b:z:i:c:p:h optname; do
    log "Option $optname set with value ${OPTARG}"
  case $optname in
    k)  #kafka version
      KF_VERSION=${OPTARG}
      ;;
    b)  #broker id
      BROKER_ID=${OPTARG}
      ;;
    z)  #zookeeper not kafka
      ZOOKEEPER1KAFKA0=${OPTARG}
      ;;
    i)  #zookeeper Private IP address prefix
      ZOOKEEPER_IP_PREFIX=${OPTARG}
      ;;
    c) # Number of instances
	INSTANCE_COUNT=${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

# Install Oracle Java

# install_java()
# {
#     log "Installing Java"
#     add-apt-repository -y ppa:webupd8team/java
#     apt-get -y update
#     echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections
#     echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections
#     apt-get -y install oracle-java7-installer
# 	java -version
# }

install_java()
{
    if [ -f "jdk-8u291-linux-x64.tar.gz" ];
    then
        log "Java already downloaded"
        return
    fi

    log "Installing Java"
    RETRY=0
    MAX_RETRY=5
    while [ $RETRY -lt $MAX_RETRY ]; do
        log "Retry $RETRY: downloading jdk-8u291-linux-x64.tar.gz"
        wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" https://download.oracle.com/otn-pub/java/jdk/8u291-b10/d7fc238d0cbf4b0dac67be84580cfb4b/jdk-8u291-linux-x64.tar.gz
        if [ $? -ne 0 ]; then
            let RETRY=RETRY+1
        else
            break
        fi
    done
    if [ $RETRY -eq $MAX_RETRY ]; then
        log "Failed to download jdk-8u291-linux-x64.tar.gz"
        exit 1
    fi

    tar xzf jdk-8u291-linux-x64.tar.gz -C /var/lib
    export JAVA_HOME=/var/lib/jdk1.8.0_291
    export PATH=$PATH:$JAVA_HOME/bin
    log "JAVA_HOME: $JAVA_HOME"
    log "PATH: $PATH"

    java -version
    if [ $? -ne 0 ]; then
        log "Java installation failed"
        exit 1
    fi
}

# Expand a list of successive IP range defined by a starting address prefix (e.g. 10.0.0.1) and the number of machines in the range
# 10.0.0.1-3 would be converted to "10.0.0.10 10.0.0.11 10.0.0.12"

expand_ip_range_for_server_properties() {
    IFS='-' read -a HOST_IPS <<< "$1"
    for (( n=0 ; n<("${HOST_IPS[1]}"+0) ; n++))
    do
        echo "server.$(expr ${n} + 1)=${HOST_IPS[0]}${n}:2888:3888" >> apache-zookeeper-3.5.9/conf/zoo.cfg
    done
}

function join { local IFS="$1"; shift; echo "$*"; }

expand_ip_range() {
    IFS='-' read -a HOST_IPS <<< "$1"

    declare -a EXPAND_STATICIP_RANGE_RESULTS=()

    for (( n=0 ; n<("${HOST_IPS[1]}"+0) ; n++))
    do
        HOST="${HOST_IPS[0]}${n}:${ZOOKEEPER_PORT}"
                EXPAND_STATICIP_RANGE_RESULTS+=($HOST)
    done

    echo "${EXPAND_STATICIP_RANGE_RESULTS[@]}"
}

# Install Zookeeper - can expose zookeeper version
install_zookeeper()
{
	mkdir -p /var/lib/zookeeper
	cd /var/lib/zookeeper
	wget "http://mirrors.ukfast.co.uk/sites/ftp.apache.org/zookeeper/zookeeper-3.5.9/apache-zookeeper-3.5.9.tar.gz"
	tar -xvf "apache-zookeeper-3.5.9.tar.gz"

	touch apache-zookeeper-3.5.9/conf/zoo.cfg

	echo "tickTime=2000" >> apache-zookeeper-3.5.9/conf/zoo.cfg
	echo "dataDir=/var/lib/zookeeper" >> apache-zookeeper-3.5.9/conf/zoo.cfg
	echo "clientPort=2181" >> apache-zookeeper-3.5.9/conf/zoo.cfg
	echo "initLimit=5" >> apache-zookeeper-3.5.9/conf/zoo.cfg
	echo "syncLimit=2" >> apache-zookeeper-3.5.9/conf/zoo.cfg
	# OLD Test echo "server.1=${ZOOKEEPER_IP_PREFIX}:2888:3888" >> zookeeper-3.4.6/conf/zoo.cfg
	$(expand_ip_range_for_server_properties "${ZOOKEEPER_IP_PREFIX}-${INSTANCE_COUNT}")

	echo $(($1+1)) >> /var/lib/zookeeper/myid

	apache-zookeeper-3.5.9/bin/zkServer.sh start
}

# Setup datadisks
setup_datadisks() {

	MOUNTPOINT="/datadisks/disk1"

	# Move database files to the striped disk
	if [ -L ${KAFKADIR} ];
	then
		logger "Symbolic link from ${KAFKADIR} already exists"
		echo "Symbolic link from ${KAFKADIR} already exists"
	else
		logger "Moving  data to the $MOUNTPOINT/kafkadir"
		echo "Moving Kafka data to the $MOUNTPOINT/kafkadir"
		mv ${KAFKADIR} $MOUNTPOINT/kafkadir

		# Create symbolic link so that configuration files continue to use the default folders
		logger "Create symbolic link from ${KAFKADIR} to $MOUNTPOINT/kafkadir"
		ln -s $MOUNTPOINT/kafkadir ${KAFKADIR}
	fi
}

# Install kafka
install_kafka()
{
	cd /usr/local
	name=kafka
	version=${KF_VERSION}
	#this Kafka version is prefix same used for all versions
	kafkaversion=2.10
	description="Apache Kafka is a distributed publish-subscribe messaging system."
	url="https://kafka.apache.org/"
	arch="all"
	section="misc"
	license="Apache Software License 2.0"
	package_version="-1"
	src_package="kafka_${kafkaversion}-${version}.tgz"
	download_url=http://mirror.sdunix.com/apache/kafka/${version}/${src_package}

	rm -rf kafka
	mkdir -p kafka
	cd kafka
	#_ MAIN _#
	if [[ ! -f "${src_package}" ]]; then
	  wget ${download_url}
	fi
	tar zxf ${src_package}
	cd kafka_${kafkaversion}-${version}

	sed -r -i "s/(broker.id)=(.*)/\1=${BROKER_ID}/g" config/server.properties
	sed -r -i "s/(zookeeper.connect)=(.*)/\1=$(join , $(expand_ip_range "${ZOOKEEPER_IP_PREFIX}-${INSTANCE_COUNT}"))/g" config/server.properties
	sed -r -i "s/(log.dirs)=(.*)/\1=${KAFKADIR}/g" config/server.properties

	chmod u+x /usr/local/kafka/kafka_${kafkaversion}-${version}/bin/kafka-server-start.sh
	/usr/local/kafka/kafka_${kafkaversion}-${version}/bin/kafka-server-start.sh /usr/local/kafka/kafka_${kafkaversion}-${version}/config/server.properties &
}

# Primary Install Tasks
#########################
#NOTE: These first three could be changed to run in parallel
#      Future enhancement - (export the functions and use background/wait to run in parallel)

#Install Oracle Java
#------------------------
install_java

if [ ${ZOOKEEPER1KAFKA0} -eq "1" ];
then
	#
	#Install zookeeper
	#-----------------------
	install_zookeeper
else
	#
	#Install kafka
	#-----------------------
	mkdir ${KAFKADIR}
	setup_datadisks
	install_kafka
fi


#!/bin/bash

REMOTEMYSQLIP=$1

apt-get -y update

#no password prompt while installing mysql server
export DEBIAN_FRONTEND=noninteractive

#install php mysql apache
apt-get -y install apache2 php5 libapache2-mod-php5 mysql-server libapache2-mod-auth-mysql php5-mysql

#php test file
cat > /var/www/html/info.php <<EOF
<?php
phpinfo();
?>
EOF

#mysql connection test file
cat > /var/www/html/mysql.php <<EOF
<?php
\$link = mysql_connect('localhost', 'root', '');
if (!\$link) {
    die('Could not connect:' . mysql_error());
}
echo 'Connected sucessfully';
?>
EOF

cat > /var/www/html/remotemysql.php <<EOF
<?php
\$link = mysql_connect('$REMOTEMYSQLIP', 'root', '');
if (!\$link) {
    die('Could not connect:' . mysql_error());
}
echo 'Connected sucessfully';
?>
EOF


#!/bin/bash

LAPIP=$1

apt-get -y update

#no password prompt while installing mysql server
export DEBIAN_FRONTEND=noninteractive

#install mysql server
apt-get -y install mysql-server
cp -p /etc/mysql/my.cnf /etc/mysql/my.cnf.bak
sed -i 's/\(bind-address\)/#\1/' /etc/mysql/my.cnf
service mysql restart
#allow $LAPIP to access
mysql -u root -e "use mysql;grant all privileges on *.* to 'root'@'$LAPIP';flush privileges"


#!/bin/bash

apt-get -y update

#no password prompt while installing neo4j server
export DEBIAN_FRONTEND=noninteractive

#install php apache
apt-get -y install apache2

apt-get -y install php

apt-get -y install libapache2-mod-php

#install composer
#curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer
#curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/var/www/html
#echo "starting to install composer"
#php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
#php -r "if (hash_file('SHA384', 'composer-setup.php') === '070854512ef404f16bac87071a6db9fd9721da1684cd4589b1196c3faf71b9a2682e2311b36a5079825e155ac7ce150d') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
#php composer-setup.php
#php -r "unlink('composer-setup.php');"
#echo "Composer is installed"
curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

#php test file
cat > /var/www/html/info.php <<EOF
<?php
phpinfo();
?>
EOF

#neo4j code test
#creating the composer.json file which uses the neoclient
cat > /var/www/html/composer.json <<EOF
{
  "require": {
    "neoxygen/neoclient":"~2.1"
  }
}
EOF

#creating the neo4jtest php file
cat > /var/www/html/neo4jtest.php <<EOF
<?php

require_once 'vendor/autoload.php';

use Neoxygen\NeoClient\ClientBuilder;

\$client = ClientBuilder::create()
  ->addConnection('default', 'http', '10.0.0.10', 7474,true,'neo4j','neo4j')
  ->build();

if (!\$client) {
    die('Could not connect with neo4j database');
}
echo 'Connected sucessfully';
EOF

echo "everything installed successfully, lets install composer dependecies"

#composer install
cd /var/www/html
composer install


#!/bin/bash

wget -O - http://debian.neo4j.org/neotechnology.gpg.key | apt-key add -

echo 'deb http://debian.neo4j.org/repo stable/' > /etc/apt/sources.list.d/neo4j.list

apt-get -y update
#no password prompt while installing neo4j server
export DEBIAN_FRONTEND=noninteractive

#install java
apt-get install -y python-software-properties debconf-utils
add-apt-repository -y ppa:webupd8team/java
apt-get update
echo "oracle-java8-installer shared/accepted-oracle-license-v1-1 select true" | debconf-set-selections
apt-get install -y oracle-java8-installer

#install neo4j server
apt-get -y install neo4j
#make a copy of the config file
cp -p /etc/neo4j/neo4j.conf /etc/neo4j/neo4j.conf.bak
#open the http access at port 7474 to apache node
sed -i -e '/dbms.connector.http.address/s/^#//' /etc/neo4j/neo4j.conf
service neo4j restart