#!/bin/bash

echo -e "Arguments:
[0] - Used by Bash (script filename)
[1] - Base directory
[2] - Filename type (maximum two values)
[3] - Ignored files or folders (optional; use "\""./<directory_name>"\"")
"

# Separate $2 value (filename types) if it has a comma
if [[ "$2" == *","* ]];
then
    string="$2"

    str_value=${string#*,}
    str_value2=${string%%,*}
else
    str_value="$2"
    str_value2="$2"
fi

# Do not run script if there are no given arguments.
if [[ "$1" == "" ]] || [[ "$2" == "" ]];
then
    echo "No arguments given. Please specify minimum two arguments."
    exit 1
fi

echo "Changed files:"

IFS=$'\n'; set -f
for fname in $(find $1 -type f -name "*$str_value2" -or -name "*$str_value")
do
    ignored_files="$(echo "$3" | tr "," "\n")"

    str="${fname}"
    value=${str%/*} # If the base directory is `.`, check in all directories for the ignored filenames

    for files in $ignored_files
    do
        if [ "${fname}" == "$value/$files" ] || [ "$value" == "$files" ];
        then
            continue 2
        fi
    done

    #echo ${fname}
    new_fname=$(echo "${fname}" | tr ' ' '_')
    #echo "      ${new_fname}"
    new_fname=$(echo "${new_fname}" | tr '[:upper:]' '[:lower:]')
    #echo "      ${new_fname}"
    new_fname=$(echo "${new_fname}" | tr '-' '_')
    #echo "      ${new_fname}"
    if [ "${fname}" != "${new_fname}" ]
    then
        echo "      ${fname} --> ${new_fname}"
        git "mv" "${fname}" "${new_fname}" # Requires you to be in version control
    fi
done
unset IFS; set +f


#!/usr/bin/env bash

ZIG_TEST='zig build test'

# -fsummary                    Print the build summary, even on success
# -freference-trace            Reference trace should be shown per compile error
Args='-fsummary -freference-trace'

## Test all algorithms

# Math
$ZIG_TEST -Dalgorithm=math/ceil $Args
$ZIG_TEST -Dalgorithm=math/crt $Args
$ZIG_TEST -Dalgorithm=math/primes $Args
$ZIG_TEST -Dalgorithm=math/fibonacci $Args
$ZIG_TEST -Dalgorithm=math/factorial $Args
$ZIG_TEST -Dalgorithm=math/euclidianGCDivisor $Args
$ZIG_TEST -Dalgorithm=math/gcd $Args

# Data Structures
$ZIG_TEST -Dalgorithm=ds/linkedlist $Args
$ZIG_TEST -Dalgorithm=ds/lrucache $Args

# Dynamic Programming

## Sort
$ZIG_TEST -Dalgorithm=sort/quicksort $Args
$ZIG_TEST -Dalgorithm=sort/bubblesort $Args
$ZIG_TEST -Dalgorithm=sort/radixsort $Args
$ZIG_TEST -Dalgorithm=sort/mergesort $Args
$ZIG_TEST -Dalgorithm=sort/insertsort $Args

## Search
$ZIG_TEST -Dalgorithm=search/bSearchTree $Args
$ZIG_TEST -Dalgorithm=search/rb $Args

## Threads
$ZIG_TEST -Dalgorithm=threads/threadpool $Args

## Web
$ZIG_TEST -Dalgorithm=web/httpClient $Args
$ZIG_TEST -Dalgorithm=web/httpServer $Args
$ZIG_TEST -Dalgorithm=web/tls1_3 $Args

## Add more...


#!/bin/bash
echo "cleaning up the generated files..."
find . -type f \( -name "*.js" -o -name "*.d.ts" -o -name "*.js.map" -o -name "*.d.ts.map" \) -print | grep '/lib/\|/test/\|/bin/' | grep -v 'node_modules' | xargs -I{} rm {}
echo "cleaning done!"


for TAG in "$@"
do
   git push origin :refs/tags/$TAG
done


# current openqasm commit: 429781bb9c95ef15944861f306ac6b9e4ff0abf0

# This script rebuilds the parsers from the source g4 files. Use for
# development when making changes to the grammar.

if [ ! -f "antlr-4.9.2-complete.jar" ]; then
    curl -O https://www.antlr.org/download/antlr-4.9.2-complete.jar
fi

cp antlr-4.9.2-complete.jar /usr/local/lib/antlr-4.9.2-complete.jar

export CLASSPATH=".:/usr/local/lib/antlr-4.9.2-complete.jar:$CLASSPATH"
alias antlr4='java -Xmx500M -cp "/usr/local/lib/antlr-4.9.2-complete.jar:$CLASSPATH" org.antlr.v4.Tool'
alias grun='java -Xmx500M -cp "/usr/local/lib/antlr-4.9.2-complete.jar:$CLASSPATH" org.antlr.v4.gui.TestRig'

cd src/braket/default_simulator/openqasm/parser || exit
antlr4 -Dlanguage=Python3 -visitor BraketPragmasLexer.g4 BraketPragmasParser.g4 -o generated
antlr4 -Dlanguage=Python3 -visitor qasm3Lexer.g4 qasm3Parser.g4 -o generated
cd generated || exit
rm BraketPragmasParser.interp BraketPragmasParser.tokens BraketPragmasLexer.interp \
  BraketPragmasLexer.tokens BraketPragmasParserListener.py qasm3Lexer.interp \
  qasm3Lexer.tokens qasm3Parser.interp qasm3Parser.tokens qasm3ParserListener.py
cd ../../../../../.. || exit


# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

#!/bin/sh

set -e

REPOSITORY_ROOT="$(git rev-parse --show-toplevel)"
WORKING_BRANCH="$(git rev-parse --abbrev-ref HEAD)"
HAS_UNCOMMITTED_CHANGES="$(git status --porcelain)"

# Remove any old data from previous executions
rm -rf "$REPOSITORY_ROOT/test/.benchmarks"
# Stash uncommitted changes (if any)
if [ -n "$HAS_UNCOMMITTED_CHANGES" ]; then git stash -u; fi
git checkout main
# Execute performance tests against the latest commit on the main branch
pytest --benchmark-autosave --benchmark-only --benchmark-timer='time.process_time' --benchmark-warmup='on' --benchmark-warmup-iterations=100 performance
# Stash the performance test execution results and switch back to the working branch
git stash -u && git checkout $WORKING_BRANCH
# Retrieve the stashed performance test execution results for the main branch (to compare against)
git stash pop
# Retrieve the uncommitted changes which had been stashed (if any)
if [ -n "$HAS_UNCOMMITTED_CHANGES" ]; then git stash pop; fi
# Execute the performance tests and compare the results against the main branch.
# Fails if there >= 5% increase in the minimum execution time of any test
pytest --benchmark-autosave --benchmark-only --benchmark-timer='time.process_time' --benchmark-warmup='on' --benchmark-warmup-iterations=100 --benchmark-compare --benchmark-compare-fail=min:5% performance
# Cleanup benchmark metadata
rm -rf "$REPOSITORY_ROOT/test/.benchmarks"


#!/usr/bin/env bash

# This script shows how to build the Docker image and push it to ECR to be ready for use
# by Braket.

# The argument to this script is the image name. This will be used as the image on the local
# machine and combined with the account and region to form the repository name for ECR.
image=$1

if [ "$image" == "" ]
then
    echo "Usage: $0 <image-name>"
    exit 1
fi

# Get the account number associated with the current IAM credentials
account=$(aws sts get-caller-identity --query Account --output text)

if [ $? -ne 0 ]
then
    exit 255
fi

# Get the region defined in the current configuration (default to us-west-2 if none defined)
region=$(aws configure get region)
region=${region:-us-west-2}

fullname="${account}.dkr.ecr.${region}.amazonaws.com/${image}:latest"

# If the repository doesn't exist in ECR, create it.

desc_output=$(aws ecr describe-repositories --repository-names ${image} 2>&1)

if [ $? -ne 0 ]
then
    if echo ${desc_output} | grep -q RepositoryNotFoundException
    then
        aws ecr create-repository --repository-name "${image}" > /dev/null
    else
        >&2 echo ${desc_output}
    fi
fi

aws ecr get-login-password --region us-west-2 | docker login -u AWS --password-stdin 292282985366.dkr.ecr.us-west-2.amazonaws.com
aws ecr get-login-password --region ${region} | docker login -u AWS --password-stdin ${account}.dkr.ecr.${region}.amazonaws.com

# Build the docker image locally with the image name and then push it to ECR
# with the full name.

docker build  -t ${image} -f dockerfile .
docker tag ${image} ${fullname}

docker push ${fullname}


# This copied this file from https://github.com/aws/aws-codebuild-docker-images/tree/master/local_builds, and have modified a bit as per the use case here.

#!/bin/bash

COMPOSE_HTTP_TIMEOUT=120

function allOSRealPath() {
    if isOSWindows
    then
        path=""
        case $1 in
            .* ) path="$PWD/${1#./}" ;;
            /* ) path="$1" ;;
            *  ) path="/$1" ;;
        esac

        echo "/$path" | sed -e 's/\\/\//g' -e 's/://' -e 's/./\U&/3'
    else
        case $1 in
            /* ) echo "$1"; exit;;
            *  ) echo "$PWD/${1#./}"; exit;;
        esac
    fi
}

function isOSWindows() {
    if [ $OSTYPE == "msys" ]
    then
        return 0
    else
        return 1
    fi
}

function usage {
    echo "usage: codebuild_build.sh [-i image_name] [-a artifact_output_directory] [options]"
    echo "Required:"
    echo "  -i        Used to specify the customer build container image."
    echo "  -a        Used to specify an artifact output directory."
    echo "Options:"
    echo "  -l IMAGE  Used to override the default local agent image."
    echo "  -r        Used to specify a report output directory."
    echo "  -s        Used to specify source information. Defaults to the current working directory for primary source."
    echo "               * First (-s) is for primary source"
    echo "               * Use additional (-s) in <sourceIdentifier>:<sourceLocation> format for secondary source"
    echo "               * For sourceIdentifier, use a value that is fewer than 128 characters and contains only alphanumeric characters and underscores"
    echo "  -c        Use the AWS configuration and credentials from your local host. This includes ~/.aws and any AWS_* environment variables."
    echo "  -p        Used to specify the AWS CLI Profile."
    echo "  -b FILE   Used to specify a buildspec override file. Defaults to buildspec.yml in the source directory."
    echo "  -m        Used to mount the source directory to the customer build container directly."
    echo "  -d        Used to run the build container in docker privileged mode."
    echo "  -e FILE   Used to specify a file containing environment variables."
    echo "            (-e) File format expectations:"
    echo "               * Each line is in VAR=VAL format"
    echo "               * Lines beginning with # are processed as comments and ignored"
    echo "               * Blank lines are ignored"
    echo "               * File can be of type .env or .txt"
    echo "               * There is no special handling of quotation marks, meaning they will be part of the VAL"
    exit 1
}

image_flag=false
artifact_flag=false
awsconfig_flag=false
mount_src_dir_flag=false
docker_privileged_mode_flag=false

while getopts "cmdi:a:r:s:b:e:l:p:h" opt; do
    case $opt in
        i  ) image_flag=true; image_name=$OPTARG;;
        a  ) artifact_flag=true; artifact_dir=$OPTARG;;
        r  ) report_dir=$OPTARG;;
        b  ) buildspec=$OPTARG;;
        c  ) awsconfig_flag=true;;
        m  ) mount_src_dir_flag=true;;
        d  ) docker_privileged_mode_flag=true;;
        s  ) source_dirs+=("$OPTARG");;
        e  ) environment_variable_file=$OPTARG;;
        l  ) local_agent_image=$OPTARG;;
        p  ) aws_profile=$OPTARG;;
        h  ) usage; exit;;
        \? ) echo "Unknown option: -$OPTARG" >&2; exit 1;;
        :  ) echo "Missing option argument for -$OPTARG" >&2; exit 1;;
        *  ) echo "Invalid option: -$OPTARG" >&2; exit 1;;
    esac
done

echo "${buildspec:-empty}"

if  ! $image_flag
then
    echo "The image name flag (-i) must be included for a build to run" >&2
fi

if  ! $artifact_flag
then
    echo "The artifact directory (-a) must be included for a build to run" >&2
fi

if  ! $image_flag ||  ! $artifact_flag
then
    exit 1
fi

docker_command="docker run -i "
if isOSWindows
then
    docker_command+="-v //var/run/docker.sock:/var/run/docker.sock -e "
else
    docker_command+="-v /var/run/docker.sock:/var/run/docker.sock -e "
fi

docker_command+="\"IMAGE_NAME=$image_name\" -e \
    \"ARTIFACTS=$(allOSRealPath "$artifact_dir")\""

if [ -n "$report_dir" ]
then
    docker_command+=" -e \"REPORTS=$(allOSRealPath "$report_dir")\""
fi

if [ -z "$source_dirs" ]
then
    docker_command+=" -e \"SOURCE=$(allOSRealPath "$PWD")\""
else
    for index in "${!source_dirs[@]}"; do
        if [ $index -eq 0 ]
        then
            docker_command+=" -e \"SOURCE=$(allOSRealPath "${source_dirs[$index]}")\""
        else
            identifier=${source_dirs[$index]%%:*}
            src_dir=$(allOSRealPath "${source_dirs[$index]#*:}")

            docker_command+=" -e \"SECONDARY_SOURCE_$index=$identifier:$src_dir\""
        fi
    done
fi

if [ -n "$buildspec" ]
then
    docker_command+=" -e \"BUILDSPEC=$(allOSRealPath "$buildspec")\""
fi

if [ -n "$environment_variable_file" ]
then
    environment_variable_file_path=$(allOSRealPath "$environment_variable_file")
    environment_variable_file_dir=$(dirname "$environment_variable_file_path")
    environment_variable_file_basename=$(basename "$environment_variable_file")
    docker_command+=" -v \"$environment_variable_file_dir:/LocalBuild/envFile/\" -e \"ENV_VAR_FILE=$environment_variable_file_basename\""
fi

if [ -n "$local_agent_image" ]
then
    docker_command+=" -e \"LOCAL_AGENT_IMAGE_NAME=$local_agent_image\""
fi

if $awsconfig_flag
then
    if [ -d "$HOME/.aws" ]
    then
        configuration_file_path=$(allOSRealPath "$HOME/.aws")
        docker_command+=" -e \"AWS_CONFIGURATION=$configuration_file_path\""
    else
        docker_command+=" -e \"AWS_CONFIGURATION=NONE\""
    fi

    if [ -n "$aws_profile" ]
    then
        docker_command+=" -e \"AWS_PROFILE=$aws_profile\""
    fi

    docker_command+="$(env | grep ^AWS_ | while read -r line; do echo " -e \"$line\""; done )"
fi

if $mount_src_dir_flag
then
    docker_command+=" -e \"MOUNT_SOURCE_DIRECTORY=TRUE\""
fi

if $docker_privileged_mode_flag
then
    docker_command+=" -e \"DOCKER_PRIVILEGED_MODE=TRUE\""
fi

if isOSWindows
then
    docker_command+=" -e \"INITIATOR=$USERNAME\""
else
    docker_command+=" -e \"INITIATOR=$USER\""
fi

if [ -n "$local_agent_image" ]
then
    docker_command+=" $local_agent_image"
else
    docker_command+=" public.ecr.aws/codebuild/local-builds:latest"
fi

# Note we do not expose the AWS_SECRET_ACCESS_KEY or the AWS_SESSION_TOKEN
exposed_command=$docker_command
secure_variables=( "AWS_SECRET_ACCESS_KEY=" "AWS_SESSION_TOKEN=")
for variable in "${secure_variables[@]}"
do
    exposed_command="$(echo $exposed_command | sed "s/\($variable\)[^ ]*/\1********\"/")"
done

echo "Build Command:"
echo ""
echo $exposed_command
echo ""

eval $docker_command


#!/usr/bin/env bash

cd "$(dirname "$0")"
k8sDirPrefix="./k8s-deployment-manifest-templates/deployment-mode/daemonset/container-insights-monitoring"
ecsDirPrefix="./ecs-task-definition-templates/deployment-mode/daemon-service/cwagent-ecs-instance-metric"

newK8sVersion="k8s/1.3.0"
agentVersion="amazon/cloudwatch-agent:1.247355.0b252062"
fluentdVersion="fluent/fluentd-kubernetes-daemonset:v1.7.3-debian-cloudwatch-1.0"
fluentBitVersion="amazon/aws-for-fluent-bit:2.10.0"

k8sPrometheusDirPrefix="./k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus"
ecsPrometheusDirPrefix="./ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus"

# replace agent version for ECS Prometheus
sed -i'.bak' "s|amazon/cloudwatch-agent:[0-9]*\.[0-9]*\.[0-9a-z]*\(-prometheus\)\?|${agentVersion}|g" ${ecsPrometheusDirPrefix}/cwagent-prometheus-task-definition.json
rm ${ecsPrometheusDirPrefix}/cwagent-prometheus-task-definition.json.bak
sed -i'.bak' "s|amazon/cloudwatch-agent:[0-9]*\.[0-9]*\.[0-9a-z]*\(-prometheus\)\?|${agentVersion}|g" ${ecsPrometheusDirPrefix}/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-awsvpc.yaml
rm ${ecsPrometheusDirPrefix}/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-awsvpc.yaml.bak
sed -i'.bak' "s|amazon/cloudwatch-agent:[0-9]*\.[0-9]*\.[0-9a-z]*\(-prometheus\)\?|${agentVersion}|g" ${ecsPrometheusDirPrefix}/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-bridge-host.yaml
rm ${ecsPrometheusDirPrefix}/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-bridge-host.yaml.bak

# replace agent and k8s version for K8s Prometheus
sed -i'.bak' "s|k8s/[0-9]*\.[0-9]*\.[0-9a-z]*\(-prometheus\)\?|${newK8sVersion}|g;s|amazon/cloudwatch-agent:[0-9]*\.[0-9]*\.[0-9a-z]*\(-prometheus\)\?|${agentVersion}|g" ${k8sPrometheusDirPrefix}/prometheus-eks.yaml
rm ${k8sPrometheusDirPrefix}/prometheus-eks.yaml.bak
sed -i'.bak' "s|k8s/[0-9]*\.[0-9]*\.[0-9a-z]*\(-prometheus\)\?|${newK8sVersion}|g;s|amazon/cloudwatch-agent:[0-9]*\.[0-9]*\.[0-9a-z]*\(-prometheus\)\?|${agentVersion}|g" ${k8sPrometheusDirPrefix}/prometheus-k8s.yaml
rm ${k8sPrometheusDirPrefix}/prometheus-k8s.yaml.bak

# replace agent version for ECS
sed -i'.bak' "s|amazon/cloudwatch-agent:[0-9]*\.[0-9]*\.[0-9a-z]*|${agentVersion}|g" ${ecsDirPrefix}/cwagent-ecs-instance-metric.json
rm ${ecsDirPrefix}/cwagent-ecs-instance-metric.json.bak

sed -i'.bak' "s|amazon/cloudwatch-agent:[0-9]*\.[0-9]*\.[0-9a-z]*|${agentVersion}|g" ${ecsDirPrefix}/cloudformation-quickstart/cwagent-ecs-instance-metric-cfn.json
rm ${ecsDirPrefix}/cloudformation-quickstart/cwagent-ecs-instance-metric-cfn.json.bak

# replace agent, fluentD and fluent-bit version for K8s
sed -i'.bak' "s|k8s/[0-9]*\.[0-9]*\.[0-9a-z]*|${newK8sVersion}|g;s|amazon/cloudwatch-agent:[0-9]*\.[0-9]*\.[0-9a-z]*|${agentVersion}|g" ${k8sDirPrefix}/cwagent/cwagent-daemonset.yaml
rm ${k8sDirPrefix}/cwagent/cwagent-daemonset.yaml.bak

sed -i'.bak' "s|k8s/[0-9]*\.[0-9]*\.[0-9a-z]*|${newK8sVersion}|g;s|fluent/fluentd-kubernetes-daemonset:.*|${fluentdVersion}|g" ${k8sDirPrefix}/fluentd/fluentd.yaml
rm ${k8sDirPrefix}/fluentd/fluentd.yaml.bak

sed -i'.bak' "s|k8s/[0-9]*\.[0-9]*\.[0-9a-z]*|${newK8sVersion}|g;s|amazon/aws-for-fluent-bit.*|${fluentBitVersion}|g" ${k8sDirPrefix}/fluent-bit/fluent-bit.yaml
rm ${k8sDirPrefix}/fluent-bit/fluent-bit.yaml.bak

sed -i'.bak' "s|k8s/[0-9]*\.[0-9]*\.[0-9a-z]*|${newK8sVersion}|g;s|amazon/aws-for-fluent-bit.*|${fluentBitVersion}|g" ${k8sDirPrefix}/fluent-bit/fluent-bit-compatible.yaml
rm ${k8sDirPrefix}/fluent-bit/fluent-bit-compatible.yaml.bak

# generate quickstart manifest for K8s
OUTPUT=${k8sDirPrefix}/quickstart/cwagent-fluentd-quickstart.yaml
OUTPUT_FLUENT_BIT=${k8sDirPrefix}/quickstart/cwagent-fluent-bit-quickstart.yaml

cat ${k8sDirPrefix}/cloudwatch-namespace.yaml >${OUTPUT}
echo -e "\n---\n" >>${OUTPUT}
cat ${k8sDirPrefix}/cwagent/cwagent-serviceaccount.yaml >>${OUTPUT}
echo -e "\n---\n" >>${OUTPUT}
cat ${k8sDirPrefix}/cwagent/cwagent-configmap.yaml | sed "s|\"logs|\"agent\": {\\
        \"region\": \"{{region_name}}\"\\
      },\\
      \"logs|g" >>${OUTPUT}
echo -e "\n---\n" >>${OUTPUT}
cat ${k8sDirPrefix}/cwagent/cwagent-daemonset.yaml >>${OUTPUT}
echo -e "\n---\n" >>${OUTPUT}
cat ${k8sDirPrefix}/fluentd/fluentd-configmap.yaml >>${OUTPUT}
echo -e "\n---\n" >>${OUTPUT}
cat ${k8sDirPrefix}/fluentd/fluentd.yaml >>${OUTPUT}

cat ${k8sDirPrefix}/cloudwatch-namespace.yaml >${OUTPUT_FLUENT_BIT}
echo -e "\n---\n" >>${OUTPUT_FLUENT_BIT}
cat ${k8sDirPrefix}/cwagent/cwagent-serviceaccount.yaml >>${OUTPUT_FLUENT_BIT}
echo -e "\n---\n" >>${OUTPUT_FLUENT_BIT}
cat ${k8sDirPrefix}/cwagent/cwagent-configmap.yaml | sed "s|\"logs|\"agent\": {\\
        \"region\": \"{{region_name}}\"\\
      },\\
      \"logs|g" >>${OUTPUT_FLUENT_BIT}
echo -e "\n---\n" >>${OUTPUT_FLUENT_BIT}
cat ${k8sDirPrefix}/cwagent/cwagent-daemonset.yaml >>${OUTPUT_FLUENT_BIT}
echo -e "\n---\n" >>${OUTPUT_FLUENT_BIT}
cat ${k8sDirPrefix}/fluent-bit/fluent-bit-configmap.yaml >>${OUTPUT_FLUENT_BIT}
echo -e "\n---\n" >>${OUTPUT_FLUENT_BIT}
cat ${k8sDirPrefix}/fluent-bit/fluent-bit.yaml >>${OUTPUT_FLUENT_BIT}


#!/usr/bin/env bash

cd "$(dirname "$0")"

newversion="k8s\/1.0.1"

sed -i'.bak' "s/k8s\/[0-9]*\.[0-9]*\.[0-9]*/$newversion/g" ./cwagent-kubernetes-monitoring/cwagent-daemonset.yaml
rm ./cwagent-kubernetes-monitoring/cwagent-daemonset.yaml.bak

sed -i'.bak' "s/k8s\/[0-9]*\.[0-9]*\.[0-9]*/$newversion/g" ./fluentd/fluentd.yaml
rm ./fluentd/fluentd.yaml.bak

OUTPUT=./quickstart/cwagent-fluentd-quickstart.yaml

cat ./cloudwatch-namespace.yaml >${OUTPUT}
echo -e "\n---\n" >>${OUTPUT}
cat ./cwagent-kubernetes-monitoring/cwagent-serviceaccount.yaml >>${OUTPUT}
echo -e "\n---\n" >>${OUTPUT}
cat ./cwagent-kubernetes-monitoring/cwagent-configmap.yaml | sed "s|\"logs|\"agent\": {\\
        \"region\": \"{{region_name}}\"\\
      },\\
      \"logs|g" >>${OUTPUT}
echo -e "\n---\n" >>${OUTPUT}
cat ./cwagent-kubernetes-monitoring/cwagent-daemonset.yaml >>${OUTPUT}
echo -e "\n---\n" >>${OUTPUT}
cat ./fluentd/fluentd-configmap.yaml >>${OUTPUT}
echo -e "\n---\n" >>${OUTPUT}
cat ./fluentd/fluentd.yaml >>${OUTPUT}


#!/usr/bin/env bash
set -e
set -u
set -x
set -o pipefail
echo "****************************************"
echo "Creating tar file for Mac OS X ${ARCH}  "
echo "****************************************"

AGENT_VERSION=$(cat ${PREPKGPATH}/CWAGENT_VERSION | sed -e "s/-/+/g")
echo "BUILD_SPACE: ${BUILD_SPACE}    agent_version: ${AGENT_VERSION}  pre-package location:${PREPKGPATH}"

mkdir -p ${BUILD_SPACE}/bin/darwin/${ARCH}/

echo "Creating darwin folders"
MACHINE_ROOT="/opt/aws/amazon-cloudwatch-agent/"
BUILD_ROOT="${BUILD_SPACE}/private/darwin_${ARCH}"
TAR_NAME="amazon-cloudwatch-agent.tar.gz"

echo "Creating darwin workspace"
mkdir -p ${BUILD_ROOT}${MACHINE_ROOT}logs
mkdir -p ${BUILD_ROOT}${MACHINE_ROOT}bin
mkdir -p ${BUILD_ROOT}${MACHINE_ROOT}etc
mkdir -p ${BUILD_ROOT}${MACHINE_ROOT}etc/amazon-cloudwatch-agent.d
mkdir -p ${BUILD_ROOT}${MACHINE_ROOT}var
mkdir -p ${BUILD_ROOT}${MACHINE_ROOT}doc
mkdir -p ${BUILD_ROOT}/Library/LaunchDaemons

############################# create the symbolic links
# log
mkdir -p ${BUILD_ROOT}/var/log/amazon
ln -f -s /opt/aws/amazon-cloudwatch-agent/logs ${BUILD_ROOT}/var/log/amazon/amazon-cloudwatch-agent

echo "Copying application files"
cp ${PREPKGPATH}/LICENSE ${BUILD_ROOT}${MACHINE_ROOT}
cp ${PREPKGPATH}/NOTICE ${BUILD_ROOT}${MACHINE_ROOT}
cp ${PREPKGPATH}/THIRD-PARTY-LICENSES ${BUILD_ROOT}${MACHINE_ROOT}
cp ${PREPKGPATH}/RELEASE_NOTES ${BUILD_ROOT}${MACHINE_ROOT}
cp ${PREPKGPATH}/CWAGENT_VERSION ${BUILD_ROOT}${MACHINE_ROOT}bin/
cp ${PREPKGPATH}/amazon-cloudwatch-agent ${BUILD_ROOT}${MACHINE_ROOT}bin/
cp ${PREPKGPATH}/amazon-cloudwatch-agent-ctl ${BUILD_ROOT}${MACHINE_ROOT}bin/
cp ${PREPKGPATH}/config-translator ${BUILD_ROOT}${MACHINE_ROOT}bin/
cp ${PREPKGPATH}/config-downloader ${BUILD_ROOT}${MACHINE_ROOT}bin/
cp ${PREPKGPATH}/amazon-cloudwatch-agent-config-wizard ${BUILD_ROOT}${MACHINE_ROOT}bin/
cp ${PREPKGPATH}/start-amazon-cloudwatch-agent ${BUILD_ROOT}${MACHINE_ROOT}bin/
cp ${PREPKGPATH}/common-config.toml ${BUILD_ROOT}${MACHINE_ROOT}etc/
cp ${PREPKGPATH}/amazon-cloudwatch-agent-schema.json ${BUILD_ROOT}${MACHINE_ROOT}doc/
cp ${PREPKGPATH}/com.amazon.cloudwatch.agent.plist ${BUILD_ROOT}/Library/LaunchDaemons/

echo "Setting permissions as required by launchd"
chmod 600 ${BUILD_ROOT}/Library/LaunchDaemons/*
chmod ug+rx ${BUILD_ROOT}${MACHINE_ROOT}bin/amazon-cloudwatch-agent
chmod ug+rx ${BUILD_ROOT}${MACHINE_ROOT}bin/amazon-cloudwatch-agent-ctl
chmod ug+rx ${BUILD_ROOT}${MACHINE_ROOT}bin/start-amazon-cloudwatch-agent

echo "Creating tar"
(
     cd ${BUILD_ROOT}
     tar -czf $TAR_NAME *
)

echo "Archive created at ${BUILD_ROOT}/${TAR_NAME}"

echo "Copying tarball to bin"
mv ${BUILD_ROOT}/${TAR_NAME} ${BUILD_SPACE}/bin/darwin/${ARCH}/${TAR_NAME}
ls -ltr ${BUILD_SPACE}/bin/darwin/${ARCH}/*.tar.gz


#!/usr/bin/env bash
echo "****************************************"
echo "Creating deb file for Debian Linux ${ARCH}"
echo "****************************************"
set -e

AGENT_VERSION=$(cat ${PREPKGPATH}/CWAGENT_VERSION)
BUILD_ROOT="${BUILD_SPACE}/private/linux_${ARCH}/debian"
echo "BUILD_SPACE: ${BUILD_SPACE}    agent_version: ${AGENT_VERSION}   pre-package location:${PREPKGPATH}"
echo "Creating debian folders"

mkdir -p ${BUILD_SPACE}/bin/linux/${ARCH}/
mkdir -p ${BUILD_ROOT}/bin
mkdir -p ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/logs
mkdir -p ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/var
mkdir -p ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d
mkdir -p ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin
mkdir -p ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/doc
mkdir -p ${BUILD_ROOT}/etc/init
mkdir -p ${BUILD_ROOT}/etc/systemd/system/

echo "Copying application files"
cp ${PREPKGPATH}/LICENSE ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/NOTICE ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/THIRD-PARTY-LICENSES ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/RELEASE_NOTES ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/CWAGENT_VERSION ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/
cp ${PREPKGPATH}/amazon-cloudwatch-agent ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/
cp ${PREPKGPATH}/amazon-cloudwatch-agent-ctl ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/
cp ${PREPKGPATH}/amazon-cloudwatch-agent.service ${BUILD_ROOT}/etc/systemd/system/
cp ${PREPKGPATH}/config-translator ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/
cp ${PREPKGPATH}/config-downloader ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/
cp ${PREPKGPATH}/amazon-cloudwatch-agent-config-wizard ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/
cp ${PREPKGPATH}/start-amazon-cloudwatch-agent ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/
cp ${PREPKGPATH}/common-config.toml ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/etc/
cp ${PREPKGPATH}/amazon-cloudwatch-agent.conf ${BUILD_ROOT}/etc/init/
cp ${PREPKGPATH}/amazon-cloudwatch-agent-schema.json ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/doc/

############################# create the symbolic links here to make them managed by dpkg
# bin
mkdir -p ${BUILD_ROOT}/usr/bin
ln -f -s /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl ${BUILD_ROOT}/usr/bin/amazon-cloudwatch-agent-ctl
# etc
mkdir -p ${BUILD_ROOT}/etc/amazon
ln -f -s /opt/aws/amazon-cloudwatch-agent/etc ${BUILD_ROOT}/etc/amazon/amazon-cloudwatch-agent
# log
mkdir -p ${BUILD_ROOT}/var/log/amazon
ln -f -s /opt/aws/amazon-cloudwatch-agent/logs ${BUILD_ROOT}/var/log/amazon/amazon-cloudwatch-agent
# pid
mkdir -p ${BUILD_ROOT}/var/run/amazon
ln -f -s /opt/aws/amazon-cloudwatch-agent/var ${BUILD_ROOT}/var/run/amazon/amazon-cloudwatch-agent

cp ${BUILD_SPACE}/packaging/debian/conffiles ${BUILD_ROOT}/
cp ${BUILD_SPACE}/packaging/debian/preinst ${BUILD_ROOT}/
cp ${BUILD_SPACE}/packaging/debian/prerm ${BUILD_ROOT}/
cp ${BUILD_SPACE}/packaging/debian/debian-binary ${BUILD_ROOT}/

chmod ug+rx ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent
chmod ug+rx ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl
chmod ug+rx ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/start-amazon-cloudwatch-agent

echo "Constructing the control file"
echo 'Package: amazon-cloudwatch-agent' >${BUILD_ROOT}/control
echo "Architecture: ${ARCH}" >>${BUILD_ROOT}/control
echo -n 'Version: ' >>${BUILD_ROOT}/control
echo -n ${AGENT_VERSION} >>${BUILD_ROOT}/control
echo '-1' >>${BUILD_ROOT}/control

cat ${BUILD_SPACE}/packaging/debian/control >>${BUILD_ROOT}/control

echo "Setting permissioning as required by debian"
cd ${BUILD_ROOT}/..
find ./debian -type d | xargs chmod 755
cd ~-

# the below permissioning is required by debian
cd ${BUILD_ROOT}
tar czf data.tar.gz opt etc usr var --owner=0 --group=0
cd ~-
cd ${BUILD_ROOT}
tar czf control.tar.gz control conffiles preinst prerm --owner=0 --group=0
cd ~-

echo "Creating the debian package"
echo "Constructing the deb packagage"
ar r ${BUILD_ROOT}/bin/amazon-cloudwatch-agent-${AGENT_VERSION}-1.deb ${BUILD_ROOT}/debian-binary
ar r ${BUILD_ROOT}/bin/amazon-cloudwatch-agent-${AGENT_VERSION}-1.deb ${BUILD_ROOT}/control.tar.gz
ar r ${BUILD_ROOT}/bin/amazon-cloudwatch-agent-${AGENT_VERSION}-1.deb ${BUILD_ROOT}/data.tar.gz

echo "Copying debian files to bin"

mv ${BUILD_ROOT}/bin/amazon-cloudwatch-agent-${AGENT_VERSION}-1.deb ${BUILD_SPACE}/bin/linux/${ARCH}/amazon-cloudwatch-agent.deb
ls -ltr ${BUILD_SPACE}/bin/linux/${ARCH}/*.deb


#!/usr/bin/env bash
echo "*************************************************"
echo "Creating rpm file for Amazon Linux and RHEL ${ARCH}"
echo "*************************************************"
set -e

SPEC_FILE="${PREPKGPATH}/amazon-cloudwatch-agent.spec"
BUILD_ROOT="${BUILD_SPACE}/private/linux_${ARCH}/rpm-build"
AGENT_VERSION=$(cat ${PREPKGPATH}/CWAGENT_VERSION | sed -e "s/-/+/g")

echo "BUILD_SPACE: ${BUILD_SPACE}  agent_version: ${AGENT_VERSION}  pre-package location:${PREPKGPATH}"

echo "Creating rpm-build workspace"

mkdir -p ${BUILD_SPACE}/bin/linux/${ARCH}/
mkdir -p ${BUILD_ROOT}/{RPMS,SRPMS,BUILD,SOURCES,SPECS,BUILDROOT}
mkdir -p ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/logs
mkdir -p ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/var
mkdir -p ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d
mkdir -p ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin
mkdir -p ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/doc
mkdir -p ${BUILD_ROOT}/SOURCES/etc/init
mkdir -p ${BUILD_ROOT}/SOURCES/etc/systemd/system/

echo "Copying application files"

cp ${PREPKGPATH}/LICENSE ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/NOTICE ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/THIRD-PARTY-LICENSES ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/RELEASE_NOTES ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/CWAGENT_VERSION ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/
cp ${PREPKGPATH}/amazon-cloudwatch-agent ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/
cp ${PREPKGPATH}/amazon-cloudwatch-agent-ctl ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/
cp ${PREPKGPATH}/amazon-cloudwatch-agent.service ${BUILD_ROOT}/SOURCES/etc/systemd/system/
cp ${PREPKGPATH}/config-translator ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/
cp ${PREPKGPATH}/config-downloader ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/
cp ${PREPKGPATH}/amazon-cloudwatch-agent-config-wizard ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/
cp ${PREPKGPATH}/start-amazon-cloudwatch-agent ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/
cp ${PREPKGPATH}/common-config.toml ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/etc/
cp ${PREPKGPATH}/amazon-cloudwatch-agent.conf ${BUILD_ROOT}/SOURCES/etc/init/amazon-cloudwatch-agent.conf
cp ${PREPKGPATH}/amazon-cloudwatch-agent-schema.json ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/doc/

chmod ug+rx ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent
chmod ug+rx ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl
chmod ug+rx ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/start-amazon-cloudwatch-agent
tar -zcvf ${BUILD_ROOT}/SOURCES/amazon-cloudwatch-agent.tar.gz -C ${BUILD_ROOT}/SOURCES opt etc

rm -rf ${BUILD_ROOT}/SOURCES/opt ${BUILD_ROOT}/SOURCES/etc

echo "Creating the rpm package"

rpmbuild -bb -v --clean --define "AGENT_VERSION $AGENT_VERSION" --define "_topdir ${BUILD_ROOT}" ${SPEC_FILE} --target ${TARGET_SUPPORTED_ARCH}

echo "Copying rpm files to bin"

mv ${BUILD_ROOT}/RPMS/${TARGET_SUPPORTED_ARCH}/amazon-cloudwatch-agent-${AGENT_VERSION}-1.${TARGET_SUPPORTED_ARCH}.rpm ${BUILD_SPACE}/bin/linux/${ARCH}/amazon-cloudwatch-agent.rpm
ls -ltr ${BUILD_SPACE}/bin/linux/${ARCH}/*.rpm


#!/usr/bin/env bash
echo "****************************************"
echo "Creating zip file for Windows amd64"
echo "****************************************"
set -e

BUILD_ROOT="${BUILD_SPACE}/private/windows_${ARCH}/"
AGENT_VERSION=$(cat ${PREPKGPATH}/CWAGENT_VERSION)
echo "BUILD_SPACE: ${BUILD_SPACE}    agent_version: ${AGENT_VERSION}  pre-package location:${PREPKGPATH}"
echo "Creating windows folders"

mkdir -p "${BUILD_ROOT}/amazon-cloudwatch-agent"
mkdir -p ${BUILD_SPACE}/bin/windows/${ARCH}/
echo "Copying application files"

echo "Copying application files"
cp ${PREPKGPATH}/LICENSE ${BUILD_ROOT}/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/NOTICE ${BUILD_ROOT}/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/THIRD-PARTY-LICENSES ${BUILD_ROOT}/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/RELEASE_NOTES ${BUILD_ROOT}/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/CWAGENT_VERSION ${BUILD_ROOT}/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/amazon-cloudwatch-agent.exe ${BUILD_ROOT}/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/amazon-cloudwatch-agent-ctl.ps1 ${BUILD_ROOT}/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/install.ps1 ${BUILD_ROOT}/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/uninstall.ps1 ${BUILD_ROOT}/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/config-translator.exe ${BUILD_ROOT}/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/config-downloader.exe ${BUILD_ROOT}/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/amazon-cloudwatch-agent-config-wizard.exe ${BUILD_ROOT}/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/start-amazon-cloudwatch-agent.exe ${BUILD_ROOT}/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/common-config.toml ${BUILD_ROOT}/amazon-cloudwatch-agent/
cp ${PREPKGPATH}/amazon-cloudwatch-agent-schema.json ${BUILD_ROOT}/amazon-cloudwatch-agent/

echo "Constructing the zip package"

if [ -f ${BUILD_ROOT}/amazon-cloudwatch-agent.zip ]; then
     rm ${BUILD_ROOT}/amazon-cloudwatch-agent.zip
fi
cd ${BUILD_ROOT}

zip -r amazon-cloudwatch-agent-${AGENT_VERSION}.zip *

mv ${BUILD_ROOT}/amazon-cloudwatch-agent-${AGENT_VERSION}.zip ${BUILD_SPACE}/bin/windows/${ARCH}/amazon-cloudwatch-agent.zip
ls -ltr ${BUILD_SPACE}/bin/windows/${ARCH}/amazon-cloudwatch-agent.zip


#!/usr/bin/env bash

#get the version of the agent
AGENT_VERSION=$(</tmp/CWAGENT_VERSION)

#create a .pkg file
rm -rf /tmp/AmazonCWAgentPackage
mkdir /tmp/AmazonCWAgentPackage
gunzip -c /tmp/amazon-cloudwatch-agent.tar.gz | tar -C /tmp/AmazonCWAgentPackage -xvf -
COMMON_CONFIG_PATH=/tmp/AmazonCWAgentPackage/opt/aws/amazon-cloudwatch-agent/etc/common-config.toml
SAMPLE_SUFFIX=SAMPLE_DO_NOT_MODIFY
mv ${COMMON_CONFIG_PATH} ${COMMON_CONFIG_PATH}.${SAMPLE_SUFFIX}
if [ $? -ne 0 ]; then
    echo "Failed to mv common-config.toml"
    exit 1
fi

mkdir /tmp/AmazonAgentScripts
mv preinstall.sh /tmp/AmazonAgentScripts/preinstall
mv postinstall.sh /tmp/AmazonAgentScripts/postinstall
chmod +x /tmp/AmazonAgentScripts/preinstall
chmod +x /tmp/AmazonAgentScripts/postinstall

rm -rf artifact
mkdir artifact
sudo pkgbuild --root /tmp/AmazonCWAgentPackage/ --install-location "/" --scripts /tmp/AmazonAgentScripts --identifier com.amazon.cloudwatch.agent --version=$AGENT_VERSION artifact/amazon-cloudwatch-agent.pkg
bucketPath="s3://$1/integration-test/packaging/$2/$3/amazon-cloudwatch-agent.pkg"
if [[ $2 = "nosha" ]]; then
    # SHA parameter is empty, this must be a prod, nonprod, or nightly build.
    bucketPath="s3://$1/$3/amazon-cloudwatch-agent.pkg"
fi
aws s3 cp ./artifact/amazon-cloudwatch-agent.pkg $bucketPath
echo "bucket path, $bucketPath"

#TODO uncomment for mac specific signing gpg is supported
## create a package.tar.gz for the uploading it to signing bucket
#tar -cvzf artifact.gz -C artifact .
#tar -cvzf  package.tar.gz manifest.yaml artifact.gz
#
##upload the .pkg file created
#/usr/local/bin/aws s3 cp /tmp/package.tar.gz "s3://macos-cwagent-binaries/$AGENT_VERSION/pre-signed/package.tar.gz" --acl public-read


#!/bin/bash

echo "Creating a default user cwagent"
COMMON_CONFIG_PATH=/opt/aws/amazon-cloudwatch-agent/etc/common-config.toml
SAMPLE_SUFFIX=SAMPLE_DO_NOT_MODIFY
if [ ! -f ${COMMON_CONFIG_PATH} ]; then
     cp ${COMMON_CONFIG_PATH}.${SAMPLE_SUFFIX} ${COMMON_CONFIG_PATH}
fi

if [[ cwagent == $(sudo dscl . -list /Users UniqueID | awk '{print $1}' | grep -w cwagent) ]]; then
     echo "User already exists!"
     exit 0
fi

LastID=$(sudo dscl . -list /Users UniqueID | awk '{print $2}' | sort -n | tail -1)
NextID=$((LastID + 1))

. /etc/rc.common
sudo dscl . create /Users/cwagent
sudo dscl . create /Users/cwagent RealName cwagent

sudo dscl . create /Users/cwagent UniqueID $NextID
# PrimaryGroupID of 20 to create a standard user
sudo dscl . create /Users/cwagent PrimaryGroupID 20
sudo dscl . create /Users/cwagent UserShell /usr/bin/false
sudo dscl . create /Users/cwagent NFSHomeDirectory /Users/cwagent
sudo createhomedir -u cwagent -c

echo " "
echo "New user $(sudo dscl . -list /Users UniqueID | awk '{print $1}' | grep -w cwagent) has been created with unique ID $(sudo dscl . -list /Users UniqueID | grep -w cwagent | awk '{print $2}')"


#!/bin/bash

COMMON_CONFIG_PATH=/opt/aws/amazon-cloudwatch-agent/etc/common-config.toml
SAMPLE_SUFFIX=SAMPLE_DO_NOT_MODIFY
if [ -e ${COMMON_CONFIG_PATH}.${SAMPLE_SUFFIX} -a -e ${COMMON_CONFIG_PATH} ]; then
     diff ${COMMON_CONFIG_PATH}.${SAMPLE_SUFFIX} ${COMMON_CONFIG_PATH} >/dev/null 2>&1
     if [ $? -eq 0 ]; then
          rm -r ${COMMON_CONFIG_PATH}
     fi
fi

launchctl list com.amazon.cloudwatch.agent >/dev/null 2>&1
if [ $? -eq 0 ]; then
     echo "Agent is running in the instance"
     echo "Stopping the agent"
     launchctl unload /Library/LaunchDaemons/com.amazon.cloudwatch.agent.plist
     echo "Agent stopped"
fi


#! /bin/bash
echo sha ${cwa_github_sha}
echo clone and install agent
cd /home/ec2-user/
git clone --branch ${github_test_repo_branch} ${github_test_repo}
cd amazon-cloudwatch-agent-test
aws s3 cp s3://${binary_uri} .
export HOME=/root
export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin
echo Running command ${install_agent}
${install_agent}
echo Starting agent now
/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c file:/home/ec2-user/amazon-cloudwatch-agent-test/test/userdata/agent_configs/config.json
cloud-init status --wait


countLogLines() {
    log_path="${1:-}"
    if [ -f "${log_path}" ]; then
        cat ${log_path} | wc -l
    else
        echo 0
    fi
}
cwa_log=$(countLogLines "/opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log")
echo "cwa_log:${cwa_log}"


#!/bin/sh

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT

assertStatus() {
     keyToCheck="${1:-}"
     expectedVal="${2:-}"

     grepKey='unknown'
     case "${keyToCheck}" in
     cwa_running_status)
          grepKey="\"status\""
          ;;
     cwa_config_status)
          grepKey="\"configstatus\""
          ;;
     *)
          echo "Invalid Key To Check: ${keyToCheck}" >&2
          exit 1
          ;;
     esac

     result=$(/usr/bin/amazon-cloudwatch-agent-ctl -a status | grep "${grepKey}" | awk -F: '{print $2}' | sed 's/ "//; s/",//')

     if [ "${result}" = "${expectedVal}" ]; then
          echo "In step ${step}, ${keyToCheck} is expected"
     else
          echo "In step ${step}, ${keyToCheck} is NOT expected. (actual="${result}"; expected="${expectedVal}")"
          exit 1
     fi
}

# init
step=0
/usr/bin/amazon-cloudwatch-agent-ctl -a remove-config -c all
/usr/bin/amazon-cloudwatch-agent-ctl -a stop

step=1
/usr/bin/amazon-cloudwatch-agent-ctl -a status
assertStatus "cwa_running_status" "stopped"
assertStatus "cwa_config_status" "not configured"

step=2
/usr/bin/amazon-cloudwatch-agent-ctl -a start
assertStatus "cwa_running_status" "running"
assertStatus "cwa_config_status" "configured"

step=3
/usr/bin/amazon-cloudwatch-agent-ctl -a remove-config -c default -s
assertStatus "cwa_running_status" "running"
assertStatus "cwa_config_status" "configured"

step=4
/usr/bin/amazon-cloudwatch-agent-ctl -a prep-restart
/usr/bin/amazon-cloudwatch-agent-ctl -a stop
assertStatus "cwa_running_status" "stopped"
assertStatus "cwa_config_status" "configured"

step=5
/usr/bin/amazon-cloudwatch-agent-ctl -a cond-restart
assertStatus "cwa_running_status" "running"
assertStatus "cwa_config_status" "configured"

step=6
/usr/bin/amazon-cloudwatch-agent-ctl -a append-config -c default -s
assertStatus "cwa_running_status" "running"
assertStatus "cwa_config_status" "configured"

step=7
/usr/bin/amazon-cloudwatch-agent-ctl -a remove-config -c all
assertStatus "cwa_running_status" "running"
assertStatus "cwa_config_status" "not configured"

step=8
/usr/bin/amazon-cloudwatch-agent-ctl -a fetch-config -s
assertStatus "cwa_running_status" "running"
assertStatus "cwa_config_status" "configured"

step=9
/usr/bin/amazon-cloudwatch-agent-ctl -a remove-config -c all
/usr/bin/amazon-cloudwatch-agent-ctl -a stop
assertStatus "cwa_running_status" "stopped"
assertStatus "cwa_config_status" "not configured"


#!/bin/bash
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the
# "License"). You may not use this file except in compliance
#  with the License. A copy of the License is located at
#
#     http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and
# limitations under the License.
#
# This script wraps the mockgen tool and inserts licensing information.

set -e
package=${1?Must provide package}
interfaces=${2?Must provide interface names}
outputfile=${3?Must provide an output file}

export PATH="${GOPATH//://bin:}/bin:$PATH"

data=$(
cat << EOF
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
//     http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.

$(mockgen "$package" "$interfaces")
EOF
)

echo "$data" | goimports > "${outputfile}"


#!/bin/sh

if test -z "$BASH_SOURCE"
then
      ABSOLUTE_PATH="$(cd "$(dirname "${BASH_SOURCE:-$0}")" && pwd)/$(basename "${BASH_SOURCE:-$0}")"
else
      ABSOLUTE_PATH="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/$(basename "${BASH_SOURCE[0]}")"
fi
CURRENT_FOLDER="${ABSOLUTE_PATH%/*}"
echo "ABSOLUTEPATH=${ABSOLUTE_PATH}"
echo "CURRENT_FOLDER=${CURRENT_FOLDER}"
TARGET_FOLDER="$CURRENT_FOLDER"/target
echo TARGET_FOLDER=${TARGET_FOLDER}
mkdir -p $TARGET_FOLDER

echo "Building Docker Image"
docker build -t taco-builder $CURRENT_FOLDER

echo "Assembling Tableau Connector"
docker run -d -it --name=taco-builder --mount type=bind,source=$TARGET_FOLDER,target=/output taco-builder
echo "Copying Tableau Connector"
docker exec taco-builder sh -c "cp /tableau-sdk/connector-plugin-sdk/connector-packager/packaged-connector/documentdbjdbc.taco  /output"
echo "Verifying Tableau Connector"
docker exec taco-builder sh -c "ls -l /output"
docker exec taco-builder pwd
echo "Extracting Tableau Connector"
docker cp taco-builder:/output/documentdbjdbc.taco $TARGET_FOLDER
echo "Checking Resulting TACO FILE in $TARGET_FOLDER"
ls -l $TARGET_FOLDER
docker stop taco-builder
docker rm taco-builder


BUILD_DIR=cmake-build64
BUILD_TYPE=Debug
PROJECT_DIR=$(pwd)
DRIVER_BIN_DIR="$PROJECT_DIR/build/odbc/bin"
DRIVER_LOG_DIR="$PROJECT_DIR/build/odbc/logs"

mkdir $DRIVER_LOG_DIR

mkdir $BUILD_DIR
cd $BUILD_DIR
cmake ../src -DCMAKE_BUILD_TYPE="$BUILD_TYPE" -DCODE_COVERAGE="ON" -DBUILD_SHARED_LIBS="OFF" -DWITH_TESTS="ON" -DWITH_ODBC="ON"
cd ..

# Download the DocumentDB JDBC Driver
read -r JDBC_DRIVER_VERSION < "${PROJECT_DIR}/src/JDBC_DRIVER_VERSION.txt"
JDBC_DRIVER_FILENAME="documentdb-jdbc-$JDBC_DRIVER_VERSION-all.jar"
JDBC_DRIVER_FULLPATH="$DRIVER_BIN_DIR/libs/$JDBC_DRIVER_FILENAME"
export DOCUMENTDB_HOME="$DRIVER_BIN_DIR"
if [ ! -f "$JDBC_DRIVER_FULLPATH" ]; then
    mkdir "$DRIVER_BIN_DIR/libs"
    echo "Downloading version $JDBC_DRIVER_VERSION of JDBC driver..."
    curl -o "$DRIVER_BIN_DIR/libs/$JDBC_DRIVER_FILENAME" -L https://github.com/aws/amazon-documentdb-jdbc-driver/releases/download/v$JDBC_DRIVER_VERSION/$JDBC_DRIVER_FILENAME
    echo "Download complete."
fi

cd cmake-build64
make -j 4
cd ..


BUILD_DIR=cmake-build64
BUILD_TYPE=Release
PROJECT_DIR=$(pwd)
DRIVER_BIN_DIR="$PROJECT_DIR/build/odbc/bin"

mkdir cmake-build64
cd cmake-build64
cmake ../src -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCODE_COVERAGE="OFF" -DBUILD_SHARED_LIBS="OFF" -DWITH_TESTS="ON" -DWITH_ODBC="ON"
cd ..

# Download the DocumentDB JDBC Driver
read -r JDBC_DRIVER_VERSION < "${PROJECT_DIR}/src/JDBC_DRIVER_VERSION.txt"
JDBC_DRIVER_FILENAME="documentdb-jdbc-$JDBC_DRIVER_VERSION-all.jar"
JDBC_DRIVER_FULLPATH="$DRIVER_BIN_DIR/libs/$JDBC_DRIVER_FILENAME"
export DOCUMENTDB_HOME="$DRIVER_BIN_DIR"
if [ ! -f "$JDBC_DRIVER_FULLPATH" ]; then
    mkdir "$DRIVER_BIN_DIR/libs"
    echo "Downloading version $JDBC_DRIVER_VERSION of JDBC driver..."
    curl -o "$DRIVER_BIN_DIR/libs/$JDBC_DRIVER_FILENAME" -L https://github.com/aws/amazon-documentdb-jdbc-driver/releases/download/v$JDBC_DRIVER_VERSION/$JDBC_DRIVER_FILENAME
    echo "Download complete."
fi

cd cmake-build64
make -j 4
cd ..


BUILD_DIR=cmake-build64
BUILD_TYPE=Debug
PROJECT_DIR=$(pwd)
DRIVER_BIN_DIR="$PROJECT_DIR/build/odbc/bin"
DRIVER_LOG_DIR="$PROJECT_DIR/build/odbc/logs"

mkdir $DRIVER_LOG_DIR

mkdir $BUILD_DIR
cd $BUILD_DIR
cmake ../src -DCMAKE_BUILD_TYPE="$BUILD_TYPE" -DCODE_COVERAGE="ON" -DBUILD_SHARED_LIBS="OFF" -DWITH_TESTS="ON" -DWITH_ODBC="ON"
cd ..

# Download the DocumentDB JDBC Driver
read -r JDBC_DRIVER_VERSION < "${PROJECT_DIR}/src/JDBC_DRIVER_VERSION.txt"
JDBC_DRIVER_FILENAME="documentdb-jdbc-$JDBC_DRIVER_VERSION-all.jar"
JDBC_DRIVER_FULLPATH="$DRIVER_BIN_DIR/libs/$JDBC_DRIVER_FILENAME"
export DOCUMENTDB_HOME="$DRIVER_BIN_DIR"
if [ ! -f "$JDBC_DRIVER_FULLPATH" ]; then
    mkdir "$DRIVER_BIN_DIR/libs"
    echo "Downloading version $JDBC_DRIVER_VERSION of JDBC driver..."
    curl -o "$DRIVER_BIN_DIR/libs/$JDBC_DRIVER_FILENAME" -L https://github.com/aws/amazon-documentdb-jdbc-driver/releases/download/v$JDBC_DRIVER_VERSION/$JDBC_DRIVER_FILENAME
    echo "Download complete."
fi

#clean up the binary files used to generate code coverage report
find . -name "*.gcda" -type f -delete

cd cmake-build64
make -j 4
cd ..


BUILD_DIR=cmake-build64
BUILD_TYPE=Release
PROJECT_DIR=$(pwd)
DRIVER_BIN_DIR="$PROJECT_DIR/build/odbc/bin"

mkdir $BUILD_DIR
cd $BUILD_DIR
cmake ../src -DCMAKE_BUILD_TYPE="$BUILD_TYPE" -DCODE_COVERAGE="OFF" -DBUILD_SHARED_LIBS="OFF" -DWITH_TESTS="ON" -DWITH_ODBC="ON"
make -j 4

# Download the DocumentDB JDBC Driver
read -r JDBC_DRIVER_VERSION < "${PROJECT_DIR}/src/JDBC_DRIVER_VERSION.txt"
JDBC_DRIVER_FILENAME="documentdb-jdbc-$JDBC_DRIVER_VERSION-all.jar"
JDBC_DRIVER_FULLPATH="$DRIVER_BIN_DIR/libs/$JDBC_DRIVER_FILENAME"
export DOCUMENTDB_HOME="$DRIVER_BIN_DIR"
if [ ! -f "$JDBC_DRIVER_FULLPATH" ]; then
    mkdir "$DRIVER_BIN_DIR/libs"
    echo "Downloading version $JDBC_DRIVER_VERSION of JDBC driver..."
    curl -o "$DRIVER_BIN_DIR/libs/$JDBC_DRIVER_FILENAME" -L https://github.com/aws/amazon-documentdb-jdbc-driver/releases/download/v$JDBC_DRIVER_VERSION/$JDBC_DRIVER_FILENAME
    echo "Download complete."
fi

cd ..


#!/bin/bash

RESULTS_FILE=cppcheck-results.log

# --force: force checks all define combinations (default max is 12)
# -iaws-sdk-cpp: avoid checking AWS C++ SDK source files in our repo
cppcheck --force --library=boost --library=documentdb -UWIN32 ./src/ 2>  ${RESULTS_FILE}

if [ -s ${RESULTS_FILE} ]; then
    echo "!! Cppcheck errors found! Check ${RESULTS_FILE} for details."
    exit 1
else
    echo "No Cppcheck errors found."
fi


#!/bin/bash

#
#   Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
#   Licensed under the Apache License, Version 2.0 (the "License").
#   You may not use this file except in compliance with the License.
#   A copy of the License is located at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#   or in the "license" file accompanying this file. This file is distributed
#   on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
#   express or implied. See the License for the specific language governing
#   permissions and limitations under the License.
#

PROJECT_DIR=$(pwd)
TEST_RUNNER_DIR=${PROJECT_DIR}/src/TestRunner
WORKING_DIR=${PROJECT_DIR}

cd ${WORKING_DIR}

pip3 install mako

python3 ${TEST_RUNNER_DIR}/test_runner.py -i ${TEST_RUNNER_DIR}/mako_template.html -o ${PROJECT_DIR}/test_output.html -e ${TEST_RUNNER_DIR}/test_exclude_list.txt

ERROR_CODE=$?

cd ..

exit ${ERROR_CODE}


#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"

CHECK=1

if [[ -z "${DOC_DB_USER_NAME}" ]]; then
  echo "DOC_DB_USER_NAME environment variable is not set. Using default."
  export DOC_DB_USER_NAME=documentdb
  echo "DOC_DB_USER_NAME=$DOC_DB_USER_NAME"
else
  echo "DOC_DB_USER_NAME=$DOC_DB_USER_NAME"
fi

if [[ -z "${DOC_DB_PASSWORD}" ]]; then
  echo "DOC_DB_PASSWORD environment variable is not set. Please set this variable explicitly."
  CHECK=0
else
  echo "DOC_DB_PASSWORD=******"
fi

if [[ -z "${DOC_DB_USER}" ]]; then
  echo "DOC_DB_USER environment variable is not set. Please set this variable explicitly."
  CHECK=0
else
  echo "DOC_DB_USER=$DOC_DB_USER"
fi

if [[ -z "${DOC_DB_LOCAL_PORT}" ]]; then
  echo "DOC_DB_LOCAL_PORT environment variable is not set. Please set this variable explicitly."
  CHECK=0
else
  echo "DOC_DB_LOCAL_PORT=$DOC_DB_LOCAL_PORT"
fi

if [[ -z "${DOC_DB_PRIV_KEY_FILE}" ]]; then
  echo "DOC_DB_PRIV_KEY_FILE environment variable is not set. Please set this variable explicitly."
  CHECK=0
else
  echo "DOC_DB_PRIV_KEY_FILE$DOC_DB_PRIV_KEY_FILE"
fi

if [[ -z "${JAVA_HOME}" ]]; then
  echo "JAVA_HOME environment variable is not set. Please set this variable explicitly."
  CHECK=0
else
  echo "JAVA_HOME=$JAVA_HOME"
fi

if [[ -z "${DOCUMENTDB_HOME}" ]]; then
  echo "DOCUMENTDB_HOME environment variable is not set. Using default."
  export DOCUMENTDB_HOME=${SCRIPT_DIR}/../build/odbc/bin
  echo "DOCUMENTDB_HOME=$DOCUMENTDB_HOME"
else
  echo "DOCUMENTDB_HOME=$DOCUMENTDB_HOME"
fi

if [[ -z "${ODBCINSTINI}" ]]; then
  echo "ODBCINSTINI environment variable is not set. Using default."
  export ODBCINSTINI="${SCRIPT_DIR}/../build/odbc/lib/documentdb-odbc-install.ini"
  echo "ODBCINSTINI=ODBCINSTINI"
else
  echo "ODBCINSTINI=ODBCINSTINI"
fi

#if [[ -z "${ODBC_LIB_PATH}" ]]; then
#  echo "ODBC_LIB_PATH environment variable is not set. Using default."
#  export ODBC_LIB_PATH=${SCRIPT_DIR}/../build/odbc/lib
#  echo "ODBC_LIB_PATH=$ODBC_LIB_PATH"
#else
#  echo "ODBC_LIB_PATH=$ODBC_LIB_PATH"
#fi

if [[ "${CHECK}" -eq "0" ]]; then
  echo "Missing envrionment variables, please set them accordingly."
else
  echo "Environment variables are all set"
fi


#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements.  See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License.  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

# This script installs all required dependencies on Mac and sets the appropriate vars

# get the current script directory
PROJECT_DIR=$(pwd)
MAC_SCRIPT_DIR="$PROJECT_DIR/scripts/mac"

# install formula dependencies via brew
brew tap homebrew/services

# unlink unix ODBC driver manager
if brew ls --versions unixodbc > /dev/null; then
    echo "unixodbc is installed via brew. unlink unixodbc"
    brew unlink unixodbc
fi
# check if dependnecies are installed

# check if user is under the DocDB ODBC repository
if [[ ! -f "$MAC_SCRIPT_DIR/check_dependencies_mac.sh" ]]; then
    echo "Cannot find file $MAC_SCRIPT_DIR/check_dependencies_mac.sh, please check that you're under the DocumentDB ODBC repository before executing this script"
    exit 1
fi

chmod +x $MAC_SCRIPT_DIR/check_dependencies_mac.sh
source $MAC_SCRIPT_DIR/check_dependencies_mac.sh
# num_apps, apps_installed and req_apps are variables from check_dependencies_mac.sh

if [[ "${missing_formula}" -eq "0" ]]; then
    echo "Most required dependencies are installed. Checking if JAVA is installed."
else
    echo "Installing the missing required dependencies"
    for (( i=0 ; i<$num_apps ; i++ ));
    do
        if [[ "${apps_installed[i]}" -eq "0" ]]; then
            echo  "${req_apps[i]} is not installed, attempt to install it with brew."
            brew install ${req_apps[i]}
            # The libiodbc package may conflict with the unixodbc package
            if [[ "${req_apps[i]}" -eq "libiodbc" ]]; then
                brew link --overwrite --force ${req_apps[i]}
            fi
        fi
    done
fi

# [Re-]Install mongodb server
# TODO: make re-installing mongodb server optional
# https://github.com/aws/amazon-documentdb-odbc-driver/issues/172
chmod +x $MAC_SCRIPT_DIR/reinstall_mongodb_mac.sh
$MAC_SCRIPT_DIR/reinstall_mongodb_mac.sh

# check if java dependency is installed
chmod +x $MAC_SCRIPT_DIR/check_java_dependency_mac.sh
source $MAC_SCRIPT_DIR/check_java_dependency_mac.sh
# jdkFound is a variable from check_java_dependency_mac.sh

java_ver=corretto
if [[ "${jdkFound}" -ne "1" ]]; then
    echo "$java_ver is not installed, attempt to install it with brew."
    # install JAVA dependency via brew
    brew tap homebrew/cask-versions
    brew install --cask $java_ver
fi

# set JAVA_HOME and save JAVA /bin and JAVA /server paths to $PATH
chmod +x $MAC_SCRIPT_DIR/set_java_def_mac.sh
source $MAC_SCRIPT_DIR/set_java_def_mac.sh

# add llvm to path
chmod +x $MAC_SCRIPT_DIR/set_llvm_mac.sh
source $MAC_SCRIPT_DIR/set_llvm_mac.sh

echo "The mac dependency installation script has finshed running."


SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done

SCRIPT_DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"

PROJECT_DIR="$SCRIPT_DIR/.."
ODBC_LIB_PATH="$PROJECT_DIR/build/odbc/lib"
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
  ODBC_LIB_FILENAME="$ODBC_LIB_PATH/libdocumentdb-odbc.so"
elif [[ "$OSTYPE" == "darwin"* ]]; then
  ODBC_LIB_FILENAME="$ODBC_LIB_PATH/libdocumentdb-odbc.dylib"
fi

if [ ! -f "$ODBC_LIB_FILENAME" ]
then
  echo "Cannot find ODBC library file: $ODBC_LIB_FILENAME"
  exit 1
fi

echo "[Amazon DocumentDB]"            > "$ODBC_LIB_PATH/documentdb-odbc-install.ini"
echo "Description=Amazon DocumentDB" >> "$ODBC_LIB_PATH/documentdb-odbc-install.ini"
echo "Driver=$ODBC_LIB_FILENAME" >> "$ODBC_LIB_PATH/documentdb-odbc-install.ini"
echo "Setup=$ODBC_LIB_FILENAME"  >> "$ODBC_LIB_PATH/documentdb-odbc-install.ini"
echo "DriverODBCVer=03.00"       >> "$ODBC_LIB_PATH/documentdb-odbc-install.ini"
echo "FileUsage=0"               >> "$ODBC_LIB_PATH/documentdb-odbc-install.ini"

if [[ "$OSTYPE" == "linux-gnu"* ]]; then
  odbcinst -i -d -f "$ODBC_LIB_PATH/documentdb-odbc-install.ini"
elif [[ "$OSTYPE" == "darwin"* ]]; then
  export ODBCINSTINI="$ODBC_LIB_PATH/documentdb-odbc-install.ini"
  echo "Exported ODBCINSTINI=$ODBCINSTINI"
fi


# store project directory
PROJECT_DIR=$(pwd)

#find correct path to java_home_path
docdb_home="$PROJECT_DIR/build/odbc/bin"
set_docdb_home="export DOCUMENTDB_HOME=\"$docdb_home\""
odbc_instini="$PROJECT_DIR/build/odbc/lib/documentdb-odbc-install.ini"
set_odbc_instini="export ODBCINSTINI=\"$odbc_instini\""

cd ~
env_var_file=".zshrc"
updated=0

if [[ ! -d "${docdb_home}" ]]
then
    echo "Cannot find directory \"${docdb_home}\", please check that you're under the DocumentDB ODBC repository before executing this script and that a build script has run successfully."
    exit 1
fi

if [[ ! -f "${odbc_instini}" ]]
then
    echo "Cannot find file \"${odbc_instini}\", please check that you're under the DocumentDB ODBC repository before executing this script and that a build script has been run successfully."
    exit 1
fi

# check enviornment variables and write them as needed
if [[ "${DOCUMENTDB_HOME}" != "${docdb_home}" ]]; then
    echo "DOCUMENTDB_HOME is not set properly. Appending definition of DOCUMENTDB_HOME to end of ${env_var_file}"
    echo "$set_docdb_home" >> $env_var_file
    echo "DOCUMENTDB_HOME has been set"
    updated=1
fi

if [[ "${ODBCINSTINI}" != "${odbc_instini}" ]]; then
    echo "ODBCINSTINI is not set properly. Appending definition of ODBCINSTINI to end of ${env_var_file}"
    echo "$set_odbc_instini" >> $env_var_file
    echo "ODBCINSTINI has been set"
    updated=1
fi

# cd back to original directory
cd $PROJECT_DIR

if [[ ${updated} -eq "0" ]]; then
    echo "DOCUMENTDB_HOME and ODBCINSTINI are set properly. No new changes made to ~/$env_var_file"
else
    echo "~/$env_var_file has been updated to set environment variables properly. Please restart your terminal to load the variables"
fi


# TODO: [Automate setting up environment variables when building driver on Linux](https://github.com/aws/amazon-documentdb-odbc-driver/issues/173)
# store current directory
CURRENT_DIR=$(pwd)

#find correct path to java_home_path
#java_home_path="/Library/Java/JavaVirtualMachines/temurin-18.jdk/Contents/Home"
java_home_path="/path/to/java/home"
java_server_path="$java_home_path/lib/server/"
java_bin_path="$java_home_path/bin"
set_java_home="export JAVA_HOME=\"$java_home_path\""
set_java_bin_path="export PATH=\"$java_bin_path:\$PATH\""
set_java_server_path="export PATH=\"$java_server_path:\$PATH\""
# set_path="export PATH=\"$java_server_path:$java_bin_path:\$PATH\""

new_zshrc=""

cd ~
env_var_file=".bashrc"
# file=".zshrc"

java_home_set=1
# check enviornment variables
if [[ "${JAVA_HOME}" != "${java_home_path}" ]]; then
    echo "JAVA_HOME is not set properly. Removing previous definitions to JAVA_HOME and give new definition"
    java_home_set=0
fi

# Use IFS= to keep line indentations.
# assumes that env_var_file may or may not end with a new line

i=1
while IFS= read -r line || [ -n "$line" ]; do

    #Reading each line
    echo "Line No. $i : $line"

    # check if line is a comment.
    if [[ ! "$line" =~ ^[[:space:]]*\#.* ]]; then
        echo "TRACE - this line is not a comment, proceeding"

        # check that the line exports JAVA_HOME
        if [[ "${java_home_set}" == "0"  ]] && [[ "$line" =~ "export JAVA_HOME=" ]]; then
            # modify this line before writing to new_zshrc

            # removes instances of export JAVA_HOME="anything", except comments
            line=$(echo $line | sed -e 's/(?<!(^[[:space:]]*\#.*))(export JAVA_HOME=\".*?\")//g')

            echo "this line is setting JAVA_HOME"
            echo "modified line: $line"
            change_zshrc=1
        fi

    fi

    # remove duplicate of $set_path
    # but this is not needed. We just need to make sure we export the path when we don't have it -AL-
    # the search pattern is same as set_path except $var becomes '"${var}"', and all symbols are escaped (e.g., / becomes \/, : becomes \:)
    # line=$(echo $line | sed -e 's/export PATH=\"'"${JAVA_HOME}"'\/lib\/server\/\:'"${JAVA_HOME}"'\/bin:\$PATH\"//g')

    # if line is not white space
    if [[ $line =~ [^[:space:]] ]]; then
        echo "line is not whitespace"
        # write this line to new_zshrc

        # do not write new line if it is the first non-empty line
        if [[ ! $new_zshrc =~ [^[:space:]] ]]; then
            new_zshrc="$new_zshrc$line"
        else
            new_zshrc="$new_zshrc\n$line"
        fi
    fi

    i=$((i+1))
done < $env_var_file

if [[ "${change_zshrc}" -eq "1" ]]; then
    echo "re-writing ${env_var_file}"
    echo "$new_zshrc" > $env_var_file
fi

echo "writing new lines to ${env_var_file}"

if [[ "${java_home_set}" == "0"  ]]; then
    echo "$set_java_home" >> $env_var_file
    java_home_set=1
fi

if [[ ! :$PATH: == *:"$java_server_path":* ]] ; then
    echo "setting JAVA server path"
    echo "$set_java_server_path" >> $env_var_file
fi

if [[ ! :$PATH: == *:"$java_bin_path":* ]] ; then
    echo "setting JAVA bin path"
    echo "$set_java_bin_path" >> $env_var_file
fi

# cd back to original directory
cd $CURRENT_DIR


# script to check if formulas in req_apps are installed.

# add the required dependencies to the req_apps array.
# There is no need to change other variables
req_apps=("libiodbc" "cmake" "openssl" "boost" "mongo-cxx-driver")
num_apps=${#req_apps[@]}
apps_installed=()

for (( i=0 ; i<$num_apps ; i++ ));
do
  apps_installed+=(0)
  if brew ls --versions ${req_apps[i]} > /dev/null; then
    # ${req_apps[i]} is installed via brew
    echo "${req_apps[i]} is installed."
    apps_installed[i]=1
  else
    # ${req_apps[i]} not installed via brew
    echo "${req_apps[i]} is not installed."
    missing_formula=1
  fi
done


# Checks that JAVA_HOME is defined, the path to JAVA_HOME exists
# and is a JDK (i.e., include subdirectory)
if [[ ! -z "${JAVA_HOME}" ]] && [[ -d "${JAVA_HOME}" ]] && [[ -d "${JAVA_HOME}/include" ]]; then
    # Test Java in path and has minimum version
    javaVersionString=`echo "$(java --version)" | head -1`
    read -a javaVersionStringArrary <<< "$javaVersionString" # Reading a space-delimited string into an array
    javaVersion=${javaVersionStringArrary[1]}
    javaVersionArray=(${javaVersion//./ }) # separate javaVersion string by delimiter '.'
    if [[ ${#javaVersionArray[@]} -ge 1 ]] && [[ ! -z ${javaVersionArray[0]} ]]; then
        if [[ "1" -eq ${javaVersionArray[0]} ]] && [[ ! -z ${javaVersionArray[1]} ]]; then
            if  [[ ${javaVersionArray[1]} -eq "8" || ${javaVersionArray[1]} -eq "9" ]]; then
                jdkFound=1
            fi
        elif [[ ${javaVersionArray[0]} -ge "10" ]]; then
            jdkFound=1
        fi
    fi
fi

if [[ "${jdkFound}" -eq "1" ]]; then
    echo "Found suitable JDK on user's machine."
else
    echo "Did not find JDK on user's machine. If you have JDK installed, please ensure to set JAVA_HOME to the home directory of JDK to help me find it next time."
fi


#!/bin/sh

##################################################
# Assumptions
# 1. Environment variables DOC_DB_USER_NAME and DOC_DB_PASSWORD must be defined.
# 2. This is running on MacOS Intel silicon
##################################################

# Get the path to the configuration file (Intel silicon)
MONGO_CONFIG_FILE=/usr/local/etc/mongod.conf
MONGODB_SERVICE_NAME="mongodb-community"

function update_mongod_config_authorization() {
    MONGO_ENABLED_DISABLED=${1:-enabled}
    if [ -f "$MONGO_CONFIG_FILE" ]
    then
        MONGO_AUTHORIZATION=$(grep -E '^[ \t]*authorization:[ \t]+["]?((enabled)?|(disabled)?)["]?' "${MONGO_CONFIG_FILE}")
        if [ -z "${MONGO_AUTHORIZATION}" ]
        then
            echo 'security:' >> "${MONGO_CONFIG_FILE}"
            echo "    authorization: \"${MONGO_ENABLED_DISABLED}\"" >> "${MONGO_CONFIG_FILE}"
        else
            echo "Updating in place...."
            cat "${MONGO_CONFIG_FILE}"
            sed "s/^[ \t]*authorization:.*$/    authorization: \"${MONGO_ENABLED_DISABLED}\"/g" "${MONGO_CONFIG_FILE}" > "${MONGO_CONFIG_FILE}.new"
            mv -f "${MONGO_CONFIG_FILE}.new" "${MONGO_CONFIG_FILE}"
            echo "Updated"
            cat "${MONGO_CONFIG_FILE}"
        fi
    else
        echo "Config file not found: \"${MONGO_CONFIG_FILE}\""
    fi
}

brew tap mongodb/brew
brew install ${MONGODB_SERVICE_NAME}

update_mongod_config_authorization "disabled"
brew services restart ${MONGODB_SERVICE_NAME}

# By reinstalling, we've disabled authorization - so we can reset the authorization from scratch.
mongosh --eval "db.dropAllUsers()" "admin"
mongosh --eval "db.createUser({ user: '${DOC_DB_USER_NAME}', pwd: '${DOC_DB_PASSWORD}', roles: [ { role: 'root', db: 'admin' } ] })" "admin"
mongosh --eval "db.createUser({ user: 'docDbRestricted', pwd: '${DOC_DB_PASSWORD}', roles: [ { role: 'readAnyDatabase', db: 'admin' } ] })" "admin"

update_mongod_config_authorization "enabled"
brew services restart ${MONGODB_SERVICE_NAME}


# store current directory
CURRENT_DIR=$(pwd)

#java_home_path points to JAVA_HOME
#jdkFound is a variable from check_java_dependency_mac.sh.
if [[ "${jdkFound}" -eq "1" ]]; then
    java_home_path=$JAVA_HOME
else
    java_home_path="/Library/Java/JavaVirtualMachines/amazon-corretto-18.jdk/Contents/Home"
fi
java_server_path="$java_home_path/lib/server/"
java_bin_path="$java_home_path/bin"
set_java_home="export JAVA_HOME=\"$java_home_path\""
set_java_bin_path="export PATH=\"$java_bin_path:\$PATH\""
set_java_server_path="export PATH=\"$java_server_path:\$PATH\""

cd ~
env_var_file=".zshrc"
updated=0

# check enviornment variables
# Checks that JAVA_HOME is defined, the path to JAVA_HOME exists
# and is a JDK (i.e., include subdirectory)
if [[ "${JAVA_HOME}" != "${java_home_path}" ]]; then
    if [[ -d "${java_home_path}" ]]; then
        echo "JAVA_HOME is not set properly. Appending definition of JAVA_HOME to end of ${env_var_file}"
        echo "$set_java_home" >> $env_var_file
        echo "JAVA_HOME has been set"
        updated=1
    else
        echo "cannot find directory \"${java_home_path}\", please check if JAVA 18 is installed."
        dir_not_found=1
    fi
fi

if [[ ! :$PATH: == *:"$java_server_path":* ]] ; then
    if [[ -d "${java_server_path}" ]]; then
        echo "setting JAVA server path"
        echo "$set_java_server_path" >> $env_var_file
        echo "JAVA server path has been set"
        updated=1
    else
        echo "cannot find directory \"${java_server_path}\", please check if JAVA 18 is installed or find JAVA /server path manually."
        dir_not_found=1
    fi
fi

if [[ ! :$PATH: == *:"$java_bin_path":* ]] ; then
    if [[ -d "${java_bin_path}" ]]; then
        echo "setting JAVA bin path"
        echo "$set_java_bin_path" >> $env_var_file
        echo "JAVA bin path has been set"
        updated=1
    else
        echo "cannot find directory \"${java_bin_path}\", please check if JAVA 18 is installed or find JAVA /bin path manually."
        dir_not_found=1
    fi
fi

# cd back to original directory
cd $CURRENT_DIR

if [[ ${dir_not_found} -eq "1" ]]; then
    echo "One or more JAVA directories not found. Please make sure JAVA_HOME, JAVA bin path, and JAVA server path are set properly manually."
elif [[ ${updated} -eq "0" ]]; then
    echo "JAVA_HOME, JAVA bin path, and JAVA server path are set properly. No new changes made to ~/$env_var_file"
else
    echo "~/$env_var_file has been updated to set environment variables properly. Please restart your terminal to load the variables"
fi


# store project directory
PROJECT_DIR=$(pwd)

#llvm_path points to path to LLVM
llvm_path="/Library/Developer/CommandLineTools/usr/bin/"
set_llvm_path="export PATH=\"$llvm_path:\$PATH\""
llvm_app_path"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/"
set_llvm_app_path="export PATH=\"$llvm_app_path:\$PATH\""

cd ~
env_var_file=".zshrc"
updated=0

if [[ ! :$PATH: == *:"$llvm_path":* ]] && [[ ! :$PATH: == *:"$llvm_app_path":* ]]; then
    echo "attempt to add llvm to your path"
    if [[ -d "${llvm_path}" ]]; then
        echo "setting llvm path"
        echo "$set_llvm_path" >> $env_var_file
        echo "llvm path has been set"
        updated=1
    else
        echo "cannot find directory \"${llvm_path}\", checking if \"${llvm_app_path}\" exists."
        if [[ -d "${llvm_app_path}" ]]; then
            echo "setting XCode application llvm path"
            echo "$set_llvm_app_path" >> $env_var_file
            echo "XCode application llvm path has been set"
            updated=1
        else
            echo "cannot find directory \"${set_llvm_app_path}\". Will not update \$PATH. XCode installation is required."
            no_llvm_found=1
        fi
    fi
fi

# cd back to original directory
cd $PROJECT_DIR

if [[ ${no_llvm_found} -eq "1" ]]; then
    echo "No llvm found on your machine. No new updates has been made to ~/$env_var_file. XCode installation is required for DocumentDB ODBC driver to build. After XCode is installed, run ./scripts/mac/set_llvm_mac.sh to add the path to llvm to your \$PATH."
elif [[ ${updated} -eq "0" ]]; then
    echo "PATH includes at least 1 path to llvm. No new changes made to ~/$env_var_file"
else
    echo "~/$env_var_file has been updated to include llvm in your \$PATH. Please restart your terminal to load the system path"
fi


#!/bin/bash

##################################################
# Assumptions
# 1. Mongo server running and listening on port 27017
# 2. Mongo started with the environment variables DOC_DB_USER_NAME and DOC_DB_PASSWORD
##################################################

if [[ "$OSTYPE" == "linux-gnu"* ]]; then
  SCRIPT_DIR=$( cd -- "$( dirname -- $0 )"  && pwd )
elif [[ "$OSTYPE" == "darwin"* ]]; then
  SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
fi

TEST_INPUT_FOLDER="${SCRIPT_DIR}/../input"
DATABASE_NAME="odbc-test"

# Clear the database so we don't have any existing data
mongosh --quiet -u="${DOC_DB_USER_NAME}" -p="${DOC_DB_PASSWORD}" --authenticationDatabase=admin \
    --eval "db.dropDatabase()" "${DATABASE_NAME}"

# Load each test input file
for FILENAME in "${TEST_INPUT_FOLDER}"/*.json
do
    # Collection will be named the same as the input file base name
    COLLECTION_NAME="$(basename -- ${FILENAME%.json})"
    TEST_FILE_NAME="$(basename -- ${FILENAME})"

    mongoimport -u="${DOC_DB_USER_NAME}" -p="${DOC_DB_PASSWORD}" --authenticationDatabase=admin \
        -d="${DATABASE_NAME}" -c="${COLLECTION_NAME}" --jsonArray \
        --file="""${TEST_INPUT_FOLDER}/${TEST_FILE_NAME}"""
    if [ $? -ne 0 ]
    then
        exit 1
    fi
done


#!/bin/sh

PATH=/sbin:/bin:/usr/bin
failed='false'

# Hibernation selects the swapfile with highest priority. Since there may be
# other swapfiles configured, ensure /swap is selected as hibernation
# target by setting to maximum priority.
swap_priority=32767

hibernate()
{
        swapon --priority=$swap_priority /swap && /usr/sbin/pm-hibernate
        if [ $? -ne 0 ]
        then
            logger "Hibernation failed, Sleeping 2 mins before retry"
            failed='true'
        else
            failed='false'
        fi
        swapoff /swap
}

case "$2" in
    SBTN)
        # The iteration had been placed here to add retry logic to hibernation
        # in case of failures and to avoid force stop of instances after 20min
        for i in 1 2 3
        do
          hibernate
          if [ $failed == 'true' ];
          then
            sleep 2m
          else
           break
          fi
       done
       ;;
    *)
        logger "ACPI action undefined: $2" ;;
esac


#!/bin/sh

PATH=/sbin:/bin:/usr/bin
failed='false'

hibernate()
{
        swapon /swap
        systemctl hibernate

        if [ $? -ne 0 ]
        then
            logger "Hibernation failed, Sleeping 2 mins before retry"
            failed='true'
        else
            failed='false'
        fi
}

case "$2" in
    SBTN)
        # The iteration had been placed here to add retry logic to hibernation
        # in case of failures and to avoid force stop of instances after 20min
        for i in 1 2 3
        do
          hibernate
          if [ $failed == 'true' ];
          then
            sleep 2m
          else
           break
          fi
       done
       ;;
    *)
        logger "ACPI action undefined: $2" ;;
esac


#!/bin/bash

# This is called before hibernating or after resuming, as follows:
# $0=/usr/lib/systemd/system-sleep/sleepyhead, $1=pre, $2=suspend
# ...and when the lid is opened, as follows:
# $0=/usr/lib/systemd/system-sleep/sleepyhead, $1=post, $2=suspend

if [ "$1" = "post" ] ; then
    logger "Resuming from sleep to swapoff"
    swapoff /swap
fi


#!/bin/bash
set -euo pipefail

ROOT_PATH="$( cd "$(dirname "$0")" ; pwd -P )/../../"
EXIT_CODE=0

while read pkg_license_tuple; do
    pkg=$(echo $pkg_license_tuple | tr -s " " | cut -d" " -f1)
    license=$(echo $pkg_license_tuple | tr -s " " | cut -d" " -f2-)
    if [[ "$(grep -c ${pkg} ${ROOT_PATH}/THIRD_PARTY_LICENSES)" -ge 1 ]]; then
        echo "âœ… FOUND ${pkg} (${license})"
    else
        echo "ðŸ”´ MISSING for ${pkg} (${license})"
        EXIT_CODE=1
    fi
done < "${1:-/dev/stdin}"

echo "================================================="
if [[ "${EXIT_CODE}" -eq 0 ]]; then
    echo "âœ… TEST PASSED"
else
    echo "ðŸ”´ TEST FAILED"
fi

exit $EXIT_CODE


#!/bin/bash
set -euo pipefail

SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"
BUILD_DIR="$SCRIPTPATH/../../build"
mkdir -p $BUILD_DIR
GOBIN=$(go env GOPATH | sed 's+:+/bin+g')/bin
export PATH="$PATH:$GOBIN"

go install github.com/mitchellh/golicense@v0.2.0
go build -o $BUILD_DIR/aeis $SCRIPTPATH/../../.
golicense -out-xlsx=$BUILD_DIR/report.xlsx $SCRIPTPATH/license-config.hcl $BUILD_DIR/aeis


#!/bin/bash
set -euo pipefail

SCRIPTPATH="$( cd "$(dirname "$0")" ; pwd -P )"
BUILD_PATH="$SCRIPTPATH/../../build"
BUILD_BIN="$BUILD_PATH/bin"

BINARY_NAME="ec2-instance-selector-linux-amd64"
LICENSE_TEST_TAG="aeis-license-test"
LICENSE_REPORT_FILE="$BUILD_PATH/license-report"
GOPROXY="direct|https://proxy.golang.org"

SUPPORTED_PLATFORMS_LINUX="linux/amd64" make -s -f $SCRIPTPATH/../../Makefile build-binaries
docker buildx build --load --build-arg=GOPROXY=${GOPROXY} -t $LICENSE_TEST_TAG $SCRIPTPATH/
docker run -i -e GITHUB_TOKEN --rm -v $SCRIPTPATH/:/test -v $BUILD_BIN/:/aeis-bin $LICENSE_TEST_TAG golicense /test/license-config.hcl /aeis-bin/$BINARY_NAME | tee $LICENSE_REPORT_FILE
$SCRIPTPATH/check-licenses.sh $LICENSE_REPORT_FILE


#!/bin/bash
# Test the current package under a different kernel.
# Requires virtme and qemu to be installed.
# Examples:
#     Run all tests on a 5.4 kernel
#     $ ./run-tests.sh 5.4
#     Run a subset of tests:
#     $ ./run-tests.sh 5.4 go test ./link

set -euo pipefail

script="$(realpath "$0")"
readonly script

# This script is a bit like a Matryoshka doll since it keeps re-executing itself
# in various different contexts:
#
#   1. invoked by the user like run-tests.sh 5.4
#   2. invoked by go test like run-tests.sh --exec-vm
#   3. invoked by init in the vm like run-tests.sh --exec-test
#
# This allows us to use all available CPU on the host machine to compile our
# code, and then only use the VM to execute the test. This is because the VM
# is usually slower at compiling than the host.
if [[ "${1:-}" = "--exec-vm" ]]; then
  shift

  input="$1"
  shift

  # Use sudo if /dev/kvm isn't accessible by the current user.
  sudo=""
  if [[ ! -r /dev/kvm || ! -w /dev/kvm ]]; then
    sudo="sudo"
  fi
  readonly sudo

  testdir="$(dirname "$1")"
  output="$(mktemp -d)"
  printf -v cmd "%q " "$@"

  if [[ "$(stat -c '%t:%T' -L /proc/$$/fd/0)" == "1:3" ]]; then
    # stdin is /dev/null, which doesn't play well with qemu. Use a fifo as a
    # blocking substitute.
    mkfifo "${output}/fake-stdin"
    # Open for reading and writing to avoid blocking.
    exec 0<> "${output}/fake-stdin"
    rm "${output}/fake-stdin"
  fi

  $sudo virtme-run --kimg "${input}/bzImage" --memory 768M --pwd \
  --rwdir="${testdir}=${testdir}" \
  --rodir=/run/input="${input}" \
  --rwdir=/run/output="${output}" \
  --script-sh "PATH=\"$PATH\" \"$script\" --exec-test $cmd" \
  --qemu-opts -smp 2 # need at least two CPUs for some tests

  if [[ ! -e "${output}/success" ]]; then
    exit 1
  fi

  $sudo rm -r "$output"
  exit 0
elif [[ "${1:-}" = "--exec-test" ]]; then
  shift

  mount -t bpf bpf /sys/fs/bpf
  mount -t tracefs tracefs /sys/kernel/debug/tracing

  if [[ -d "/run/input/bpf" ]]; then
    export KERNEL_SELFTESTS="/run/input/bpf"
  fi

  dmesg -C
  if ! "$@"; then
    dmesg
    exit 1
  fi
  touch "/run/output/success"
  exit 0
fi

readonly kernel_version="${1:-}"
if [[ -z "${kernel_version}" ]]; then
  echo "Expecting kernel version as first argument"
  exit 1
fi
shift

readonly kernel="linux-${kernel_version}.bz"
readonly selftests="linux-${kernel_version}-selftests-bpf.bz"
readonly input="$(mktemp -d)"
readonly tmp_dir="${TMPDIR:-/tmp}"
readonly branch="${BRANCH:-master}"

fetch() {
    echo Fetching "${1}"
    wget -nv -N -P "${tmp_dir}" "https://github.com/cilium/ci-kernels/raw/${branch}/${1}"
}

fetch "${kernel}"
cp "${tmp_dir}/${kernel}" "${input}/bzImage"

if fetch "${selftests}"; then
  mkdir "${input}/bpf"
  tar --strip-components=4 -xjf "${tmp_dir}/${selftests}" -C "${input}/bpf"
else
  echo "No selftests found, disabling"
fi

args=(-v -short -coverpkg=./... -coverprofile=coverage.out -count 1 ./...)
if (( $# > 0 )); then
  args=("$@")
fi

export GOFLAGS=-mod=readonly
export CGO_ENABLED=0

echo Testing on "${kernel_version}"
go test -exec "$script --exec-vm $input" "${args[@]}"
echo "Test successful on ${kernel_version}"

rm -r "${input}"


#!/usr/bin/env bash
# Copyright 2009 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

# This script runs or (given -n) prints suggested commands to generate files for
# the Architecture/OS specified by the GOARCH and GOOS environment variables.
# See README.md for more information about how the build system works.

GOOSARCH="${GOOS}_${GOARCH}"

# defaults
mksyscall="go run mksyscall.go"
mkerrors="./mkerrors.sh"
zerrors="zerrors_$GOOSARCH.go"
mksysctl=""
zsysctl="zsysctl_$GOOSARCH.go"
mksysnum=
mktypes=
mkasm=
run="sh"
cmd=""

case "$1" in
-syscalls)
	for i in zsyscall*go
	do
		# Run the command line that appears in the first line
		# of the generated file to regenerate it.
		sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i
		rm _$i
	done
	exit 0
	;;
-n)
	run="cat"
	cmd="echo"
	shift
esac

case "$#" in
0)
	;;
*)
	echo 'usage: mkall.sh [-n]' 1>&2
	exit 2
esac

if [[ "$GOOS" = "linux" ]]; then
	# Use the Docker-based build system
	# Files generated through docker (use $cmd so you can Ctl-C the build or run)
	$cmd docker build --tag generate:$GOOS $GOOS
	$cmd docker run --interactive --tty --volume $(cd -- "$(dirname -- "$0")/.." && /bin/pwd):/build generate:$GOOS
	exit
fi

GOOSARCH_in=syscall_$GOOSARCH.go
case "$GOOSARCH" in
_* | *_ | _)
	echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2
	exit 1
	;;
aix_ppc)
	mkerrors="$mkerrors -maix32"
	mksyscall="go run mksyscall_aix_ppc.go -aix"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
aix_ppc64)
	mkerrors="$mkerrors -maix64"
	mksyscall="go run mksyscall_aix_ppc64.go -aix"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
darwin_amd64)
	mkerrors="$mkerrors -m64"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	mkasm="go run mkasm.go"
	;;
darwin_arm64)
	mkerrors="$mkerrors -m64"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	mkasm="go run mkasm.go"
	;;
dragonfly_amd64)
	mkerrors="$mkerrors -m64"
	mksyscall="go run mksyscall.go -dragonfly"
	mksysnum="go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
freebsd_386)
	mkerrors="$mkerrors -m32"
	mksyscall="go run mksyscall.go -l32"
	mksysnum="go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
freebsd_amd64)
	mkerrors="$mkerrors -m64"
	mksysnum="go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
freebsd_arm)
	mkerrors="$mkerrors"
	mksyscall="go run mksyscall.go -l32 -arm"
	mksysnum="go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
freebsd_arm64)
	mkerrors="$mkerrors -m64"
	mksysnum="go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
freebsd_riscv64)
	mkerrors="$mkerrors -m64"
	mksysnum="go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
netbsd_386)
	mkerrors="$mkerrors -m32"
	mksyscall="go run mksyscall.go -l32 -netbsd"
	mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
netbsd_amd64)
	mkerrors="$mkerrors -m64"
	mksyscall="go run mksyscall.go -netbsd"
	mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
netbsd_arm)
	mkerrors="$mkerrors"
	mksyscall="go run mksyscall.go -l32 -netbsd -arm"
	mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
netbsd_arm64)
	mkerrors="$mkerrors -m64"
	mksyscall="go run mksyscall.go -netbsd"
	mksysnum="go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
openbsd_386)
	mkasm="go run mkasm.go"
	mkerrors="$mkerrors -m32"
	mksyscall="go run mksyscall.go -l32 -openbsd -libc"
	mksysctl="go run mksysctl_openbsd.go"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
openbsd_amd64)
	mkasm="go run mkasm.go"
	mkerrors="$mkerrors -m64"
	mksyscall="go run mksyscall.go -openbsd -libc"
	mksysctl="go run mksysctl_openbsd.go"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
openbsd_arm)
	mkasm="go run mkasm.go"
	mkerrors="$mkerrors"
	mksyscall="go run mksyscall.go -l32 -openbsd -arm -libc"
	mksysctl="go run mksysctl_openbsd.go"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
openbsd_arm64)
	mkasm="go run mkasm.go"
	mkerrors="$mkerrors -m64"
	mksyscall="go run mksyscall.go -openbsd -libc"
	mksysctl="go run mksysctl_openbsd.go"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
openbsd_mips64)
	mkasm="go run mkasm.go"
	mkerrors="$mkerrors -m64"
	mksyscall="go run mksyscall.go -openbsd -libc"
	mksysctl="go run mksysctl_openbsd.go"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
openbsd_ppc64)
	mkasm="go run mkasm.go"
	mkerrors="$mkerrors -m64"
	mksyscall="go run mksyscall.go -openbsd -libc"
	mksysctl="go run mksysctl_openbsd.go"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
openbsd_riscv64)
	mkasm="go run mkasm.go"
	mkerrors="$mkerrors -m64"
	mksyscall="go run mksyscall.go -openbsd -libc"
	mksysctl="go run mksysctl_openbsd.go"
	# Let the type of C char be signed for making the bare syscall
	# API consistent across platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
solaris_amd64)
	mksyscall="go run mksyscall_solaris.go"
	mkerrors="$mkerrors -m64"
	mksysnum=
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
illumos_amd64)
        mksyscall="go run mksyscall_solaris.go"
	mkerrors=
	mksysnum=
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
*)
	echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2
	exit 1
	;;
esac

(
	if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi
	case "$GOOS" in
	*)
		syscall_goos="syscall_$GOOS.go"
		case "$GOOS" in
		darwin | dragonfly | freebsd | netbsd | openbsd)
			syscall_goos="syscall_bsd.go $syscall_goos"
			;;
		esac
		if [ -n "$mksyscall" ]; then
			if [ "$GOOSARCH" == "aix_ppc64" ]; then
				# aix/ppc64 script generates files instead of writing to stdin.
				echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_"$GOOSARCH"_gccgo.go && gofmt -w zsyscall_"$GOOSARCH"_gc.go " ;
			elif [ "$GOOS" == "illumos" ]; then
			        # illumos code generation requires a --illumos switch
			        echo "$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go";
			        # illumos implies solaris, so solaris code generation is also required
				echo "$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go";
			else
				echo "$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go";
			fi
		fi
	esac
	if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi
	if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi
	if [ -n "$mktypes" ]; then echo "$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go"; fi
	if [ -n "$mkasm" ]; then echo "$mkasm $GOOS $GOARCH"; fi
) | $run