#!/usr/bin/env bash
# Copyright (c) Microsoft. All rights reserved.
# Note: Windows Bash doesn't support shebang extra params
set -e

# Sometimes when creating bash scripts in Windows, bash scripts will not have
# the +x flag carried over to Linux/MacOS. This script should help setting the
# permission flags right.

APP_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && cd .. && pwd )/"
cd $APP_HOME

chmod ugo+x ./scripts/build
chmod ugo+x ./scripts/git/setup
chmod ugo+x ./scripts/git/*.sh
chmod ugo+x ./scripts/containers.sh
chmod ugo+x ./scripts/env-vars-setup
chmod ugo+x ./scripts/asamanager.sh
chmod ugo+x ./scripts/devicesimulation.sh
chmod ugo+x ./scripts/iothubmanager.sh
chmod ugo+x ./scripts/config.sh
chmod ugo+x ./scripts/storageadapter.sh
chmod ugo+x ./scripts/telemetry.sh
chmod ugo+x ./scripts/telemetry-agent.sh
chmod ugo+x ./StorageAdapter/run.sh
chmod ugo+x ./IoTHubManager/run.sh
chmod ugo+x ./Config/run.sh
chmod ugo+x ./ASAManager/run.sh
chmod ugo+x ./Telemetry/run.sh

git update-index --chmod=+x ./scripts/build
git update-index --chmod=+x ./scripts/git/setup
git update-index --chmod=+x ./scripts/git/*.sh
git update-index --chmod=+x ./scripts/containers.sh
git update-index --chmod=+x ./scripts/env-vars-setup
git update-index --chmod=+x ./scripts/asamanager.sh
git update-index --chmod=+x ./scripts/devicesimulation.sh
git update-index --chmod=+x ./scripts/iothubmanager.sh
git update-index --chmod=+x ./scripts/config.sh
git update-index --chmod=+x ./scripts/storageadapter.sh
git update-index --chmod=+x ./scripts/telemetry.sh
git update-index --chmod=+x ./scripts/telemetry-agent.sh
git update-index --chmod=+x ./StorageAdapter/run.sh
git update-index --chmod=+x ./IoTHubManager/run.sh
git update-index --chmod=+x ./Config/run.sh
git update-index --chmod=+x ./ASAManager/run.sh
git update-index --chmod=+x ./Telemetry/run.sh

set +e


#!/usr/bin/env bash
# Copyright (c) Microsoft. All rights reserved.
# Note: Windows Bash doesn't support shebang extra params
set -e

# Path relative to .git/hooks/
APP_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && cd .. && pwd )/"
cd $APP_HOME

./scripts/git/pre-commit.sh

set +e


#!/usr/bin/env bash
# Copyright (c) Microsoft. All rights reserved.
# Note: Windows Bash doesn't support shebang extra params
set -e

APP_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && cd .. && pwd )/"
source "$APP_HOME/scripts/git/.functions.sh"

SANDBOX_MODE="$1"

cd $APP_HOME
echo "Current folder: `pwd`"

if git rev-parse --verify HEAD >/dev/null 2>&1 ; then
    against=HEAD
else
    # Initial commit: diff against an empty tree object
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

check_filenames() {
    header "Checking filenames..."

    # Redirect output to stderr.
    exec 1>&2

    # Cross platform projects tend to avoid non-ASCII filenames; prevent
    # them from being added to the repository. We exploit the fact that the
    # printable range starts at the space character and ends with tilde.
    # Note that the use of brackets around a tr range is ok here, (it's
    # even required, for portability to Solaris 10's /usr/bin/tr), since
    # the square bracket bytes happen to fall in the designated range.
    set +e
    if test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 ; then
        error "Attempt to add a non-ASCII file name. This can cause problems on other platforms."
        exit 1
    fi
    set -e
}

check_whitespaces() {
    header "Checking white spaces and line separators..."
    git diff-index --check --cached $against --
}

check_do_not_commit() {
    PATTERN1="DONOT"
    PATTERN1="${PATTERN1}COMMIT"
    PATTERN2="DO NOT"
    PATTERN2="${PATTERN2} COMMIT"
    PATTERN3="DONT"
    PATTERN3="${PATTERN3}COMMIT"
    PATTERN4="DONT"
    PATTERN4="${PATTERN4} COMMIT"
    PATTERN5="DON'T"
    PATTERN5="${PATTERN5} COMMIT"

    header "Checking diff for comments containing '${PATTERN1}'..."

    set +e

    PATT="^\+.*${PATTERN1}.*$"
    diffstr=`git diff --cached $against | grep -ie "$PATT"`
    if [[ -n "$diffstr" ]]; then
        error "You have left '${PATTERN1}' in your changes, you can't commit until it has been removed."
        exit 1
    fi

    PATT="^\+.*${PATTERN2}.*$"
    diffstr=`git diff --cached $against | grep -ie "$PATT"`
    if [[ -n "$diffstr" ]]; then
        error "You have left '${PATTERN2}' in your changes, you can't commit until it has been removed."
        exit 1
    fi

    PATT="^\+.*${PATTERN3}.*$"
    diffstr=`git diff --cached $against | grep -ie "$PATT"`
    if [[ -n "$diffstr" ]]; then
        error "You have left '${PATTERN3}' in your changes, you can't commit until it has been removed."
        exit 1
    fi

    PATT="^\+.*${PATTERN4}.*$"
    diffstr=`git diff --cached $against | grep -ie "$PATT"`
    if [[ -n "$diffstr" ]]; then
        error "You have left '${PATTERN4}' in your changes, you can't commit until it has been removed."
        exit 1
    fi

    PATT="^\+.*${PATTERN5}.*$"
    diffstr=`git diff --cached $against | grep -ie "$PATT"`
    if [[ -n "$diffstr" ]]; then
        error "You have left '${PATTERN5}' in your changes, you can't commit until it has been removed."
        exit 1
    fi

    set -e
}

verify_build() {
    header "Verifying build..."

    cd $APP_HOME/scripts
    if [[ "$SANDBOX_MODE" == "--with-sandbox" ]]; then
        ./build --in-sandbox
    else
        ./build
    fi

    if [ $? -ne 0 ]; then
        error "Some tests failed."
        exit 1
    else
        header "All tests passed"
    fi
}

check_filenames
check_whitespaces
check_do_not_commit
verify_build

set +e


#!/usr/bin/env bash
# Copyright (c) Microsoft. All rights reserved.
# Note: Windows Bash doesn't support shebang extra params
set -e

TEST_SUITE="Storage Adapter tests"

TEST_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/"
APP_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && pwd )/"

source "$APP_HOME/scripts/.functions.sh"

start_containers() {
    header2 "$TEST_SUITE - Starting services..."

    cd $APP_HOME
    ./scripts/storageadapter.sh start
    docker ps -a
}

stop_containers() {
    header2 "$TEST_SUITE - Stopping services..."

    cd $APP_HOME
    docker ps -a
    ./scripts/storageadapter.sh stop
}

run_tests() {
    header2 "$TEST_SUITE - Downloading dependencies..."

    cd $APP_HOME
    dotnet restore

    header2 "$TEST_SUITE - Compiling tests..."
    dotnet build --configuration Release

    header2 "$TEST_SUITE - Running tests..."
    cd $TEST_HOME
    find . -name *.csproj | xargs dotnet test --configuration Release
}

#Script options
repo=""
tag="testing"
dockeraccount="azureiotpcs"

set_up() {
    export DOCKER_TAG=$tag
    export DOCKER_ACCOUNT=$dockeraccount
    check_dependency_docker
    check_dependency_dotnet
}

run() {
    start_containers
    run_tests
    stop_containers
}

tear_down() {
    unset DOCKER_TAG
    unset DOCKER_ACCOUNT
}

#### Parse script arguments
while [[ $# -gt 0 ]] ;
do
    opt=$1;
    shift;
    case $opt in
        -t|--tag) tag=$1; shift;;
        -re|--repo) repo=$1; shift;;
        -da|--docker-account) dockeraccount=$1; shift;;
        *)  shift;;
    esac
done

header "Running $TEST_SUITE"

#### Set Up Tests
set_up

#### Run tests based on repo
if [ "$repo" == "both" ] || [ "$repo" == "" ]; then
    export REPO=dotnet
    run
    export REPO=java
    run
elif [[ "$repo" == "dotnet" ]]; then
    export REPO=dotnet
    run
elif [[ "$repo" == "java" ]]; then
    export REPO=java
    run
else
    error "No build type specified, pass either 'dotnet' or 'java'."
    echo "eg:- sh containers.sh -re java"
    exit 1
fi

#### Tear down test
tear_down

set +e


ï»¿#!/usr/bin/env bash
# Copyright (c) Microsoft. All rights reserved.
# Note: Windows Bash doesn't support shebang extra params
set -e

TEST_SUITE="Device Telemetry Tests"

TEST_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/"
APP_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && pwd )/"

source "$APP_HOME/scripts/.functions.sh"

start_containers() {
    header2 "$TEST_SUITE - Starting services..."

    cd $APP_HOME
    ./scripts/storageadapter.sh start
    ./scripts/telemetry.sh start
    ./scripts/devicesimulation.sh start
    ./scripts/config.sh start
    ./scripts/asamanager.sh start
    docker ps -a
}

stop_containers() {
    header2 "$TEST_SUITE - Stopping services..."

    cd $APP_HOME
    docker ps -a
    ./scripts/storageadapter.sh stop
    ./scripts/telemetry.sh stop
    ./scripts/devicesimulation.sh stop
    ./scripts/config.sh stop
    ./scripts/asamanager.sh stop
}

run_tests() {
    header2 "$TEST_SUITE - Downloading dependencies..."

    cd $APP_HOME
    dotnet restore

    header2 "$TEST_SUITE - Compiling tests..."
    dotnet build --configuration Release

    header2 "$TEST_SUITE - Running tests..."
    cd $TEST_HOME
    find . -name *.csproj | xargs dotnet test --configuration Release
}

#Script options
repo=""
tag="testing"
dockeraccount="azureiotpcs"

set_up() {
    export DOCKER_TAG=$tag
    export DOCKER_ACCOUNT=$dockeraccount
    check_dependency_docker
    check_dependency_dotnet
}

run() {
    start_containers
    run_tests
    stop_containers
}

tear_down() {
    unset DOCKER_TAG
    unset DOCKER_ACCOUNT
}

#### Parse script arguments
while [[ $# -gt 0 ]] ;
do
    opt=$1;
    shift;
    case $opt in
        -t|--tag) tag=$1; shift;;
        -re|--repo) repo=$1; shift;;
        -da|--docker-account) dockeraccount=$1; shift;;
        *)  shift;;
    esac
done

header "Running $TEST_SUITE"

#### Set Up Tests
set_up

#### Run tests based on repo
if [ "$repo" == "both" ] || [ "$repo" == "" ]; then
    export REPO=dotnet
    run
    export REPO=java
    run
elif [[ "$repo" == "dotnet" ]]; then
    export REPO=dotnet
    run
elif [[ "$repo" == "java" ]]; then
    export REPO=java
    run
else
    error "No build type specified, pass either 'dotnet' or 'java'."
    echo "eg:- sh containers.sh -re java"
    exit 1
fi

#### Tear down test
tear_down

set +e


#!/usr/bin/env bash

set -e

APP_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && pwd )/"

cd $APP_HOME

git checkout master
git pull

COL="\e[93m\e[1m"
NOCOL="\e[0m"

echo -e "${COL}### CLI${NOCOL}"
cd $APP_HOME && git submodule update --init cli               && cd cli               && git checkout master && git pull
echo -e "${COL}### Config${NOCOL}"
cd $APP_HOME && git submodule update --init config            && cd config            && git checkout master && git pull
echo -e "${COL}### Device Simulation${NOCOL}"
cd $APP_HOME && git submodule update --init device-simulation && cd device-simulation && git checkout master && git pull
echo -e "${COL}### IoT Hub Manager${NOCOL}"
cd $APP_HOME && git submodule update --init iothub-manager    && cd iothub-manager    && git checkout master && git pull
echo -e "${COL}### Storage Adapter${NOCOL}"
cd $APP_HOME && git submodule update --init storage-adapter   && cd storage-adapter   && git checkout master && git pull
echo -e "${COL}### Telemetry${NOCOL}"
cd $APP_HOME && git submodule update --init telemetry         && cd telemetry         && git checkout master && git pull
echo -e "${COL}### ASA Manager${NOCOL}"
cd $APP_HOME && git submodule update --init asa-manager       && cd asa-manager       && git checkout master && git pull
echo -e "${COL}### Web UI${NOCOL}"
cd $APP_HOME && git submodule update --init webui             && cd webui             && git checkout master && git pull

cd $APP_HOME


#!/usr/bin/env bash

set -e

# Path relative to .git/hooks/
APP_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && cd .. && pwd )/"
source "$APP_HOME/scripts/git/pre-commit.sh"


#!/usr/bin/env bash

set -e
APP_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && cd .. && pwd )/"
source "$APP_HOME/scripts/git/.functions.sh"

cd $APP_HOME
echo "Current folder: `pwd`"

if git rev-parse --verify HEAD >/dev/null 2>&1 ; then
    against=HEAD
else
    # Initial commit: diff against an empty tree object
    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

check_filenames() {
    header "Checking filenames..."

    # Redirect output to stderr.
    exec 1>&2

    # Cross platform projects tend to avoid non-ASCII filenames; prevent
    # them from being added to the repository. We exploit the fact that the
    # printable range starts at the space character and ends with tilde.
    # Note that the use of brackets around a tr range is ok here, (it's
    # even required, for portability to Solaris 10's /usr/bin/tr), since
    # the square bracket bytes happen to fall in the designated range.
    set +e
    if test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0 ; then
        error "Attempt to add a non-ASCII file name. This can cause problems on other platforms."
        exit 1
    fi
    set -e
}

check_whitespaces() {
    header "Checking white spaces and line separators..."
    git diff-index --check --cached $against --
}

check_do_not_commit() {
    PATTERN1="DONOT"
    PATTERN1="${PATTERN1}COMMIT"
    PATTERN2="DO NOT"
    PATTERN2="${PATTERN2} COMMIT"
    PATTERN3="DONT"
    PATTERN3="${PATTERN3}COMMIT"
    PATTERN4="DONT"
    PATTERN4="${PATTERN4} COMMIT"
    PATTERN5="DON'T"
    PATTERN5="${PATTERN5} COMMIT"

    header "Checking diff for comments containing '${PATTERN1}'..."

    set +e

    PATT="^\+.*${PATTERN1}.*$"
    diffstr=`git diff --cached $against | grep -ie "$PATT"`
    if [[ -n "$diffstr" ]]; then
        error "You have left '${PATTERN1}' in your changes, you can't commit until it has been removed."
        exit 1
    fi

    PATT="^\+.*${PATTERN2}.*$"
    diffstr=`git diff --cached $against | grep -ie "$PATT"`
    if [[ -n "$diffstr" ]]; then
        error "You have left '${PATTERN2}' in your changes, you can't commit until it has been removed."
        exit 1
    fi

    PATT="^\+.*${PATTERN3}.*$"
    diffstr=`git diff --cached $against | grep -ie "$PATT"`
    if [[ -n "$diffstr" ]]; then
        error "You have left '${PATTERN3}' in your changes, you can't commit until it has been removed."
        exit 1
    fi

    PATT="^\+.*${PATTERN4}.*$"
    diffstr=`git diff --cached $against | grep -ie "$PATT"`
    if [[ -n "$diffstr" ]]; then
        error "You have left '${PATTERN4}' in your changes, you can't commit until it has been removed."
        exit 1
    fi

    PATT="^\+.*${PATTERN5}.*$"
    diffstr=`git diff --cached $against | grep -ie "$PATT"`
    if [[ -n "$diffstr" ]]; then
        error "You have left '${PATTERN5}' in your changes, you can't commit until it has been removed."
        exit 1
    fi

    set -e
}

verify_build() {
    header "Verifying build..."

    cd $APP_HOME/scripts
    ./build

    if [ $? -ne 0 ]; then
        error "Some tests failed."
        exit 1
    fi
}

check_filenames
check_whitespaces
check_do_not_commit
verify_build


#!/usr/bin/env bash
# Copyright (c) Microsoft. All rights reserved.
# Note: Windows Bash doesn't support shebang extra params
set -e

while [ "$#" -gt 0 ]; do
    case "$1" in
        --version)                      VERSION="$2" ;;
        --git_access_token)             GIT_ACCESS_TOKEN="$2" ;;
        --docker_user)                  DOCKER_USER="$2" ;;
        --docker_pwd)                   DOCKER_PWD="$2" ;;
        --from_docker_namespace)        FROM_DOCKER_NAMESPACE="$2" ;;
        --to_docker_namespace)          TO_DOCKER_NAMESPACE="$2" ;;
        --docker_tag)                   DOCKER_TAG="$2" ;;
        --description)                  DESCRIPTION="$2" ;;
        --pre_release)                  PRE_RELEASE="$2" ;;
        --local)                        LOCAL="$2" ;;
    esac
    shift
done

# Set default values for optional parameters
FROM_DOCKER_NAMESPACE=${FROM_DOCKER_NAMESPACE:-azureiotpcs}
TO_DOCKER_NAMESPACE=${TO_DOCKER_NAMESPACE:-azureiotpcs}
DOCKER_TAG=${DOCKER_TAG:-testing}
DESCRIPTION=${DESCRIPTION:-''}
PRE_RELEASE=${PRE_RELEASE:-false}
LOCAL=${LOCAL:-''}

APP_HOME="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && cd .. && cd .. && pwd )/"

NC="\033[0m" # no color
CYAN="\033[1;36m" # light cyan
YELLOW="\033[1;33m" # yellow
RED="\033[1;31m" # light red

failed() {
    SUB_MODULE=$1
    echo -e "${RED}Cannot find directory $SUB_MODULE${NC}"
    exit 1
}

usage() {
    echo -e "${RED}ERROR: $1 is a required option${NC}"
    echo "Usage: ./release"
    echo -e 'Options:
        --version               Version of this release (required)
        --git_access_token      Git access token to push tag (required)
        --docker_user           Username to login docker hub (required)
        --docker_pwd            Password to login docker hub (required)
        --from_docker_namespace Source namespace of docker image (default:azureiotpcs)
        --to_docker_namespace   Target namespace of docker image (default:azureiotpcs)
        --docker_tag            Source tag of docker image (default:testing)
        --description           Description of this release (default:empty)
        --pre_release           Publish as non-production release on github (default:false)
        --local                 Clean up the local repo at first (default:empty)
        '
    exit 1
}

check_input() {
    if [ ! -n "$VERSION" ]; then
        usage "version"
    fi
    if [ ! -n "$GIT_ACCESS_TOKEN" ]; then
        usage "git_access_token"
    fi
    if [ ! -n "$DOCKER_USER" ]; then
        usage "docker_user"
    fi
    if [ ! -n "$DOCKER_PWD" ]; then
        usage "docker_pwd"
    fi
    echo $DOCKER_PWD | docker login -u $DOCKER_USER --password-stdin
}

tag_release_repo() {
    SUB_MODULE=$1
    REPO_NAME=$2
    DESCRIPTION=$3

    echo
    echo -e "${CYAN}====================================     Start: Tagging the $REPO_NAME repo     ====================================${NC}"
    echo
    echo -e "Current working directory ${CYAN}$APP_HOME$SUB_MODULE${NC}"
    echo
    cd $APP_HOME$SUB_MODULE || failed $SUB_MODULE

    if [ -n "$LOCAL" ]; then
        echo "Cleaning the repo"
        git reset --hard origin/master
        git clean -xdf
    fi
    git checkout master
    git pull --all --prune
    git fetch --tags

    git tag --force $VERSION
    git push https://$GIT_ACCESS_TOKEN@github.com/Azure/$REPO_NAME.git $VERSION

    echo
    echo -e "${CYAN}====================================     End: Tagging $REPO_NAME repo     ====================================${NC}"
    echo

    echo
    echo -e "${CYAN}====================================     Start: Release for $REPO_NAME     ====================================${NC}"
    echo

    # For documentation https://help.github.com/articles/creating-releases/
    DATA="{
        \"tag_name\": \"$VERSION\",
        \"target_commitish\": \"master\",
        \"name\": \"$VERSION\",
        \"body\": \"$DESCRIPTION\",
        \"draft\": false,
        \"prerelease\": $PRE_RELEASE
    }"

    curl -X POST --data "$DATA" https://api.github.com/repos/Azure/$REPO_NAME/releases?access_token=$GIT_ACCESS_TOKEN
    echo
    echo -e "${CYAN}====================================     End: Release for $REPO_NAME     ====================================${NC}"
    echo
}

publish_docker_containers()
{
    DOCKER_CONTAINER_NAME=$1
    SUB_MODULE=$2

    if [ "$SUB_MODULE" == "reverse-proxy" ]; then
        cd $APP_HOME$SUB_MODULE || failed $SUB_MODULE
        if [ -n "$LOCAL" ]; then
            echo "Cleaning the repo"
            git reset --hard origin/master
            git clean -xdf
        fi
        git checkout master
        git pull --all --prune

        echo
        echo -e "${CYAN}====================================     Start: Building $DOCKER_CONTAINER_NAME     ====================================${NC}"
        echo

        BUILD_PATH="build"
        # Building docker containers
        /bin/bash $APP_HOME$SUB_MODULE/$BUILD_PATH

        echo
        echo -e "${CYAN}====================================     End: Building $DOCKER_CONTAINER_NAME     ====================================${NC}"
        echo
    else
        # Pull containers
        echo -e "${CYAN}Pulling $FROM_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$DOCKER_TAG${NC}"
        echo
        docker pull $FROM_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$DOCKER_TAG
    fi

    # Tag containers
    echo -e "${CYAN}Tagging $FROM_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$DOCKER_TAG ==> $TO_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$VERSION${NC}"
    echo
    docker tag $FROM_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$DOCKER_TAG  $TO_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$VERSION

    # Push containers
    echo -e "${CYAN}Pusing container $TO_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$VERSION${NC}"
    docker push $TO_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$VERSION
}

check_input

# Publish Java Microservices docker containers
publish_docker_containers pcs-config-java
publish_docker_containers iothub-manager-java
publish_docker_containers pcs-storage-adapter-java
publish_docker_containers telemetry-java

# Release and tag top-level java repository with latest version
tag_release_repo          services                        remote-monitoring-services-java
tag_release_repo          ""                              azure-iot-pcs-remote-monitoring-java $DESCRIPTION

# Done through dotnet release script
# tag_release_repo          webui                           pcs-remote-monitoring-webui
# PCS CLI
# tag_release_repo          cli                             pcs-cli
# Top Level repo
# publish_docker_containers pcs-remote-monitoring-webui
# publish_docker_containers remote-monitoring-nginx       reverse-proxy

# Only dotnet exists
# publish_docker_containers pcs-diagnostics-dotnet
# publish_docker_containers pcs-auth-dotnet
# publish_docker_containers device-simulation-dotnet
# publish_docker_containers asa-manager-dotnet

set +e


#!/usr/bin/env bash

set -e
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/"
source "$DIR/.functions.sh"

if [[ "$1" == "-a" || "$1" == "--all-options" ]]; then
    ADVANCED=true
else
    ADVANCED=false
fi

SUBSCRIPTION=""
HUB_NAME=""
RESOURCE_GROUP=""
NEW_RESOURCE_GROUP="false"
LOCATION=""
SKU=""
MAXUNITS=""
UNITS=""
D2C_PARTITIONS=""
D2C_TTL=""
C2D_ATTEMPTS=""
C2D_TTL=""
C2D_FEEDBACK_LOCK=""
C2D_FEEDBACK_TTL=""
C2D_FEEDBACK_ATTEMPTS=""

ask_hub_name() {
    header "New Azure IoT Hub"
    HUB_NAME=""

    while [[ -z "$HUB_NAME" ]]; do
        echo -n "Enter IoT Hub name: "
        read HUB_NAME
    done
}

select_resource_group() {
    header "Resource group"

    echo "Existing resource groups"

    azure group list

    echo
    announce "You can re-use an existing group or enter a new name to create a new resource group."
    echo
    RESOURCE_GROUP=""
    while [[ -z "$RESOURCE_GROUP" ]]; do
        echo -n "Enter resource group name: "
        read RESOURCE_GROUP
    done

    NEW_RESOURCE_GROUP="false"
    TEST=$(azure group list | grep -i "$RESOURCE_GROUP")
    if [[ -z "$TEST" ]]; then
        NEW_RESOURCE_GROUP="true"
    fi
}

select_location() {
    header "Azure region"

    # TODO: az account list-locations + filter for IoT Hub
    echo -e "Select the location where to create the hub:"
    PS3=">> "
    select LOCATION in eastus westus westus2 westcentralus northeurope westeurope eastasia southeastasia japaneast japanwest australiaeast australiasoutheast; do
        break;
    done
}

select_sku_and_units() {
    header "Pricing and Scale Tier"

    echo "F1: 8k messages/unit/day (free)"
    echo "S1: 400k messages/unit/day"
    echo "S2: 6M messages/unit/day"
    echo "S3: 300M messages/unit/day"

    echo -e "\nSelect pricing and scale:"
    PS3=">> "
    select SKU in F1 S1 S2 S3; do
        case $SKU in
            F1 ) MAXUNITS=1; break;;
            S1 ) MAXUNITS=200; break;;
            S2 ) MAXUNITS=200; break;;
            S3 ) MAXUNITS=10; break;;
        esac
    done

    UNITS="1"
    if [[ "$SKU" != "F1" ]]; then
        echo -n -e "\nHow many units? (1..${MAXUNITS}) [${UNITS}]: "
        read TEMP
        if [[ ! -z "$TEMP" ]]; then UNITS="$TEMP"; fi
    fi
}

ask_d2c_partitions() {
    D2C_PARTITIONS="2" # 2..128 (2 for F1)
    if [[ "$ADVANCED" == "false" ]]; then return 0; fi

    if [[ "$SKU" != "F1" ]]; then
        echo -n "How many partitions? (1..128) [${D2C_PARTITIONS}]: "
        read TEMP
        if [[ ! -z "$TEMP" ]]; then D2C_PARTITIONS="$TEMP"; fi
    fi
}

ask_d2c_retention() {
    D2C_TTL="1" # 1..7 days
    if [[ "$ADVANCED" == "false" ]]; then return 0; fi

    echo -n "How many days before device-to-cloud messages expire? (1..7) [${D2C_TTL}]: "
    read TEMP
    if [[ ! -z "$TEMP" ]]; then D2C_TTL="$TEMP"; fi
}

ask_c2d_attempts() {
    C2D_ATTEMPTS="10" # 1..100 count
    if [[ "$ADVANCED" == "false" ]]; then return 0; fi

    echo -n "How many attempts to deliver a cloud-to-device message? (1..100) [${C2D_ATTEMPTS}]: "
    read TEMP
    if [[ ! -z "$TEMP" ]]; then C2D_ATTEMPTS="$TEMP"; fi
}

ask_c2d_ttl() {
    # PnYnMnDTnHnMnS
    C2D_TTL="PT1H" # 1 min .. 2 days
    if [[ "$ADVANCED" == "false" ]]; then return 0; fi

    echo -n "How long before cloud-to-device messages expire? (ISO8601: 1 min .. 2 days) [${C2D_TTL}]: "
    read TEMP
    if [[ ! -z "$TEMP" ]]; then C2D_TTL="$TEMP"; fi
}

ask_c2d_feedback_lock() {
    # PnYnMnDTnHnMnS
    C2D_FEEDBACK_LOCK="PT1M" # 5 secs .. 5 mins
    if [[ "$ADVANCED" == "false" ]]; then return 0; fi

    echo -n "How long before cloud-to-device feedback messages lock expire? (ISO8601: 5 secs .. 5 mins) [${C2D_FEEDBACK_LOCK}]: "
    read TEMP
    if [[ ! -z "$TEMP" ]]; then C2D_FEEDBACK_LOCK="$TEMP"; fi
}

ask_c2d_feedback_ttl() {
    # PnYnMnDTnHnMnS
    C2D_FEEDBACK_TTL="PT1M" # 1 min .. 2days
    if [[ "$ADVANCED" == "false" ]]; then return 0; fi

    echo -n "How long before cloud-to-device feedback messages expire? (ISO8601: 1 min .. 2days) [${C2D_FEEDBACK_TTL}]: "
    read TEMP
    if [[ ! -z "$TEMP" ]]; then C2D_FEEDBACK_TTL="$TEMP"; fi
}

ask_c2d_feedback_attempts() {
    C2D_FEEDBACK_ATTEMPTS="1" # 1..100 count
    if [[ "$ADVANCED" == "false" ]]; then return 0; fi

    echo -n "How many attempts to deliver a cloud-to-device feedback message? (1..100) [${C2D_FEEDBACK_ATTEMPTS}]: "
    read TEMP
    if [[ ! -z "$TEMP" ]]; then C2D_FEEDBACK_ATTEMPTS="$TEMP"; fi
}

advanced() {
    if [[ "$ADVANCED" == "true" ]]; then
        header "Other settings";
    else
        announce "Using default settings. Use '--all-options' to manually set all the hub options."
    fi

    ask_d2c_partitions
    ask_d2c_retention
    ask_c2d_attempts
    ask_c2d_ttl
    ask_c2d_feedback_lock
    ask_c2d_feedback_ttl
    ask_c2d_feedback_attempts
}

create_hub() {
    header "Create '$HUB_NAME' in '$LOCATION'"

    if [[ $NEW_RESOURCE_GROUP == "true" ]]; then
        azure group create "$RESOURCE_GROUP" "$LOCATION" || error_and_exit "Unable to create resource group."
    fi

    azure iothub create "$RESOURCE_GROUP" "$HUB_NAME" "$LOCATION" "$SKU" "$UNITS" \
        --enable-dm \
        --d2c-partitions "$D2C_PARTITIONS" \
        --d2c-retention-time-in-days "$D2C_TTL" \
        --c2d-max-delivery-count "$C2D_ATTEMPTS" \
        --c2d-ttl "$C2D_TTL" \
        --feedback-lock-duration "$C2D_FEEDBACK_LOCK" \
        --feedback-ttl "$C2D_FEEDBACK_TTL" \
        --feedback-max-delivery-count "$C2D_FEEDBACK_ATTEMPTS" \
        || error_and_exit "Unable to create IoT Hub"
}

confirm() {
    header "Summary"

    echo "Azure IoT Hub name:             ${HUB_NAME}"
    echo "Resource group name:            ${RESOURCE_GROUP} (new: ${NEW_RESOURCE_GROUP})"
    echo "Azure region:                   ${LOCATION}"
    echo "Pricing and Scaling SKU         ${SKU}"
    echo "Capacity units:                 ${UNITS}"
    echo "D2C events partitions:          ${D2C_PARTITIONS}"
    echo "D2C events TTL:                 ${D2C_TTL} days"
    echo "C2D messages TTL:               ${C2D_TTL}"
    echo "C2D message delivery attempts:  ${C2D_ATTEMPTS}"
    echo "C2D feedback TTL:               ${C2D_FEEDBACK_TTL}"
    echo "C2D feedback delivery attempts: ${C2D_FEEDBACK_ATTEMPTS}"
    echo "C2D feedback lock TTL:          ${C2D_FEEDBACK_LOCK}"
    echo

    echo "Proceed?"
    PS3=">> "
    select SKU in Yes No; do
        case $SKU in
            No ) user_exit;;
            Yes ) break;;
        esac
    done
}

main() {
    check_dependencies
    login

    ask_hub_name
    select_subscription
    select_resource_group
    select_location
    select_sku_and_units
    advanced
    confirm
    create_hub
    show_hub_details "$RESOURCE_GROUP" "$HUB_NAME"

    announce "Tip: to show the hub details, run: ./show-hub.sh $RESOURCE_GROUP $HUB_NAME"
}

main


#!/usr/bin/env bash

set -e
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/"
source "$DIR/.functions.sh"

main() {
    check_dependencies
    login

    header "Azure IoT Hubs in the current subscription"
    az iot hub list | jq '.[] | {name: .name, resourcegroup: .resourcegroup, location: .location, subscription: .subscriptionid}' | jq .
}

main


#!/usr/bin/env bash

set -e
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/"
source "$DIR/.functions.sh"

main() {
    check_dependencies
    login

    header "Azure subscriptions"
    azure account list
    #az account list | jq '.[] | {name: .name, id: .id, current: .isDefault}' | jq .
}

main


#!/usr/bin/env bash

set -e
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/"
source "$DIR/.functions.sh"

SUBSCRIPTION_ID="$1"

check_input() {
    if [[ -z "$SUBSCRIPTION_ID" ]]; then
        announce "Usage: ./select-subscription.sh SUBSCRIPTION_ID"
        echo "Use './list-subscriptions.sh' to see the list of subscriptions."
    fi
}

main() {
    check_input
    check_dependencies
    login

    if [[ ! -z "$SUBSCRIPTION_ID" ]]; then
        header "Changing current subscription"
        #az account set --subscription "$SUBSCRIPTION_ID"
        azure account set "$SUBSCRIPTION_ID"
    else
        select_subscription
    fi
}

main


#!/usr/bin/env bash

set -e
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/"
source "$DIR/.functions.sh"

RESOURCE_GROUP="$1"
HUB_NAME="$2"

check_input() {
    if [[ -z "$RESOURCE_GROUP" || -z "$HUB_NAME" ]]; then
        announce "Usage: ./show-hub.sh RESOURCE_GROUP HUB_NAME"
        echo "Use './list-hubs.sh' to see the list of hubs."
        exit -1
    fi
}

main() {
    check_input
    check_dependencies
    login
    show_hub_details "$RESOURCE_GROUP" "$HUB_NAME"
}

main


#!/bin/bash -ex

APP_PATH="/app"
WEBUICONFIG="${APP_PATH}/webui-config.js"
WEBUICONFIG_SAFE="${APP_PATH}/webui-config.js.safe"
WEBUICONFIG_UNSAFE="${APP_PATH}/webui-config.js.unsafe"
ENVVARS="${APP_PATH}/env-vars"
DOCKERCOMPOSE="${APP_PATH}/docker-compose.yml"
CERTS="${APP_PATH}/certs"
CERT="${CERTS}/tls.crt"
PKEY="${CERTS}/tls.key"

SCRIPTS_REPO="https://raw.githubusercontent.com/Azure/azure-iot-pcs-tools/master/remote-monitoring/single-vm-scripts/"

# ========================================================================

export HOST_NAME="${1:-localhost}"
export APP_RUNTIME="${3:-dotnet}"
export PCS_IOTHUB_CONNSTRING="$8"
export PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING="$9"
export PCS_TELEMETRY_DOCUMENTDB_CONNSTRING="$9"
export PCS_TELEMETRYAGENT_DOCUMENTDB_CONNSTRING="$9"
export PCS_IOTHUBREACT_ACCESS_CONNSTRING="$8"
export PCS_IOTHUBREACT_HUB_NAME="${10}"
export PCS_IOTHUBREACT_HUB_ENDPOINT="${11}"
export PCS_IOTHUBREACT_HUB_PARTITIONS="${12}"
export PCS_IOTHUBREACT_AZUREBLOB_ACCOUNT="${13}"
export PCS_IOTHUBREACT_AZUREBLOB_KEY="${14}"
export PCS_IOTHUBREACT_AZUREBLOB_ENDPOINT_SUFFIX="${15}"
export PCS_CERTIFICATE="${16}"
export PCS_CERTIFICATE_KEY="${17}"
export PCS_BINGMAP_KEY="${18}"
export PCS_AUTH_ISSUER="https://sts.windows.net/${5}/"
export PCS_AUTH_AUDIENCE="$6"
export PCS_WEBUI_AUTH_TYPE="aad"
export PCS_WEBUI_AUTH_AAD_TENANT="$5"
export PCS_WEBUI_AUTH_AAD_APPID="$6"
export PCS_WEBUI_AUTH_AAD_INSTANCE="$7"
export PCS_APPLICATION_SECRET=$(cat /dev/urandom | LC_CTYPE=C tr -dc 'a-zA-Z0-9-,./;:[]\(\)_=^!~' | fold -w 64 | head -n 1)

# TODO: remove temporary fix when projects have moved to use PCS_APPLICATION_SECRET
export APPLICATION_SECRET=$PCS_APPLICATION_SECRET

# ========================================================================

# Configure Docker registry based on host name
# ToDo: we may need to add similar parameter to AzureGermanCloud and AzureUSGovernment
config_for_azure_china() {
    set +e
    local host_name=$1
    if (echo $host_name | grep -c  "\.cn$") ; then
        # If the host name has .cn suffix, dockerhub in China will be used to avoid slow network traffic failure.
        local config_file='/etc/docker/daemon.json'
        echo "{\"registry-mirrors\": [\"https://registry.docker-cn.com\"]}" > ${config_file}
        service docker restart

        # Rewrite the AAD issuer in Azure China environment
        export PCS_AUTH_ISSUER="https://sts.chinacloudapi.cn/$2/"
    fi
    set -e
}

config_for_azure_china $HOST_NAME $5

# ========================================================================

mkdir -p ${APP_PATH}
cd ${APP_PATH}

# ========================================================================

# Docker compose file
DC_SOURCE="https://raw.githubusercontent.com/Azure/azure-iot-pcs-tools/master/remote-monitoring/docker-compose.${APP_RUNTIME}.yml"
wget $DC_SOURCE -O ${DOCKERCOMPOSE}

# ========================================================================

# HTTPS certificates
mkdir -p ${CERTS}
touch ${CERT} && chmod 550 ${CERT}
touch ${PKEY} && chmod 550 ${PKEY}
# Always have quotes around the certificate and key value to preserve the formatting
echo "${PCS_CERTIFICATE}"      > ${CERT}
echo "${PCS_CERTIFICATE_KEY}"  > ${PKEY}

# ========================================================================

# Download scripts
wget $SCRIPTS_REPO/logs.sh     -O /app/logs.sh     && chmod 750 /app/logs.sh
wget $SCRIPTS_REPO/simulate.sh -O /app/simulate.sh && chmod 750 /app/simulate.sh
wget $SCRIPTS_REPO/start.sh    -O /app/start.sh    && chmod 750 /app/start.sh
wget $SCRIPTS_REPO/stats.sh    -O /app/stats.sh    && chmod 750 /app/stats.sh
wget $SCRIPTS_REPO/status.sh   -O /app/status.sh   && chmod 750 /app/status.sh
wget $SCRIPTS_REPO/stop.sh     -O /app/stop.sh     && chmod 750 /app/stop.sh

# Temporarily disabled - The update scenario requires some work
# wget $SCRIPTS_REPO/update.sh   -O /app/update.sh   && chmod 750 /app/update.sh

# ========================================================================

# Web App configuration
touch ${WEBUICONFIG} && chmod 444 ${WEBUICONFIG}
touch ${WEBUICONFIG_SAFE} && chmod 444 ${WEBUICONFIG_SAFE}
touch ${WEBUICONFIG_UNSAFE} && chmod 444 ${WEBUICONFIG_UNSAFE}

echo "var DeploymentConfig = {"                       >> ${WEBUICONFIG_SAFE}
echo "  authEnabled: true,"                           >> ${WEBUICONFIG_SAFE}
echo "  authType: '${PCS_WEBUI_AUTH_TYPE}',"          >> ${WEBUICONFIG_SAFE}
echo "  aad : {"                                      >> ${WEBUICONFIG_SAFE}
echo "    tenant: '${PCS_WEBUI_AUTH_AAD_TENANT}',"    >> ${WEBUICONFIG_SAFE}
echo "    appId: '${PCS_WEBUI_AUTH_AAD_APPID}',"      >> ${WEBUICONFIG_SAFE}
echo "    instance: '${PCS_WEBUI_AUTH_AAD_INSTANCE}'" >> ${WEBUICONFIG_SAFE}
echo "  }"                                            >> ${WEBUICONFIG_SAFE}
echo "}"                                              >> ${WEBUICONFIG_SAFE}

echo "var DeploymentConfig = {"                       >> ${WEBUICONFIG_UNSAFE}
echo "  authEnabled: false,"                          >> ${WEBUICONFIG_UNSAFE}
echo "  authType: '${PCS_WEBUI_AUTH_TYPE}',"          >> ${WEBUICONFIG_UNSAFE}
echo "  aad : {"                                      >> ${WEBUICONFIG_UNSAFE}
echo "    tenant: '${PCS_WEBUI_AUTH_AAD_TENANT}',"    >> ${WEBUICONFIG_UNSAFE}
echo "    appId: '${PCS_WEBUI_AUTH_AAD_APPID}',"      >> ${WEBUICONFIG_UNSAFE}
echo "    instance: '${PCS_WEBUI_AUTH_AAD_INSTANCE}'" >> ${WEBUICONFIG_UNSAFE}
echo "  }"                                            >> ${WEBUICONFIG_UNSAFE}
echo "}"                                              >> ${WEBUICONFIG_UNSAFE}

cp -p ${WEBUICONFIG_SAFE} ${WEBUICONFIG}

# ========================================================================

# Environment variables
touch ${ENVVARS} && chmod 440 ${ENVVARS}

echo "export HOST_NAME=\"${HOST_NAME}\""                                                                 >> ${ENVVARS}
echo "export APP_RUNTIME=\"${APP_RUNTIME}\""                                                             >> ${ENVVARS}
echo "export PCS_AUTH_ISSUER=\"${PCS_AUTH_ISSUER}\""                                                     >> ${ENVVARS}
echo "export PCS_AUTH_AUDIENCE=\"${PCS_AUTH_AUDIENCE}\""                                                 >> ${ENVVARS}
echo "export PCS_AUTH_AAD_GLOBAL_TENANTID=\"${PCS_AUTH_AAD_GLOBAL_TENANTID}\""                           >> ${ENVVARS}
echo "export PCS_AUTH_AAD_GLOBAL_CLIENTID=\"${PCS_AUTH_AAD_GLOBAL_CLIENTID}\""                           >> ${ENVVARS}
echo "export PCS_AUTH_AAD_GLOBAL_LOGINURI=\"${PCS_AUTH_AAD_GLOBAL_LOGINURI}\""                           >> ${ENVVARS}
echo "export PCS_IOTHUB_CONNSTRING=\"${PCS_IOTHUB_CONNSTRING}\""                                         >> ${ENVVARS}
echo "export PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING=\"${PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING}\""   >> ${ENVVARS}
echo "export PCS_TELEMETRY_DOCUMENTDB_CONNSTRING=\"${PCS_TELEMETRY_DOCUMENTDB_CONNSTRING}\""             >> ${ENVVARS}
echo "export PCS_TELEMETRYAGENT_DOCUMENTDB_CONNSTRING=\"${PCS_TELEMETRYAGENT_DOCUMENTDB_CONNSTRING}\""   >> ${ENVVARS}
echo "export PCS_IOTHUBREACT_ACCESS_CONNSTRING=\"${PCS_IOTHUBREACT_ACCESS_CONNSTRING}\""                 >> ${ENVVARS}
echo "export PCS_IOTHUBREACT_HUB_NAME=\"${PCS_IOTHUBREACT_HUB_NAME}\""                                   >> ${ENVVARS}
echo "export PCS_IOTHUBREACT_HUB_ENDPOINT=\"${PCS_IOTHUBREACT_HUB_ENDPOINT}\""                           >> ${ENVVARS}
echo "export PCS_IOTHUBREACT_HUB_PARTITIONS=\"${PCS_IOTHUBREACT_HUB_PARTITIONS}\""                       >> ${ENVVARS}
echo "export PCS_IOTHUBREACT_AZUREBLOB_ACCOUNT=\"${PCS_IOTHUBREACT_AZUREBLOB_ACCOUNT}\""                 >> ${ENVVARS}
echo "export PCS_IOTHUBREACT_AZUREBLOB_KEY=\"${PCS_IOTHUBREACT_AZUREBLOB_KEY}\""                         >> ${ENVVARS}
echo "export PCS_IOTHUBREACT_AZUREBLOB_ENDPOINT_SUFFIX=\"${PCS_IOTHUBREACT_AZUREBLOB_ENDPOINT_SUFFIX}\"" >> ${ENVVARS}
echo "export PCS_BINGMAP_KEY=\"${PCS_BINGMAP_KEY}\""                                                     >> ${ENVVARS}
echo "export PCS_APPLICATION_SECRET=\"${PCS_APPLICATION_SECRET}\""                                       >> ${ENVVARS}
echo ""                                                                                >> ${ENVVARS}
echo "##########################################################################################"        >> ${ENVVARS}
echo "# Development settings, don't change these in Production"                                          >> ${ENVVARS}
echo "# You can run 'start.sh --unsafe' to temporarily disable Auth and Cross-Origin protections"        >> ${ENVVARS}
echo ""                                                                                >> ${ENVVARS}
echo "# Format: true | false"                                                                            >> ${ENVVARS}
echo "# empty => Auth required"                                                                          >> ${ENVVARS}
echo "export PCS_AUTH_REQUIRED=\"\""                                                                     >> ${ENVVARS}
echo ""                                                                                >> ${ENVVARS}
echo "# Format: { 'origins': ['*'], 'methods': ['*'], 'headers': ['*'] }"                                >> ${ENVVARS}
echo "# empty => CORS support disabled"                                                                  >> ${ENVVARS}
echo "export PCS_CORS_WHITELIST=\"\""                                                                    >> ${ENVVARS}

# ========================================================================

nohup /app/start.sh &


#!/bin/bash -e

cd /app

if [[ "$1" == "" ]]; then
  docker-compose logs
else
  docker logs -f --tail 100 $1
fi


#!/bin/bash -e

cd /app

echo "Starting simulation..."
ISUP=$(curl -sk https://localhost/devicesimulation/v1/status | grep "Alive" | wc -l)
while [[ "$ISUP" == "0" ]]; do
  echo "Waiting for simulation service to be available..."
  sleep 4
  ISUP=$(curl -sk https://localhost/devicesimulation/v1/status | grep "Alive" | wc -l)
done
curl -sk -X POST "https://localhost/devicesimulation/v1/simulations?template=default" -H "content-type: application/json" -d "{}"
echo


#!/bin/bash -e

cd /app

source "env-vars"

COL_NO="\033[0m" # no color
COL_ERR="\033[1;31m" # light red

APP_PATH="/app"
WEBUICONFIG="${APP_PATH}/webui-config.js"
WEBUICONFIG_SAFE="${APP_PATH}/webui-config.js.safe"
WEBUICONFIG_UNSAFE="${APP_PATH}/webui-config.js.unsafe"

rm -f ${WEBUICONFIG}
cp -p ${WEBUICONFIG_SAFE} ${WEBUICONFIG}

if [[ "$1" == "--unsafe" ]]; then
  echo -e "${COL_ERR}WARNING! Starting services in UNSAFE mode!${COL_NO}"
  # Disable Auth
  export PCS_AUTH_REQUIRED="false"
  # Allow cross-origin requests from anywhere
  export PCS_CORS_WHITELIST="{ 'origins': ['*'], 'methods': ['*'], 'headers': ['*'] }"

  rm -f ${WEBUICONFIG}
  cp -p ${WEBUICONFIG_UNSAFE} ${WEBUICONFIG}
fi

list=$(docker ps -aq)
if [ -n "$list" ]; then
    docker rm -f $list
fi
rm -f nohup.out

nohup docker-compose up &

ISUP=$(curl -ks https://localhost/ | grep -i "html" | wc -l)
while [[ "$ISUP" == "0" ]]; do
  echo "Waiting for web site to start..."
  sleep 3
  ISUP=$(curl -ks https://localhost/ | grep -i "html" | wc -l)
done


#!/bin/bash -e

cd /app

docker stats -a


#!/bin/bash -e

cd /app

echo

docker-compose ps

COL_NO="\033[0m" # no color
COL_MARK="\033[1;33m" # yellow

echo -e "\n${COL_MARK}Run ./logs.sh <service name> to see the logs of a service.${COL_NO}"


#!/bin/bash -e

list=$(docker ps -aq)

if [ -n "$list" ]; then
    docker rm -f $list
fi


#!/bin/bash -ex

# Where to download scripts from
SCRIPTS_REPO="https://raw.githubusercontent.com/Azure/azure-iot-pcs-tools/master/remote-monitoring/single-vm-scripts/"

cd /app

# Download scripts
wget $SCRIPTS_REPO/logs.sh     -O /app/logs.sh     && chmod 750 /app/logs.sh
wget $SCRIPTS_REPO/simulate.sh -O /app/simulate.sh && chmod 750 /app/simulate.sh
wget $SCRIPTS_REPO/start.sh    -O /app/start.sh    && chmod 750 /app/start.sh
wget $SCRIPTS_REPO/stats.sh    -O /app/stats.sh    && chmod 750 /app/stats.sh
wget $SCRIPTS_REPO/status.sh   -O /app/status.sh   && chmod 750 /app/status.sh
wget $SCRIPTS_REPO/stop.sh     -O /app/stop.sh     && chmod 750 /app/stop.sh
wget $SCRIPTS_REPO/update.sh   -O /app/update.sh   && chmod 750 /app/update.sh

# Stop the services, so Docker images are not in use
./stop.sh

# Update Docker images
docker-compose pull --ignore-pull-failure

# Start the services
./start.sh


#!/bin/bash

set -e

sdk_root="$HOME"
openwrt_folder="openwrt"
openwrt_sdk_folder="sdk"
working_dir=$PWD
iot_dir="azure-iot-sdk-c"

usage ()
{
    echo 'build.sh [options]'
    echo 'options'
    echo ' -d, --sdkroot   OpenWRT SDK root directory'
    echo '                 (default: $HOME)'
    exit 1
}

process_args ()
{
    while [ ! -z "$1" ] && [ ! -z "$2" ]
    do
        if [ "$1" == "-d" ] || [ "$1" == "--sdkroot" ]
        then
            sdk_root="$2"
        else
            usage
        fi

        shift
        shift
    done
}

build_iot()
{
    echo "Building IoT"
    rm -d -f -r $sdk_root/$openwrt_folder/$openwrt_sdk_folder/package/$iot_dir
    mkdir $sdk_root/$openwrt_folder/$openwrt_sdk_folder/package/$iot_dir
    mkdir $sdk_root/$openwrt_folder/$openwrt_sdk_folder/package/$iot_dir/src
    cp -f "$working_dir/Makefile.iot" "$sdk_root/$openwrt_folder/$openwrt_sdk_folder/package/$iot_dir/Makefile"
    cd "$working_dir/../../.."
    cp -R -f . "$sdk_root/$openwrt_folder/$openwrt_sdk_folder/package/$iot_dir/src"
    cd "$sdk_root/$openwrt_folder/$openwrt_sdk_folder"
    make V=s "package/$iot_dir/compile"
}

process_args $*

build_iot


#!/bin/bash

set -e

install_root="$HOME"
openwrt_folder="openwrt"
openwrt_sdk_folder="sdk"
working_dir=$PWD
package_dir="package"

iot_dir="azure-iot-sdk-c"
iot_repo="https://github.com/Azure/azure-iot-sdk-c.git"
iot_makefile="Makefile.iot"

usage ()
{
    echo 'setup.sh [options]'
    echo 'options'
    echo ' -d, --installdir   OpenWRT SDK root directory'
    echo '                    (default: $HOME)'
    exit 1
}

process_args ()
{
    while [ ! -z "$1" ] && [ ! -z "$2" ]
    do
        if [ "$1" == "-d" ] || [ "$1" == "--installdir" ]
        then
            install_root="$2"
        else
            usage
        fi

        shift
        shift
    done
}

setup_sdk()
{
  # Check if SDK is installed
  #if [ ! -d "$install_root/$openwrt_folder/$openwrt_sdk_folder" ]
  #then
    # Kickoff the SDK installation since it doesn't exists
    ./setup_sdk.sh -d $install_root
  #fi
}

process_args $*

setup_sdk


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.
cd $STAGING_DIR
echo $NEWTIN | sudo -S rm -r azure-iot-pal-arduino
git clone https://github.com/Azure/azure-iot-pal-arduino.git

cd azure-iot-pal-arduino
echo "copying sdk sources path to pal layer now"
echo $NEWTIN | sudo -S cp -r $SOURCES_DIR/. sdk/

cd build_all

python3 make_sdk.py -o $ARDUINO_LIBRARY_DIR

# input WIFI_SSID, WIFI_PWD, and IOTHUB_CONNECTION_DEVICE_STRING into iot_config.h

cd $ARDUINO_LIBRARY_DIR/AzureIoTHub/examples/esp8266/iothub_ll_telemetry_sample/
echo $NEWTIN | sudo -S sed -i 's/your-wifi-name/'$WIFI_SSID'/g' iot_configs.h
echo $NEWTIN | sudo -S sed -i 's/your-wifi-pwd/'$WIFI_PWD'/g' iot_configs.h
echo $NEWTIN | sudo -S sed -i 's@your-iothub-DEVICE-connection-string@'$IOTHUB_CONNECTION_DEVICE_STRING'@g' iot_configs.h

cd $ARDUINO_LIBRARY_DIR/AzureIoTHub/examples/esp32/iothub_ll_telemetry_sample/
echo $NEWTIN | sudo -S sed -i 's/your-wifi-name/'$WIFI_SSID'/g' iot_configs.h
echo $NEWTIN | sudo -S sed -i 's/your-wifi-pwd/'$WIFI_PWD'/g' iot_configs.h
echo $NEWTIN | sudo -S sed -i 's@your-iothub-DEVICE-connection-string@'$IOTHUB_CONNECTION_DEVICE_STRING'@g' iot_configs.h


#!/bin/bash

set -e

sdk_repo="http://download.linino.org/linino-utils/OpenWrt-SDK-ar71xx-for-linux-x86_64-gcc-4.6-linaro_uClibc-0.9.33.2-32bit.tar.bz2"
sdk_repo_x86="http://download.linino.org/linino-utils/OpenWrt-SDK-ar71xx-for-linux-x86_64-gcc-4.6-linaro_uClibc-0.9.33.2-32bit.tar.bz2"
sdk_repo_x64="http://download.linino.org/linino-utils/OpenWrt-SDK-ar71xx-for-linux-x86_64-gcc-4.6-linaro_uClibc-0.9.33.2-64bit.tar.bz2"
install_root="$HOME"
openwrt_folder="openwrt"
openwrt_sdk_folder="sdk"
working_dir=$PWD
package_dir="package"

MACHINE_TYPE=`uname -m`

usage ()
{
    echo 'setup_sdk.sh [options]'
    echo 'options'
    echo ' -d, --installdir   destination root directory for OpenWRT SDK installation'
    echo '                    (default: $HOME)'
    echo ' -s, --sdk          url of the prebuilt OpenWRT SDK archive'
    echo '                    (default: http://download.linino.org/linino-utils/OpenWrt-SDK-ar71xx-for-linux-x86_64-gcc-4.6-linaro_uClibc-0.9.33.2-32bit.tar.bz2)'
    exit 1
}

process_args ()
{
    while [ ! -z "$1" ] && [ ! -z "$2" ]
    do
        if [ "$1" == "-d" ] || [ "$1" == "--installdir" ]
        then
          install_root="$2"
        elif [ "$1" == "-s" ] || [ "$1" == "--sdk" ]
        then
          sdk_repo="$2"
        else
          usage
        fi

        shift
        shift
    done
}

download_sdk()
{
  if [ -d  "$install_root/$openwrt_folder/$openwrt_sdk_folder" ]
	then
    # SDK folder already exists ask to reinstall SDK
    read -p "The OpenWRT SDK ($install_root/$openwrt_folder/$openwrt_sdk_folder) already exists. Do you want to delete and reinstall? (Y/N)" input_var
    if [ ! "$input_var" == "y" ] && [ ! "$input_var" == "Y" ]
    then
      return
    fi
	fi

  read -p "Download and installation of the OpenWRT SDK may take some time. Do you want to continue? (Y/N)" input_var
  if [ ! "$input_var" == "y" ] && [ ! "$input_var" == "Y" ]
  then
    exit 1
  fi

	echo "Downloading OpenWRT SDK to $install_root/$openwrt_folder"

  cd $install_root

	if [ ! -d  $openwrt_folder ]
	then
		mkdir $openwrt_folder
	fi

  # Download the SDK
  cd $openwrt_folder

  if [ -d $openwrt_sdk_folder ]
  then
    rm -r -f $openwrt_sdk_folder
  fi

  if [ "$1" == "-s" ] || [ "$1" == "--sdk" ]
  then
    wget $sdk_repo -O openwrtsdk.tar.bz2
  elif [ ${MACHINE_TYPE} == 'x86_64' ]
  then
    wget $sdk_repo_x64 -O openwrtsdk.tar.bz2
  else
    wget $sdk_repo_x86 -O openwrtsdk.tar.bz2
  fi

  tar xvf openwrtsdk.tar.bz2

  # get folders only
  folders=(*/)

  # assuming the only and first file is the name of the extracted archive
  extractedFolder=${folders[0]}

  mv $extractedFolder $openwrt_sdk_folder

  patch_sdk
}

patch_sdk()
{
  #removing cmake from the toolchain
  mv "$install_root/$openwrt_folder/$openwrt_sdk_folder/staging_dir/host/bin/cmake" "$install_root/$openwrt_folder/$openwrt_sdk_folder/staging_dir/host/bin/cmake.old"
}

process_args $*
echo "Installing OpenWRT SDK to $install_root/$openwrt_folder/$openwrt_sdk_folder"

download_sdk

echo "Finished installing the OpenWRT SDK"


#!/bin/bash
#set -o pipefail
#

set -e
set -x

script_dir=$(cd "$(dirname "$0")" && pwd)
build_root=$(cd "${script_dir}/../.." && pwd)
log_dir=$build_root
run_e2e_tests=OFF
run_sfc_tests=OFF
run_longhaul_tests=OFF
build_amqp=ON
build_http=ON
build_mqtt=ON
no_blob=OFF
run_unittests=OFF
run_valgrind=0
build_folder=$build_root"/cmake"
make=true
toolchainfile=" "
cmake_install_prefix=" "
no_logging=OFF
prov_auth=OFF
prov_use_tpm_simulator=OFF
use_edge_modules=OFF
hsm_type_sastoken=OFF
hsm_type_symm_key=OFF
hsm_type_x509=OFF
hsm_type_riot=OFF
enable_ipv6=OFF
build_config=Debug

usage ()
{
    echo "build.sh [options]"
    echo "options"
    echo " -cl, --compileoption <value>  specify a compile option to be passed to gcc"
    echo "   Example: -cl -O1 -cl ..."
    echo " --run-e2e-tests               run the end-to-end tests (e2e tests are skipped by default)"
    echo " --run-sfc-tests               run the end-to-end tests for Service Faults (sfc tests are skipped by default)"
    echo " --run-unittests               run the unit tests"
    echo " --run-longhaul-tests          run long haul tests (long haul tests are not run by default)"
    echo ""
    echo " --no-amqp                     do no build AMQP transport and samples"
    echo " --no-http                     do no build HTTP transport and samples"
    echo " --no-mqtt                     do no build MQTT transport and samples"
    echo " --no_uploadtoblob             do no build upload to blob"
    echo " --no-make                     do not run make after cmake"
    echo " --toolchain-file <file>       pass cmake a toolchain file for cross compiling"
    echo " --install-path-prefix         alternative prefix for make install"
    echo " -rv, --run_valgrind           will execute ctest with valgrind"
    echo " --no-logging                  Disable logging"
    echo " --provisioning                Use Provisioning with Flow"
    echo " --use-tpm-simulator           Build TPM simulator"
    echo " --use-edge-modules            Build Edge modules"
    echo " --use-hsmsymmkey              Build with HSM for Symmetric Key"
    echo " --use-hsmsas                  Build with HSM for TPM"
    echo " --use-hsmx509                 Build with HSM for X509 Client Authentication"
    echo " --use-hsmriot                 Build with HSM for RIoT/DICE"
    echo " --use-ipv6-dualstack          Build with IPv6 dual stack support"
    echo " --config <value>              [Debug] build configuration (e.g. Debug, Release)"
    exit 1
}

process_args ()
{
    save_next_arg=0
    extracloptions=" "

    for arg in $*
    do
      if [ $save_next_arg == 1 ]
      then
        # save arg to pass to gcc
        extracloptions="$arg $extracloptions"
        save_next_arg=0
      elif [ $save_next_arg == 2 ]
      then
        # save arg to pass as toolchain file
        toolchainfile="$arg"
           save_next_arg=0
      elif [ $save_next_arg == 3 ]
      then
        # save arg for install prefix
        cmake_install_prefix="$arg"
        save_next_arg=0
      elif [ $save_next_arg == 4 ]
      then
        # save arg for build config type
        build_config="$arg"
        save_next_arg=0
      else
          case "$arg" in
              "-cl" | "--compileoption" ) save_next_arg=1;;
              "--run-e2e-tests" ) run_e2e_tests=ON;;
              "--run-unittests" ) run_unittests=ON;;
              "--run-longhaul-tests" ) run_longhaul_tests=ON;;
              "--no-amqp" ) build_amqp=OFF;;
              "--no-http" ) build_http=OFF;;
              "--no-mqtt" ) build_mqtt=OFF;;
              "--no_uploadtoblob" ) no_blob=ON;;
              "--no-make" ) make=false;;
              "--toolchain-file" ) save_next_arg=2;;
              "-rv" | "--run_valgrind" ) run_valgrind=1;;
              "--no-logging" ) no_logging=ON;;
              "--install-path-prefix" ) save_next_arg=3;;
              "--provisioning" ) prov_auth=ON;;
              "--use-tpm-simulator" ) prov_use_tpm_simulator=ON;;
              "--run-sfc-tests" ) run_sfc_tests=ON;;
              "--use-edge-modules") use_edge_modules=ON;;
              "--use-hsmsymmkey")  hsm_type_symm_key=ON;;
              "--use-hsmsas")  hsm_type_sastoken=ON;;
              "--use-hsmx509") hsm_type_riot=OFF; hsm_type_x509=ON;;
              "--use-hsmriot") hsm_type_riot=ON; hsm_type_x509=OFF;;
              "--use-ipv6-dualstack") enable_ipv6=ON;;
              "--config") save_next_arg=4;;
              * ) usage;;
          esac
      fi
    done

    if [ "$toolchainfile" != " " ]
    then
      toolchainfile=$(readlink -f $toolchainfile)
      toolchainfile="-DCMAKE_TOOLCHAIN_FILE=$toolchainfile"
    fi

   if [ "$cmake_install_prefix" != " " ]
   then
     cmake_install_prefix="-DCMAKE_INSTALL_PREFIX=$cmake_install_prefix"
   fi
}

process_args $*

rm -r -f $build_folder
mkdir -m777 -p $build_folder
pushd $build_folder
echo "Generating Build Files"
cmake $toolchainfile $cmake_install_prefix $build_root -Drun_valgrind:BOOL=$run_valgrind -DcompileOption_C:STRING="$extracloptions" -Drun_e2e_tests:BOOL=$run_e2e_tests -Drun_sfc_tests:BOOL=$run_sfc_tests -Drun_longhaul_tests=$run_longhaul_tests -Duse_amqp:BOOL=$build_amqp -Duse_http:BOOL=$build_http -Duse_mqtt:BOOL=$build_mqtt -Ddont_use_uploadtoblob:BOOL=$no_blob -Drun_unittests:BOOL=$run_unittests -Dno_logging:BOOL=$no_logging -Duse_prov_client:BOOL=$prov_auth -Duse_tpm_simulator:BOOL=$prov_use_tpm_simulator -Duse_edge_modules=$use_edge_modules -Dhsm_type_riot=$hsm_type_riot -Dhsm_type_x509=$hsm_type_x509 -Dhsm_type_symm_key=$hsm_type_symm_key -Dhsm_type_sastoken=$hsm_type_sastoken -Denable_ipv6=$enable_ipv6 -DCMAKE_BUILD_TYPE=$build_config
chmod --recursive ugo+rw ../cmake

# Set the default cores
MAKE_CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)

echo "Initial MAKE_CORES=$MAKE_CORES"

# Make sure there is enough virtual memory on the device to handle more than one job
MINVSPACE="1500000"

# Acquire total memory and total swap space setting them to zero in the event the command fails
MEMAR=( $(sed -n -e 's/^MemTotal:[^0-9]*\([0-9][0-9]*\).*/\1/p' -e 's/^SwapTotal:[^0-9]*\([0-9][0-9]*\).*/\1/p' /proc/meminfo) )
[ -z "${MEMAR[0]##*[!0-9]*}" ] && MEMAR[0]=0
[ -z "${MEMAR[1]##*[!0-9]*}" ] && MEMAR[1]=0

let VSPACE=${MEMAR[0]}+${MEMAR[1]}

echo "VSPACE=$VSPACE"

if [ "$VSPACE" -lt "$MINVSPACE" ] ; then
  echo "WARNING: Not enough space.  Setting MAKE_CORES=1"
  MAKE_CORES=1
fi

echo "Building Project"
cmake --build . -- --jobs=$MAKE_CORES

popd


#! /bin/bash

# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -o errexit # Exit if command failed.
set -o pipefail # Exit if pipe failed.

# Only for testing E2E behaviour !!!
TEST_CORES=16

# Refresh dynamic libs to link to
sudo ldconfig

ctest -T test --no-compress-output -C "Debug" -V -j $TEST_CORES --schedule-random


#! /bin/bash

# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -o errexit # Exit if command failed.
set -o pipefail # Exit if pipe failed.

# Only for testing E2E behaviour !!!
TEST_CORES=16

# Refresh dynamic libs to link to
sudo ldconfig

ctest --overwrite MemoryCheckCommandOptions="--leak-check=full --error-exitcode=100" -T MemCheck --no-compress-output -C "Debug" -V -j $TEST_CORES --schedule-random


#!/bin/bash

#This script updates a fresh Ubuntu installation with all the dependent
# components necessary to use the IoT Client SDK for C.

repo_name_from_uri()
{
    echo "$1" | sed -e 's|/$||' -e 's|:*/*\.git$||' -e 's|.*[/:]||g'
}

scriptdir=$(cd "$(dirname "$0")" && pwd)
deps="curl build-essential pkg-config libcurl4-openssl-dev git cmake libssl-dev uuid-dev valgrind"
repo="https://github.com/Azure/azure-iot-sdk-c.git"
repo_name=$(repo_name_from_uri $repo)

push_dir () { pushd $1 > /dev/null; }
pop_dir () { popd $1 > /dev/null; }

repo_exists ()
{
    push_dir "$scriptdir"
    [ "$(git rev-parse --is-inside-work-tree)" == "true" ] || return 1
    origin=$(git config remote.origin.url) || return 1
    actual_name=$(repo_name_from_uri $origin)
    [ "${repo_name,,}" == "${actual_name,,}" ] || return 1
    pop_dir
}

deps_install ()
{
    sudo apt-get update
    sudo apt-get install -y $deps
}

clone_source ()
{
    git clone $repo
}

deps_install

if repo_exists
then
    echo "Repo $repo_name already cloned"
    push_dir "$(git rev-parse --show-toplevel)"
else
    clone_source || exit 1
    push_dir "$repo_name"
fi

pop_dir


#!/bin/bash
#set -o pipefail
#

azureiot_folder="azure-iot-sdk"
azureiot_repo="https://github.com/Azure/azure-iot-sdk-c"
azureiot_c_folder="azure-iot-sdk-c-0.1.0"
azureiot_c_zip_folder="azure-iot-sdk-c-0.1.0.tar.gz"
azureiot_c_change_file="azure-iot-sdk-c_0.1.0-1_source.changes"

sync_azureiot()
{
	echo Sync Azure IoT SDK
	echo $azureiot_repo

	git clone $azureiot_repo $azureiot_folder
}

setup_debian_folder()
{
	cd ~/$azureiot_folder
	mv c $azureiot_c_folder
	tar czvf $azureiot_c_zip_folder $azureiot_c_folder
	cd $azureiot_c_folder
	dh_make -y -l -c mit -e aziotsdklinux@outlook.com -f ../$azureiot_c_zip_folder

	# Remove the debian folder
	dh_make -y -l -c mit -e aziotsdklinux@outlook.com -f ../$azureiot_c_zip_folder
	cp -r ~/$azureiot_folder/$azureiot_c_folder/build_all/packaging/linux/debian ./
}

build_package()
{
	cd ..
	echo build package
	dpkg-buildpackage -us -uc

	# Sign the packages
	dpkg-buildpackage -S
}

upload_to_Launchpad()
{
	dput ppa:aziotsdklinux/ppa-azure-iot-sdk-c $azureiot_c_file
}

sync_azureiot
build_package


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

# Print version
cat /etc/*release | grep VERSION*
gcc --version
openssl version
curl --version

build_root=$(cd "$(dirname "$0")/.." && pwd)
cd $build_root

build_folder=$build_root"/cmake"

# Set the default cores
CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)

if [ $CORES -eq 1 ]
then
    LOADLIMIT=$CORES
else
    LOADLIMIT=$(perl -e "print int($CORES * 0.8)")
fi

rm -r -f $build_folder
mkdir -p $build_folder
pushd $build_folder
cmake -Drun_valgrind:BOOL=ON $build_root -Drun_unittests:BOOL=ON

echo "Running: make --jobs=$CORES --max-load=$LOADLIMIT"
make --jobs=$CORES --max-load=$LOADLIMIT

popd


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

# Print version
cat /etc/*release | grep VERSION*
gcc --version

# Set the default cores
CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)

build_root=$(cd "$(dirname "$0")/.." && pwd)
clone_root=$(cd "$(dirname "$0")/../.." && pwd)
cd $build_root

echo "Build Root $build_root"

sdk_build_folder=$build_root"/cmake"

# Build the SDK
rm -rf $sdk_build_folder
mkdir -p $sdk_build_folder
pushd $sdk_build_folder
cmake $build_root -Duse_prov_client=ON
make install --jobs=$CORES
popd

cd "$clone_root"

echo "Clone the back compat repo"
git clone https://github.com/Azure/azure-iot-c-back-compat.git --recursive

back_compat_root="$clone_root/azure-iot-c-back-compat"

pushd $back_compat_root

# Now run back compat
rm -rf cmake
mkdir -p cmake
pushd cmake
cmake ..
make --jobs=$CORES

popd


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

# Print version
cat /etc/*release | grep VERSION*
gcc --version
curl --version

# Set the default cores
CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)
cmake . -Bcmake -Duse_bearssl:BOOL=ON -Drun_e2e_tests:BOOL=ON
cd cmake

make --jobs=$CORES


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

# Print version
cat /etc/*release | grep VERSION*
gcc --version
curl --version

# Set the default cores
CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)
cmake . -Bcmake -Duse_c_ares:BOOL=ON -Drun_e2e_tests:BOOL=ON
cd cmake

make --jobs=$CORES


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

# Print version
cat /etc/*release | grep VERSION*
gcc --version
openssl version
curl --version

build_root=$(cd "$(dirname "$0")/.." && pwd)
cd $build_root

# -- C --
./build_all/linux/build.sh "$@"
[ $? -eq 0 ] || exit $?


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

cat /etc/*release | grep VERSION*
gcc --version
openssl version

script_dir=$(cd "$(dirname "$0")" && pwd)
build_root=$(cd "${script_dir}/.." && pwd)
build_folder=$build_root"/cmake"

# Set the default cores
MAKE_CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)

echo "Initial MAKE_CORES=$MAKE_CORES"

# Make sure there is enough virtual memory on the device to handle more than one job
MINVSPACE="1500000"

# Acquire total memory and total swap space setting them to zero in the event the command fails
MEMAR=( $(sed -n -e 's/^MemTotal:[^0-9]*\([0-9][0-9]*\).*/\1/p' -e 's/^SwapTotal:[^0-9]*\([0-9][0-9]*\).*/\1/p' /proc/meminfo) )
[ -z "${MEMAR[0]##*[!0-9]*}" ] && MEMAR[0]=0
[ -z "${MEMAR[1]##*[!0-9]*}" ] && MEMAR[1]=0

let VSPACE=${MEMAR[0]}+${MEMAR[1]}

if [ "$VSPACE" -lt "$MINVSPACE" ] ; then
echo "WARNING: Not enough space.  Setting MAKE_CORES=1"
MAKE_CORES=1
fi

echo "Create custom HSM library for later"
hsm_folder=$build_root"/build_cust_hsm"
rm -r -f $hsm_folder
mkdir -p $hsm_folder
pushd $hsm_folder

cmake "$build_root/provisioning_client/samples/custom_hsm_example"
make --jobs=$MAKE_CORES

custom_hsm_lib=$hsm_folder"/libcustom_hsm_example.a"

declare -a arr=(
    "-Duse_http=OFF"
    "-Duse_amqp=OFF -Duse_http=OFF -Dno_logging=OFF -Ddont_use_uploadtoblob=ON"
    "-Duse_prov_client=ON -Dbuild_provisioning_service_client=OFF"
    "-Dbuild_as_dynamic=ON"
    "-Dbuild_as_dynamic:BOOL=ON -Ddont_use_uploadtoblob:BOOL=ON"
    "-Dbuild_as_dynamic:BOOL=ON -Ddont_use_uploadtoblob:BOOL=ON -Duse_prov_client:BOOL=ON"
    "-Dbuild_as_dynamic:BOOL=ON -Ddont_use_uploadtoblob:BOOL=ON -Duse_edge_modules:BOOL=ON"
    "-Drun_longhaul_tests=ON"
    "-Duse_prov_client=ON -Dhsm_custom_lib=$custom_hsm_lib"
    "-Drun_e2e_tests=ON -Drun_sfc_tests=ON -Duse_edge_modules=ON"
    "-Drun_e2e_tests=ON -Duse_azure_cloud_rsa_cert=ON"
    "-Drun_e2e_tests=ON -Duse_azure_cloud_ecc_cert=ON"
    "-Duse_prov_client:BOOL=ON -Dhsm_type_symm_key:BOOL=ON"
    "-Duse_prov_client:BOOL=ON -Dhsm_type_x509:BOOL=ON"
    "-Duse_prov_client:BOOL=ON -Dhsm_type_x509:BOOL=OFF -Dhsm_type_riot:BOOL=ON"
    "-Duse_prov_client:BOOL=ON -Dhsm_type_sastoken:BOOL=ON"
    "-Duse_prov_client:BOOL=ON -Dstrict_prototypes:BOOL=ON"
    "-Duse_prov_client:BOOL=ON -DcompileOption_C=-Wunused-variable"
     "-Duse_prov_client:BOOL=ON -DcompileOption_C=-Wmaybe-uninitialized"
)

for item in "${arr[@]}"
do
    rm -r -f $build_folder
    mkdir -p $build_folder
    pushd $build_folder

    echo "executing cmake/make with options <<$item>>"
    cmake $build_root $item

    make --jobs=$MAKE_CORES
done
popd


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

# Print version
cat /etc/*release | grep VERSION*
gcc --version

# Set the default cores
CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)

build_root=$(cd "$(dirname "$0")/.." && pwd)
clone_root=$(cd "$(dirname "$0")/../.." && pwd)
cd $build_root

echo "Build Root $build_root"

sdk_build_folder=$build_root"/cmake"

# Build the SDK
rm -rf $sdk_build_folder
mkdir -p $sdk_build_folder
pushd $sdk_build_folder
cmake $build_root
make install --jobs=$CORES
popd

# Now use the deps
rm -rf $sdk_build_folder
mkdir -p $sdk_build_folder
pushd $sdk_build_folder
cmake $build_root -Duse_installed_dependencies=ON
make --jobs=$CORES
popd

# Now use the deps for provisioning
rm -rf $sdk_build_folder
mkdir -p $sdk_build_folder
pushd $sdk_build_folder
cmake $build_root -Duse_installed_dependencies=ON -Duse_prov_client:BOOL=ON
make --jobs=$CORES
popd


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

# Print version
cat /etc/*release | grep VERSION*
gcc --version
curl --version

build_root=$(cd "$(dirname "$0")/.." && pwd)
cd $build_root

build_folder=$build_root"/cmake"

# Set the default cores
CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)

rm -r -f $build_folder
mkdir -p $build_folder
pushd $build_folder
cmake $build_root -Duse_mbedtls=ON -Duse_openssl=OFF -Ddont_use_uploadtoblob=ON -Drun_e2e_tests=ON
make --jobs=$CORES

popd


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

# Print version
cat /etc/*release | grep VERSION*
gcc --version
curl --version

# Set the default cores
CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)
cmake . -Bcmake -Duse_http=ON -Duse_mqtt=ON -Duse_amqp=ON -Duse_openssl:BOOL=ON -Dhsm_type_x509:BOOL=ON -Duse_prov_client:BOOL=ON -Drun_e2e_tests:BOOL=ON -Drun_e2e_openssl_engine_tests:BOOL=ON -Drun_valgrind:BOOL=ON
cd cmake

make --jobs=$CORES

# Configure OpenSSL with PKCS#11 Engine and SoftHSM

## IoT Hub Tests:

# 1. Create new test token.
#softhsm2-util --delete-token --token test-token > /dev/null
softhsm2-util --init-token --slot 0 --label test-token --pin 1234 --so-pin 4321
# 2. Convert key from PKCS#1 to PKCS#8
echo $IOTHUB_E2E_X509_PRIVATE_KEY_BASE64 | base64 --decode > test-key.pem
openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in test-key.pem -out test-key.p8
# 3. Import private key into the token.
softhsm2-util --pin 1234 --import ./test-key.p8 --token test-token --id b000 --label test-privkey
rm test-key.pem
# 4. (Test) List keys associated with slot (should see the private key listed)
pkcs11-tool --module /usr/lib/softhsm/libsofthsm2.so -l -p 1234 --token test-token --list-objects

## Provisioning Tests:

# 2. Convert key from PKCS#1 to PKCS#8
echo $IOT_DPS_INDIVIDUAL_X509_KEY | base64 --decode > test-key.pem
openssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in test-key.pem -out test-key.p8
# 3. Import private key into the token.
softhsm2-util --pin 1234 --import ./test-key.p8 --token test-token --id d000 --label dps-privkey
rm test-key.pem
# 4. (Test) List keys associated with slot (should see the private key listed)
pkcs11-tool --module /usr/lib/softhsm/libsofthsm2.so -l -p 1234 --token test-token --list-objects


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

# Print version
cat /etc/*release | grep VERSION*
gcc --version
curl --version

build_root=$(cd "$(dirname "$0")/.." && pwd)
cd $build_root

build_folder=$build_root"/cmake"

# Set the default cores
CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)

rm -r -f $build_folder
mkdir -p $build_folder
pushd $build_folder
cmake $build_root -Duse_wolfssl=ON -Duse_openssl=OFF -Ddont_use_uploadtoblob=ON -Drun_e2e_tests=ON
make --jobs=$CORES

popd


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

build_root=$(cd "$(dirname "$0")/.." && pwd)
cd $build_root

# -- C --
./build_all/linux/build.sh --run-longhaul-tests --run_valgrind --config Debug "$@" #-x
[ $? -eq 0 ] || exit $?


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

sw_vers
gcc --version
openssl version
curl --version

script_dir=$(cd "$(dirname "$0")" && pwd)
build_root=$(cd "${script_dir}/.." && pwd)
build_folder=$build_root"/cmake"

CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)

rm -r -f $build_folder
mkdir -p $build_folder
pushd $build_folder
cmake .. -DOPENSSL_ROOT_DIR:PATH=/usr/local/opt/openssl -Duse_openssl:bool=ON -Drun_unittests:bool=ON
cmake --build . -- --jobs=$CORES


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

sw_vers
xcodebuild -version

script_dir=$(cd "$(dirname "$0")" && pwd)
build_root=$(cd "${script_dir}/.." && pwd)
build_folder=$build_root"/cmake"

CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)
TEST_JOB_COUNT=16
echo "Building with $CORES cores and running $TEST_JOB_COUNT tests in parallel"

rm -r -f $build_folder
mkdir -p $build_folder
pushd $build_folder

cmake .. -Duse_prov_client=OFF -Dhsm_type_x509=OFF -Dhsm_type_sastoken=OFF -Dhsm_type_symm_key=OFF -Drun_e2e_tests=ON -G Xcode -DCMAKE_BUILD_TYPE=Debug
cmake --build . -- --jobs=$CORES
popd


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

# assume directory is root of downloaded repo
mkdir cmake
cd cmake
ls -al

# Create a cmake toolchain file on the fly
echo "SET(CMAKE_SYSTEM_NAME Linux)     # this one is important" > toolchain.cmake
echo "SET(CMAKE_SYSTEM_VERSION 1)      # this one not so much" >> toolchain.cmake

echo "SET(CMAKE_C_COMPILER ${TOOLCHAIN_EXES}/${TOOLCHAIN_NAME}-gcc)" >> toolchain.cmake
echo "SET(CMAKE_CXX_COMPILER ${TOOLCHAIN_EXES}/${TOOLCHAIN_NAME}-g++)" >> toolchain.cmake
echo "SET(CMAKE_FIND_ROOT_PATH ${TOOLCHAIN_SYSROOT})" >> toolchain.cmake
echo "SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)" >> toolchain.cmake
echo "SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)" >> toolchain.cmake
echo "SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)" >> toolchain.cmake
ls -al

# Build the SDK. This will use the OpenSSL, cURL and uuid binaries that we built before
cmake -DCMAKE_TOOLCHAIN_FILE=toolchain.cmake -Duse_prov_client:BOOL=OFF -DCMAKE_INSTALL_PREFIX=${TOOLCHAIN_PREFIX} -Drun_e2e_tests:BOOL=ON -Drun_unittests=:BOOL=ON ..
make -j 2
ls -al


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

# Print version
cat /etc/*release | grep VERSION*
gcc --version
openssl version
curl --version

build_root=$(cd "$(dirname "$0")/.." && pwd)
cd $build_root

# -- C --
./build_all/linux/build.sh --run-unittests --run_valgrind --run-e2e-tests --provisioning --use-hsmsymmkey --use-hsmsas --use-hsmx509 --use-edge-modules --config Debug "$@" #-x
[ $? -eq 0 ] || exit $?


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

# Print version
cat /etc/*release | grep VERSION*
openssl version
curl --version

build_root=$(cd "$(dirname "$0")/.." && pwd)
cd $build_root

# -- C --
./build_all/linux/build.sh --run-unittests --run_valgrind --run-e2e-tests --config Debug "$@" #-x
[ $? -eq 0 ] || exit $?


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

# Print version
cat /etc/*release | grep VERSION*
openssl version
curl --version

build_root=$(cd "$(dirname "$0")/.." && pwd)
cd $build_root

# -- C --
./build_all/linux/build.sh --run-unittests --run_valgrind --run-e2e-tests --config Release "$@" #-x
[ $? -eq 0 ] || exit $?


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

# Print version
cat /etc/*release | grep VERSION*
gcc --version
openssl version
curl --version

build_root=$(cd "$(dirname "$0")/.." && pwd)
cd $build_root

# -- C --
./build_all/linux/build.sh --run-unittests --run_valgrind --run-e2e-tests --provisioning --use-hsmsymmkey --use-hsmsas --use-hsmx509 --use-edge-modules --use-ipv6-dualstack --config Debug "$@" #-x
[ $? -eq 0 ] || exit $?


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

# Print version
cat /etc/*release | grep VERSION*
gcc --version
openssl version
curl --version

build_root=$(cd "$(dirname "$0")/.." && pwd)
cd $build_root

# -- C --
./build_all/linux/build.sh --run-unittests --run_valgrind --run-e2e-tests --provisioning --use-hsmsymmkey --use-hsmsas --use-hsmx509 --use-edge-modules --config Release "$@" #-x
[ $? -eq 0 ] || exit $?


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -x # Set trace on
set -o errexit # Exit if command failed
set -o nounset # Exit if variable not set
set -o pipefail # Exit if pipe failed

# Print version
cat /etc/*release | grep VERSION*
gcc --version
openssl version
curl --version

build_root=$(cd "$(dirname "$0")/.." && pwd)
cd $build_root

# -- C --
./build_all/linux/build.sh --run-unittests --run_valgrind --run-e2e-tests --provisioning --use-hsmsymmkey --use-hsmsas --use-hsmriot --use-edge-modules "$@" #-x
[ $? -eq 0 ] || exit $?


#!/bin/bash

# single quotes are used to turn off special meaning of $ in variables.
export IOTHUB_CONNECTION_STRING=''
export IOTHUB_EVENTHUB_CONNECTION_STRING=''
export IOTHUB_EVENTHUB_LISTEN_NAME=''
export IOTHUB_E2E_X509_THUMBPRINT=''
export IOTHUB_E2E_X509_CERT_BASE64=''
export IOTHUB_E2E_X509_PRIVATE_KEY_BASE64=''
export IOTHUB_EVENTHUB_CONSUMER_GROUP='$Default'
IOTHUB_PARTITION_COUNT=16

/home/pi/myagent/run.sh


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

chmod -R 777 $PWD/drop
# we need to cp because of something weird with artifacts
mkdir -p $PWD/drop/copy/cmake/iothub_client/tests
cp -r $PWD/drop/source_artifacts/cmake/iothub_client/tests/ $PWD/drop/copy/cmake/iothub_client/

sudo setcap cap_net_raw,cap_net_admin+ep \
$PWD/drop/source_artifacts/cmake/iothub_client/tests/iothubclient_mqtt_e2e/iothubclient_mqtt_e2e_exe \
cap_net_raw,cap_net_admin+ep $PWD/drop/source_artifacts/cmake/iothub_client/tests/iothubclient_amqp_e2e/iothubclient_amqp_e2e_exe \
cap_net_raw,cap_net_admin+ep $PWD/drop/source_artifacts/cmake/iothub_client/tests/iothubclient_mqtt_ws_e2e/iothubclient_mqtt_ws_e2e_exe \
cap_net_raw,cap_net_admin+ep $PWD/drop/source_artifacts/cmake/iothub_client/tests/iothubclient_amqp_ws_e2e/iothubclient_amqp_ws_e2e_exe \
cap_net_raw,cap_net_admin+ep $PWD/drop/source_artifacts/cmake/iothub_client/tests/iothubclient_uploadtoblob_e2e/iothubclient_uploadtoblob_e2e_exe

$PWD/drop/copy/cmake/iothub_client/tests/iothubclient_mqtt_e2e/iothubclient_mqtt_e2e_exe
$PWD/drop/copy/cmake/iothub_client/tests/iothubclient_amqp_e2e/iothubclient_amqp_e2e_exe
$PWD/drop/copy/cmake/iothub_client/tests/iothubclient_mqtt_ws_e2e/iothubclient_mqtt_ws_e2e_exe
$PWD/drop/copy/cmake/iothub_client/tests/iothubclient_amqp_ws_e2e/iothubclient_amqp_ws_e2e_exe
$PWD/drop/copy/cmake/iothub_client/tests/iothubclient_uploadtoblob_e2e/iothubclient_uploadtoblob_e2e_exe


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

###################################################################################################
################################### PI E2E TEST SETUP GUIDE #######################################
###################################################################################################
# This is a guide to setting up you raspberry pi to run E2E tests. Essentially all this stuff is
# creating the proper toolchain including upgrading cURL to the latest version so that the
# C Client Library can be able to use cURL without any issues like running out of memory.
#
# TO RUN THIS SCRIPT:
# Get a Raspberry Pi and flash the SD card with Stretch.
# This script has been tested to work on a brand new Install of Stretch. Don't use it if you care
# about if your Stretch Image becomes unusable or not. Because it's messing with the curl stuff,
# it might make things unusable... but it also probably won't. Still be cautious.
###################################################################################################
###################################################################################################

# ENABLE SSH BY DEFAULT
if ! grep -Fxq "systemctl start ssh" /etc/rc.local
then
    echo 'Enabling automatic start of ssh on bootup...'
    #insert systemctl start ssh onto the 19th line of /etc/rc.local
    sudo sed -i '19i\systemctl start ssh' /etc/rc.local
    # code if not found
fi
# END ENABLE SSH BY DEFAULT

# GET NECESSARY PACKAGES
sudo apt-get update -y
sudo apt-get install -y vim git build-essential pkg-config git cmake libssl-dev uuid-dev valgrind

###################################################################################################
# DOWNLOAD AND INSTALL LINUX AGENT
# FOR WALKTHROUGH: https://docs.microsoft.com/azure/devops/pipelines/agents/v2-linux?view=azure-devops
# NOTE: You need a Azure DevOps PAT Token. Described in the link above.
###################################################################################################
cd ~
wget https://vstsagentpackage.azureedge.net/agent/2.150.0/vsts-agent-linux-arm-2.150.0.tar.gz
mkdir myagent && cd myagent
if [[ $? -ne 0 ]]; then
    echo "myagent already created, overwriting"
    rm -r myagent && mkdir myagent && cd myagent
fi
tar zxvf ~/vsts-agent-linux-arm-2.150.0.tar.gz
# Config will prompt for name of pool and PAT.
./config.sh
./run.sh
cd ~

###################################################################################################
# INSTALL NEWEST VERSION OF CURL AND POINT TO THE NEW CURL LIBRARY
###################################################################################################
if ! grep -Fxq "LD_LIBRARY_PATH" ~/.bashrc
then
    echo 'export LD_LIBRARY_PATH'
    echo 'export LD_LIBRARY_PATH=/usr/local/lib' >> ~/.bashrc
fi

printf 'Setting variables by calling bashrc'
source ~/.bashrc
[ $? -eq 0 ] || { echo "bashrc source failed"; exit 1; }

# Install curl new version
wget https://curl.haxx.se/download/curl-7.64.1.tar.gz

tar -xzvf curl-7.64.1.tar.gz
cd curl_source/curl-7.64.1/
./configure --without-zlib --with-ssl
make -j
sudo make install

sudo ln -sf /usr/local/bin/curl /usr/bin/curl

echo "Now you can run the cross compiled E2E tests!"

# ###################################################################################################
# # UNCOMMENT THE BELOW LINES AND COMMENT OUT THE CURL INSTALL LINES ABOVE IF YOU WANT TO
# # COMPILE THE SDK ON THE DEVICE AND RUN THE E2E TESTS
# ###################################################################################################
# # check if CURL_ROOT is already a variable set in bashrc...
# if ! grep -Fxq "CURL_ROOT" ~/.bashrc
# then
#     printf 'Exporting variable CURL_ROOT...'
#     echo 'export CURL_ROOT=/home/pi/curl_install' >> ~/.bashrc
#     source ~/.bashrc
#     # code if not found
# fi

# if ! grep -Fxq "LD_LIBRARY_PATH" ~/.bashrc
# then
#     echo 'export LD_LIBRARY_PATH'
#     echo 'export LD_LIBRARY_PATH=$CURL_ROOT/lib' >> ~/.bashrc
# fi

# printf 'Setting variables by calling bashrc'
# source ~/.bashrc
# [ $? -eq 0 ] || { echo "bashrc source failed"; exit 1; }

# # BUILD AND INSTALL NEW CURL TO CURL_ROOT
# # We are commenting this out because it's useful info to have
# # but for the E2E tests it works when CURL is installed directly on the device.
# wget https://curl.haxx.se/download/curl-7.64.1.tar.gz
# mkdir $CURL_ROOT
# mkdir curl_source
# tar -C curl_source -xzvf curl-7.64.1.tar.gz
# cd curl_source/curl-7.64.1/
# ./configure --prefix=$CURL_ROOT --disable-shared --without-zlib --with-ssl --enable-static
# make -j
# sudo make install

# # END GET NECESARY PACKAGES

# # BUILD THE SDK
# cd ~
# git clone --recursive https://github.com/Azure/azure-iot-sdk-c
# cd azure-iot-sdk-c
# if [ -d cmake ]   # for file "if [-f /home/rama/file]"
# then
#     echo "cmake present"
#     rm -rf cmake
# else
#     echo "cmake not present"
# fi
# mkdir cmake && cd cmake
# cmake -Drun_unittests=ON -Drun_e2e_tests=ON -DCMAKE_BUILD_TYPE=Debug -DCURL_LIBRARY=$CURL_ROOT/lib/libcurl.a -DCURL_INCLUDE_DIR=$CURL_ROOT/include  ..
# cd iothub_client/tests/iothubclient_mqtt_e2e
# cmake --build .
# sudo -E su
# setcap cap_net_raw,cap_net_admin+ep iothubclient_mqtt_e2e_exe
# ./iothubclient_mqtt_e2e_exe
# # END RUN THE E2E TEST


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

###################################################################################################
################################### PI E2E TEST SETUP GUIDE #######################################
###################################################################################################
# This is a guide to setting up you raspberry pi to run E2E tests. Essentially all this stuff is
# creating the proper toolchain including upgrading cURL to the latest version so that the
# C Client Library can be able to use cURL without any issues like running out of memory.
#
# TO RUN THIS SCRIPT:
# Get a Raspberry Pi and flash the SD card with Stretch.
# This script has been tested to work on a brand new Install of Stretch. Don't use it if you care
# about if your Stretch Image becomes unusable or not. Because it's messing with the curl stuff,
# it might make things unusable... but it also probably won't. Still be cautious.
###################################################################################################
###################################################################################################

MYDIR="$(dirname "$0")"

# ENABLE SSH BY DEFAULT
if ! grep -Fxq "systemctl start ssh" /etc/rc.local
then
    echo 'Enabling automatic start of ssh on bootup...'
    #insert systemctl start ssh onto the 19th line of /etc/rc.local
    sudo sed -i '19i\systemctl start ssh' /etc/rc.local
    # code if not found
fi
# END ENABLE SSH BY DEFAULT

# GET NECESSARY PACKAGES
sudo apt-get update -y
sudo apt-get install -y vim git build-essential pkg-config git cmake libssl-dev uuid-dev valgrind

###################################################################################################
# DOWNLOAD AND INSTALL LINUX AGENT
# FOR WALKTHROUGH: https://docs.microsoft.com/azure/devops/pipelines/agents/v2-linux?view=azure-devops
# NOTE: You need a Azure DevOps PAT Token. Described in the link above.
###################################################################################################
cd ~
wget https://vstsagentpackage.azureedge.net/agent/2.150.0/vsts-agent-linux-arm-2.150.0.tar.gz
mkdir myagent && cd myagent
if [[ $? -ne 0 ]]; then
    echo "myagent already created, overwriting"
    rm -r myagent && mkdir myagent && cd myagent
fi
tar zxvf ~/vsts-agent-linux-arm-2.150.0.tar.gz
# Config will prompt for name of pool and PAT.
./config.sh
./run.sh
cd ~

# ###################################################################################################
# # CREATE SYSTEMD SERVICE: devops
# # Installing the agent as a systemd service.
# # This needs a manual step of creating the devops-enviroment file in /etc/
# # Look at the template devops-environment to figure out the necessary credentials
# ###################################################################################################

sudo cp devops.service /lib/systemd/system/devops.service
mkdir -p "/home/pi/devops-logs" && touch "/home/pi/devops-logs/devopsagent.log"

# This step redirects the journalctl logs for devops.service to a user log file.
echo "CREATE DEVOPSAGENT.CONF"
touch /etc/rsyslog.d/devopsagent.conf
echo "if $programname == '<your program identifier>' then /home/pi/devops-logs/devopsagent.log" >> /etc/rsyslog.d/devopsagent.conf
echo "& stop" >> /etc/rsyslog.d/devopsagent.conf
sudo chown root:adm /home/pi/devops-logs/devopsagent.log

echo "NOTE: USER INPUT NECESSARY!"
echo "add credentials to devops-environment, then copy to /etc/devops-environment"
echo "Once you have added /etc/devops-environment file, run:"
echo "sudo systemctl daemon-reload"

read -r -p "Have you added your credentials to the devops_service.sh file? [y/N] " response
if [[ "$response" =~ ^([yY][eE][sS]|[yY])+$ ]]
then
    echo "copying devops_service.sh to /home/pi/myagent/"
    cp $MYDIR/devops_service.sh /home/pi/myagent/devops_service.sh
else
    echo "Before you can run the daemon you must update your credentials."
    echo "Once the credentials have been updated then copy devops_service into myagent:"
    echo 'cp $MYDIR/devops_service.sh /home/pi/myagent/devops_service.sh'
fi

###################################################################################################
# INSTALL NEWEST VERSION OF CURL AND POINT TO THE NEW CURL LIBRARY
###################################################################################################
if ! grep -Fxq "LD_LIBRARY_PATH" ~/.bashrc
then
    echo 'export LD_LIBRARY_PATH'
    echo 'export LD_LIBRARY_PATH=/usr/local/lib' >> ~/.bashrc
fi

printf 'Setting variables by calling bashrc'
source ~/.bashrc
[ $? -eq 0 ] || { echo "bashrc source failed"; exit 1; }

# Install curl new version
wget https://curl.haxx.se/download/curl-7.64.1.tar.gz

tar -xzvf curl-7.64.1.tar.gz
cd curl_source/curl-7.64.1/
./configure --without-zlib --with-ssl
make -j
sudo make install

sudo ln -sf /usr/local/bin/curl /usr/bin/curl

echo "Now you can run the cross compiled E2E tests!"

# ###################################################################################################
# # UNCOMMENT THE BELOW LINES AND COMMENT OUT THE CURL INSTALL LINES ABOVE IF YOU WANT TO
# # COMPILE THE SDK ON THE DEVICE AND RUN THE E2E TESTS
# ###################################################################################################
# # check if CURL_ROOT is already a variable set in bashrc...
# if ! grep -Fxq "CURL_ROOT" ~/.bashrc
# then
#     printf 'Exporting variable CURL_ROOT...'
#     echo 'export CURL_ROOT=/home/pi/curl_install' >> ~/.bashrc
#     source ~/.bashrc
#     # code if not found
# fi

# if ! grep -Fxq "LD_LIBRARY_PATH" ~/.bashrc
# then
#     echo 'export LD_LIBRARY_PATH'
#     echo 'export LD_LIBRARY_PATH=$CURL_ROOT/lib' >> ~/.bashrc
# fi

# printf 'Setting variables by calling bashrc'
# source ~/.bashrc
# [ $? -eq 0 ] || { echo "bashrc source failed"; exit 1; }

# # BUILD AND INSTALL NEW CURL TO CURL_ROOT
# # We are commenting this out because it's useful info to have
# # but for the E2E tests it works when CURL is installed directly on the device.
# wget https://curl.haxx.se/download/curl-7.64.1.tar.gz
# mkdir $CURL_ROOT
# mkdir curl_source
# tar -C curl_source -xzvf curl-7.64.1.tar.gz
# cd curl_source/curl-7.64.1/
# ./configure --prefix=$CURL_ROOT --disable-shared --without-zlib --with-ssl --enable-static
# make -j
# sudo make install

# # END GET NECESARY PACKAGES

# # BUILD THE SDK
# cd ~
# git clone https://github.com/Azure/azure-iot-sdk-c
# git submodule update --init
# cd azure-iot-sdk-c
# if [ -d cmake ]   # for file "if [-f /home/rama/file]"
# then
#     echo "cmake present"
#     rm -rf cmake
# else
#     echo "cmake not present"
# fi
# mkdir cmake && cd cmake
# cmake -Drun_unittests=ON -Drun_e2e_tests=ON -DCMAKE_BUILD_TYPE=Debug -DCURL_LIBRARY=$CURL_ROOT/lib/libcurl.a -DCURL_INCLUDE_DIR=$CURL_ROOT/include  ..
# cd iothub_client/tests/iothubclient_mqtt_e2e
# cmake --build .
# sudo -E su
# setcap cap_net_raw,cap_net_admin+ep iothubclient_mqtt_e2e_exe
# ./iothubclient_mqtt_e2e_exe
# # END RUN THE E2E TEST


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -e

# basic setup of input script for python, execution steps are as follows:
# 1. wait until device flashing complete, then send help
# 2. set the IoT Hub Connection String
# 3. call exit, resetting the device to ensure mxchip connects to the set IoT Hub
# 4. call SERIAL_TASK, typically send_telemetry
# 5. call version, to log versions of software on device

echo -e "\r\n\r\nexit\r\n$SERIAL_TASK\r\n\r\nversion" | cat > input.txt


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -e

# basic setup of input script for python, execution steps are as follows:
# 1. wait until device flashing complete, then send help
# 2. set the IoT Hub Connection String
# 3. call exit, resetting the device to ensure mxchip connects to the set IoT Hub
# 4. call SERIAL_TASK, typically send_telemetry
# 5. call version, to log versions of software on device

echo -e "help\r\nset_wifissid $WIFI_SSID\r\nset_wifipwd $WIFI_PWD\r\nset_az_iothub $IOTHUB_CONNECTION_STRING\r\nexit\r\n$SERIAL_TASK\r\n\r\nversion" | cat > input.txt


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -e

cat >setup.txt <<EOL
$RASPI_USER
$RASPI_PWD

export IOTHUB_CONNECTION_STRING="$IOTHUB_CONNECTION_STRING"
export IOTHUB_EVENTHUB_CONNECTION_STRING="$IOTHUB_EVENTHUB_CONNECTION_STRING"
export IOTHUB_PARTITION_COUNT=16
export IOTHUB_E2E_X509_CERT_BASE64="$IOTHUB_E2E_X509_CERT_BASE64"
export IOTHUB_E2E_X509_PRIVATE_KEY_BASE64="$IOTHUB_E2E_X509_PRIVATE_KEY_BASE64"
export IOTHUB_E2E_X509_THUMBPRINT=$IOTHUB_E2E_X509_THUMBPRINT
export IOTHUB_POLICY_KEY=$IOTHUB_POLICY_KEY

export IOT_DPS_CONNECTION_STRING="$IOT_DPS_CONNECTION_STRING"
export IOT_DPS_ID_SCOPE=$IOT_DPS_ID_SCOPE
export IOTHUB_CA_ROOT_CERT=$IOTHUB_CA_ROOT_CERT
export IOTHUB_CA_ROOT_CERT_KEY=$IOTHUB_CA_ROOT_CERT_KEY
export IOT_DPS_GLOBAL_ENDPOINT="$IOT_DPS_GLOBAL_ENDPOINT"
export IOTHUB_DEVICE_CONN_STRING_INVALIDCERT="$IOTHUB_DEVICE_CONN_STRING_INVALIDCERT"
export IOTHUB_CONN_STRING_INVALIDCERT="$IOTHUB_CONN_STRING_INVALIDCERT"
export DPS_GLOBALDEVICEENDPOINT_INVALIDCERT="$DPS_GLOBALDEVICEENDPOINT_INVALIDCERT"
export PROVISIONING_CONNECTION_STRING_INVALIDCERT="$PROVISIONING_CONNECTION_STRING_INVALIDCERT"

EOL


#!/bin/bash
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.

set -e

# basic setup of input script for python
echo -e "rm $RASPI_TEST_FILE\nrm e2e_clone\nsz -a $RASPI_TEST_FILE > $RASPI_PORT < $RASPI_PORT\n\ncp $RASPI_TEST_FILE e2e_clone\n./e2e_clone\n\n$RASPI_SERIAL_TASK\n\n" | cat > input.txt