#  Populate the following environment variables, and execute this file before
#  running the samples.
#
#  For more information about where to find these values, more information here:
#
#  * https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-create
#
#
#  Example:
#
#  export EVENTHUB_NAME="my-event-hub"
#
#  export EVENTHUB_ENDPOINT="sb://your-namespace.servicebus.windows.net/"
#
#  export EVENTHUB_PARTITIONS=4
#
#  export EVENTHUB_ACCESS_POLICY="service"
#
#  export EVENTHUB_ACCESS_KEY="..."
#
#  export STREAMING_CHECKPOINT_ACCOUNT = 'myazurestorage'
#
#  export STREAMING_CHECKPOINT_KEY = "..."
#

export EVENTHUB_NAME=""

export EVENTHUB_ENDPOINT=""

export EVENTHUB_PARTITIONS=""

export EVENTHUB_ACCESS_POLICY=""

export EVENTHUB_ACCESS_KEY=""

# When using checkpoints stored in Azure Blob, this is the Azure Storage Account name
export STREAMING_CHECKPOINT_ACCOUNT=""

# When using checkpoints stored in Azure Blob, this is the Azure Storage Account secret key
export STREAMING_CHECKPOINT_KEY=""


#!/bin/bash
GITBRANCH=`git rev-parse --abbrev-ref HEAD`
#We intend to only run gas on release branches.
if [ "master" != $GITBRANCH ]; then
    exit 0
fi
REALEXITSTATUS=0
go get -u github.com/HewlettPackard/gas
gas -skip=*/arm/*/models.go -skip=*/management/examples/*.go -skip=*vendor* -skip=*/Gododir/* ./... | tee /dev/stderr
REALEXITSTATUS=$(($REALEXITSTATUS+$?))
gas -exclude=G101 ./arm/... ./management/examples/... | tee /dev/stderr
REALEXITSTATUS=$(($REALEXITSTATUS+$?))
gas -exclude=G204 ./Gododir/... | tee /dev/stderr
REALEXITSTATUS=$(($REALEXITSTATUS+$?))
exit $REALEXITSTATUS


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

# The plan9 package provides access to the raw system call
# interface of the underlying operating system.  Porting Go to
# a new architecture/operating system combination requires
# some manual effort, though there are tools that automate
# much of the process.  The auto-generated files have names
# beginning with z.
#
# This script runs or (given -n) prints suggested commands to generate z files
# for the current system.  Running those commands is not automatic.
# This script is documentation more than anything else.
#
# * asm_${GOOS}_${GOARCH}.s
#
# This hand-written assembly file implements system call dispatch.
# There are three entry points:
#
# 	func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);
# 	func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr);
# 	func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);
#
# The first and second are the standard ones; they differ only in
# how many arguments can be passed to the kernel.
# The third is for low-level use by the ForkExec wrapper;
# unlike the first two, it does not call into the scheduler to
# let it know that a system call is running.
#
# * syscall_${GOOS}.go
#
# This hand-written Go file implements system calls that need
# special handling and lists "//sys" comments giving prototypes
# for ones that can be auto-generated.  Mksyscall reads those
# comments to generate the stubs.
#
# * syscall_${GOOS}_${GOARCH}.go
#
# Same as syscall_${GOOS}.go except that it contains code specific
# to ${GOOS} on one particular architecture.
#
# * types_${GOOS}.c
#
# This hand-written C file includes standard C headers and then
# creates typedef or enum names beginning with a dollar sign
# (use of $ in variable names is a gcc extension).  The hardest
# part about preparing this file is figuring out which headers to
# include and which symbols need to be #defined to get the
# actual data structures that pass through to the kernel system calls.
# Some C libraries present alternate versions for binary compatibility
# and translate them on the way in and out of system calls, but
# there is almost always a #define that can get the real ones.
# See types_darwin.c and types_linux.c for examples.
#
# * zerror_${GOOS}_${GOARCH}.go
#
# This machine-generated file defines the system's error numbers,
# error strings, and signal numbers.  The generator is "mkerrors.sh".
# Usually no arguments are needed, but mkerrors.sh will pass its
# arguments on to godefs.
#
# * zsyscall_${GOOS}_${GOARCH}.go
#
# Generated by mksyscall.pl; see syscall_${GOOS}.go above.
#
# * zsysnum_${GOOS}_${GOARCH}.go
#
# Generated by mksysnum_${GOOS}.
#
# * ztypes_${GOOS}_${GOARCH}.go
#
# Generated by godefs; see types_${GOOS}.c above.

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

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

case "$1" in
-syscalls)
	for i in zsyscall*go
	do
		sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i
		rm _$i
	done
	exit 0
	;;
-n)
	run="cat"
	shift
esac

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

case "$GOOSARCH" in
_* | *_ | _)
	echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2
	exit 1
	;;
plan9_386)
	mkerrors=
	mksyscall="./mksyscall.pl -l32 -plan9"
	mksysnum="./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h"
	mktypes="XXX"
	;;
*)
	echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2
	exit 1
	;;
esac

(
	if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi
	case "$GOOS" in
	plan9)
		syscall_goos="syscall_$GOOS.go"
		if [ -n "$mksyscall" ]; then echo "$mksyscall $syscall_goos syscall_$GOOSARCH.go |gofmt >zsyscall_$GOOSARCH.go"; fi
		;;
	esac
	if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi
	if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi
	if [ -n "$mktypes" ]; then echo "$mktypes types_$GOOS.go |gofmt >ztypes_$GOOSARCH.go"; fi
) | $run


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

# Generate Go code listing errors and other #defined constant
# values (ENAMETOOLONG etc.), by asking the preprocessor
# about the definitions.

unset LANG
export LC_ALL=C
export LC_CTYPE=C

CC=${CC:-gcc}

uname=$(uname)

includes='
#include <sys/types.h>
#include <sys/file.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/tcp.h>
#include <errno.h>
#include <sys/signal.h>
#include <signal.h>
#include <sys/resource.h>
'

ccflags="$@"

# Write go tool cgo -godefs input.
(
	echo package plan9
	echo
	echo '/*'
	indirect="includes_$(uname)"
	echo "${!indirect} $includes"
	echo '*/'
	echo 'import "C"'
	echo
	echo 'const ('

	# The gcc command line prints all the #defines
	# it encounters while processing the input
	echo "${!indirect} $includes" | $CC -x c - -E -dM $ccflags |
	awk '
		$1 != "#define" || $2 ~ /\(/ || $3 == "" {next}

		$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers
		$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}
		$2 ~ /^(SCM_SRCRT)$/ {next}
		$2 ~ /^(MAP_FAILED)$/ {next}

		$2 !~ /^ETH_/ &&
		$2 !~ /^EPROC_/ &&
		$2 !~ /^EQUIV_/ &&
		$2 !~ /^EXPR_/ &&
		$2 ~ /^E[A-Z0-9_]+$/ ||
		$2 ~ /^B[0-9_]+$/ ||
		$2 ~ /^V[A-Z0-9]+$/ ||
		$2 ~ /^CS[A-Z0-9]/ ||
		$2 ~ /^I(SIG|CANON|CRNL|EXTEN|MAXBEL|STRIP|UTF8)$/ ||
		$2 ~ /^IGN/ ||
		$2 ~ /^IX(ON|ANY|OFF)$/ ||
		$2 ~ /^IN(LCR|PCK)$/ ||
		$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||
		$2 ~ /^C(LOCAL|READ)$/ ||
		$2 == "BRKINT" ||
		$2 == "HUPCL" ||
		$2 == "PENDIN" ||
		$2 == "TOSTOP" ||
		$2 ~ /^PAR/ ||
		$2 ~ /^SIG[^_]/ ||
		$2 ~ /^O[CNPFP][A-Z]+[^_][A-Z]+$/ ||
		$2 ~ /^IN_/ ||
		$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||
		$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||
		$2 == "ICMPV6_FILTER" ||
		$2 == "SOMAXCONN" ||
		$2 == "NAME_MAX" ||
		$2 == "IFNAMSIZ" ||
		$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||
		$2 ~ /^SYSCTL_VERS/ ||
		$2 ~ /^(MS|MNT)_/ ||
		$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||
		$2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ ||
		$2 ~ /^LINUX_REBOOT_CMD_/ ||
		$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||
		$2 !~ "NLA_TYPE_MASK" &&
		$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||
		$2 ~ /^SIOC/ ||
		$2 ~ /^TIOC/ ||
		$2 !~ "RTF_BITS" &&
		$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||
		$2 ~ /^BIOC/ ||
		$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||
		$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ ||
		$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||
		$2 ~ /^CLONE_[A-Z_]+/ ||
		$2 !~ /^(BPF_TIMEVAL)$/ &&
		$2 ~ /^(BPF|DLT)_/ ||
		$2 !~ "WMESGLEN" &&
		$2 ~ /^W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", $2, $2)}
		$2 ~ /^__WCOREFLAG$/ {next}
		$2 ~ /^__W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", substr($2,3), $2)}

		{next}
	' | sort

	echo ')'
) >_const.go

# Pull out the error names for later.
errors=$(
	echo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |
	sort
)

# Pull out the signal names for later.
signals=$(
	echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |
	egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |
	sort
)

# Again, writing regexps to a file.
echo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print "^\t" $2 "[ \t]*=" }' |
	sort >_error.grep
echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' |
	egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |
	sort >_signal.grep

echo '// mkerrors.sh' "$@"
echo '// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT'
echo
go tool cgo -godefs -- "$@" _const.go >_error.out
cat _error.out | grep -vf _error.grep | grep -vf _signal.grep
echo
echo '// Errors'
echo 'const ('
cat _error.out | grep -f _error.grep | sed 's/=\(.*\)/= Errno(\1)/'
echo ')'

echo
echo '// Signals'
echo 'const ('
cat _error.out | grep -f _signal.grep | sed 's/=\(.*\)/= Signal(\1)/'
echo ')'

# Run C program to print error and syscall strings.
(
	echo -E "
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <string.h>
#include <signal.h>

#define nelem(x) (sizeof(x)/sizeof((x)[0]))

enum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below

int errors[] = {
"
	for i in $errors
	do
		echo -E '	'$i,
	done

	echo -E "
};

int signals[] = {
"
	for i in $signals
	do
		echo -E '	'$i,
	done

	# Use -E because on some systems bash builtin interprets \n itself.
	echo -E '
};

static int
intcmp(const void *a, const void *b)
{
	return *(int*)a - *(int*)b;
}

int
main(void)
{
	int i, j, e;
	char buf[1024], *p;

	printf("\n\n// Error table\n");
	printf("var errors = [...]string {\n");
	qsort(errors, nelem(errors), sizeof errors[0], intcmp);
	for(i=0; i<nelem(errors); i++) {
		e = errors[i];
		if(i > 0 && errors[i-1] == e)
			continue;
		strcpy(buf, strerror(e));
		// lowercase first letter: Bad -> bad, but STREAM -> STREAM.
		if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)
			buf[0] += a - A;
		printf("\t%d: \"%s\",\n", e, buf);
	}
	printf("}\n\n");

	printf("\n\n// Signal table\n");
	printf("var signals = [...]string {\n");
	qsort(signals, nelem(signals), sizeof signals[0], intcmp);
	for(i=0; i<nelem(signals); i++) {
		e = signals[i];
		if(i > 0 && signals[i-1] == e)
			continue;
		strcpy(buf, strsignal(e));
		// lowercase first letter: Bad -> bad, but STREAM -> STREAM.
		if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)
			buf[0] += a - A;
		// cut trailing : number.
		p = strrchr(buf, ":"[0]);
		if(p)
			*p = '\0';
		printf("\t%d: \"%s\",\n", e, buf);
	}
	printf("}\n\n");

	return 0;
}

'
) >_errors.c

$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out


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

COMMAND="mksysnum_plan9.sh $@"

cat <<EOF
// $COMMAND
// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT

package plan9

const(
EOF

SP='[ 	]' # space or tab
sed "s/^#define${SP}\\([A-Z0-9_][A-Z0-9_]*\\)${SP}${SP}*\\([0-9][0-9]*\\)/SYS_\\1=\\2/g" \
	< $1 | grep -v SYS__

cat <<EOF
)
EOF


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

# The unix package provides access to the raw system call
# interface of the underlying operating system.  Porting Go to
# a new architecture/operating system combination requires
# some manual effort, though there are tools that automate
# much of the process.  The auto-generated files have names
# beginning with z.
#
# This script runs or (given -n) prints suggested commands to generate z files
# for the current system.  Running those commands is not automatic.
# This script is documentation more than anything else.
#
# * asm_${GOOS}_${GOARCH}.s
#
# This hand-written assembly file implements system call dispatch.
# There are three entry points:
#
# 	func Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);
# 	func Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr);
# 	func RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);
#
# The first and second are the standard ones; they differ only in
# how many arguments can be passed to the kernel.
# The third is for low-level use by the ForkExec wrapper;
# unlike the first two, it does not call into the scheduler to
# let it know that a system call is running.
#
# * syscall_${GOOS}.go
#
# This hand-written Go file implements system calls that need
# special handling and lists "//sys" comments giving prototypes
# for ones that can be auto-generated.  Mksyscall reads those
# comments to generate the stubs.
#
# * syscall_${GOOS}_${GOARCH}.go
#
# Same as syscall_${GOOS}.go except that it contains code specific
# to ${GOOS} on one particular architecture.
#
# * types_${GOOS}.c
#
# This hand-written C file includes standard C headers and then
# creates typedef or enum names beginning with a dollar sign
# (use of $ in variable names is a gcc extension).  The hardest
# part about preparing this file is figuring out which headers to
# include and which symbols need to be #defined to get the
# actual data structures that pass through to the kernel system calls.
# Some C libraries present alternate versions for binary compatibility
# and translate them on the way in and out of system calls, but
# there is almost always a #define that can get the real ones.
# See types_darwin.c and types_linux.c for examples.
#
# * zerror_${GOOS}_${GOARCH}.go
#
# This machine-generated file defines the system's error numbers,
# error strings, and signal numbers.  The generator is "mkerrors.sh".
# Usually no arguments are needed, but mkerrors.sh will pass its
# arguments on to godefs.
#
# * zsyscall_${GOOS}_${GOARCH}.go
#
# Generated by mksyscall.pl; see syscall_${GOOS}.go above.
#
# * zsysnum_${GOOS}_${GOARCH}.go
#
# Generated by mksysnum_${GOOS}.
#
# * ztypes_${GOOS}_${GOARCH}.go
#
# Generated by godefs; see types_${GOOS}.c above.

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

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

case "$1" in
-syscalls)
	for i in zsyscall*go
	do
		sed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i
		rm _$i
	done
	exit 0
	;;
-n)
	run="cat"
	shift
esac

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

GOOSARCH_in=syscall_$GOOSARCH.go
case "$GOOSARCH" in
_* | *_ | _)
	echo 'undefined $GOOS_$GOARCH:' "$GOOSARCH" 1>&2
	exit 1
	;;
darwin_386)
	mkerrors="$mkerrors -m32"
	mksyscall="./mksyscall.pl -l32"
	mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
darwin_amd64)
	mkerrors="$mkerrors -m64"
	mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
darwin_arm)
	mkerrors="$mkerrors"
	mksysnum="./mksysnum_darwin.pl /usr/include/sys/syscall.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
darwin_arm64)
	mkerrors="$mkerrors -m64"
	mksysnum="./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
dragonfly_386)
	mkerrors="$mkerrors -m32"
	mksyscall="./mksyscall.pl -l32 -dragonfly"
	mksysnum="curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
dragonfly_amd64)
	mkerrors="$mkerrors -m64"
	mksyscall="./mksyscall.pl -dragonfly"
	mksysnum="curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
freebsd_386)
	mkerrors="$mkerrors -m32"
	mksyscall="./mksyscall.pl -l32"
	mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
freebsd_amd64)
	mkerrors="$mkerrors -m64"
	mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
freebsd_arm)
	mkerrors="$mkerrors"
	mksyscall="./mksyscall.pl -l32 -arm"
	mksysnum="curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl"
	# Let the type of C char be singed for making the bare syscall
	# API consistent across over platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
linux_386)
	mkerrors="$mkerrors -m32"
	mksyscall="./mksyscall.pl -l32"
	mksysnum="./mksysnum_linux.pl /usr/include/asm/unistd_32.h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
linux_amd64)
	unistd_h=$(ls -1 /usr/include/asm/unistd_64.h /usr/include/x86_64-linux-gnu/asm/unistd_64.h 2>/dev/null | head -1)
	if [ "$unistd_h" = "" ]; then
		echo >&2 cannot find unistd_64.h
		exit 1
	fi
	mkerrors="$mkerrors -m64"
	mksysnum="./mksysnum_linux.pl $unistd_h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
linux_arm)
	mkerrors="$mkerrors"
	mksyscall="./mksyscall.pl -l32 -arm"
	mksysnum="curl -s 'http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/arch/arm/include/uapi/asm/unistd.h' | ./mksysnum_linux.pl -"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
linux_arm64)
	unistd_h=$(ls -1 /usr/include/asm/unistd.h /usr/include/asm-generic/unistd.h 2>/dev/null | head -1)
	if [ "$unistd_h" = "" ]; then
		echo >&2 cannot find unistd_64.h
		exit 1
	fi
	mksysnum="./mksysnum_linux.pl $unistd_h"
	# Let the type of C char be singed for making the bare syscall
	# API consistent across over platforms.
	mktypes="GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char"
	;;
linux_ppc64)
	GOOSARCH_in=syscall_linux_ppc64x.go
	unistd_h=/usr/include/asm/unistd.h
	mkerrors="$mkerrors -m64"
	mksysnum="./mksysnum_linux.pl $unistd_h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
linux_ppc64le)
	GOOSARCH_in=syscall_linux_ppc64x.go
	unistd_h=/usr/include/powerpc64le-linux-gnu/asm/unistd.h
	mkerrors="$mkerrors -m64"
	mksysnum="./mksysnum_linux.pl $unistd_h"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
netbsd_386)
	mkerrors="$mkerrors -m32"
	mksyscall="./mksyscall.pl -l32 -netbsd"
	mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
netbsd_amd64)
	mkerrors="$mkerrors -m64"
	mksyscall="./mksyscall.pl -netbsd"
	mksysnum="curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
openbsd_386)
	mkerrors="$mkerrors -m32"
	mksyscall="./mksyscall.pl -l32 -openbsd"
	mksysctl="./mksysctl_openbsd.pl"
	zsysctl="zsysctl_openbsd.go"
	mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
openbsd_amd64)
	mkerrors="$mkerrors -m64"
	mksyscall="./mksyscall.pl -openbsd"
	mksysctl="./mksysctl_openbsd.pl"
	zsysctl="zsysctl_openbsd.go"
	mksysnum="curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl"
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
solaris_amd64)
	mksyscall="./mksyscall_solaris.pl"
	mkerrors="$mkerrors -m64"
	mksysnum=
	mktypes="GOARCH=$GOARCH go tool cgo -godefs"
	;;
*)
	echo 'unrecognized $GOOS_$GOARCH: ' "$GOOSARCH" 1>&2
	exit 1
	;;
esac

(
	if [ -n "$mkerrors" ]; then echo "$mkerrors |gofmt >$zerrors"; fi
	case "$GOOS" in
	*)
		syscall_goos="syscall_$GOOS.go"
		case "$GOOS" in
		darwin | dragonfly | freebsd | netbsd | openbsd)
			syscall_goos="syscall_bsd.go $syscall_goos"
			;;
		esac
		if [ -n "$mksyscall" ]; then echo "$mksyscall $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go"; fi
		;;
	esac
	if [ -n "$mksysctl" ]; then echo "$mksysctl |gofmt >$zsysctl"; fi
	if [ -n "$mksysnum" ]; then echo "$mksysnum |gofmt >zsysnum_$GOOSARCH.go"; fi
	if [ -n "$mktypes" ]; then
		echo "echo // +build $GOARCH,$GOOS > ztypes_$GOOSARCH.go";
		echo "$mktypes types_$GOOS.go | gofmt >>ztypes_$GOOSARCH.go";
	fi
) | $run


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

# Generate Go code listing errors and other #defined constant
# values (ENAMETOOLONG etc.), by asking the preprocessor
# about the definitions.

unset LANG
export LC_ALL=C
export LC_CTYPE=C

if test -z "$GOARCH" -o -z "$GOOS"; then
	echo 1>&2 "GOARCH or GOOS not defined in environment"
	exit 1
fi

CC=${CC:-cc}

if [[ "$GOOS" -eq "solaris" ]]; then
	# Assumes GNU versions of utilities in PATH.
	export PATH=/usr/gnu/bin:$PATH
fi

uname=$(uname)

includes_Darwin='
#define _DARWIN_C_SOURCE
#define KERNEL
#define _DARWIN_USE_64_BIT_INODE
#include <sys/types.h>
#include <sys/event.h>
#include <sys/ptrace.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <termios.h>
'

includes_DragonFly='
#include <sys/types.h>
#include <sys/event.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <termios.h>
#include <netinet/ip.h>
#include <net/ip_mroute/ip_mroute.h>
'

includes_FreeBSD='
#include <sys/param.h>
#include <sys/types.h>
#include <sys/event.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <termios.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
#include <sys/extattr.h>

#if __FreeBSD__ >= 10
#define IFT_CARP	0xf8	// IFT_CARP is deprecated in FreeBSD 10
#undef SIOCAIFADDR
#define SIOCAIFADDR	_IOW(105, 26, struct oifaliasreq)	// ifaliasreq contains if_data
#undef SIOCSIFPHYADDR
#define SIOCSIFPHYADDR	_IOW(105, 70, struct oifaliasreq)	// ifaliasreq contains if_data
#endif
'

includes_Linux='
#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#ifndef __LP64__
#define _FILE_OFFSET_BITS 64
#endif
#define _GNU_SOURCE

#include <bits/sockaddr.h>
#include <sys/epoll.h>
#include <sys/inotify.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <linux/if.h>
#include <linux/if_arp.h>
#include <linux/if_ether.h>
#include <linux/if_tun.h>
#include <linux/if_packet.h>
#include <linux/if_addr.h>
#include <linux/filter.h>
#include <linux/netlink.h>
#include <linux/reboot.h>
#include <linux/rtnetlink.h>
#include <linux/ptrace.h>
#include <linux/sched.h>
#include <linux/wait.h>
#include <linux/icmpv6.h>
#include <net/route.h>
#include <asm/termbits.h>

#ifndef MSG_FASTOPEN
#define MSG_FASTOPEN    0x20000000
#endif

#ifndef PTRACE_GETREGS
#define PTRACE_GETREGS	0xc
#endif

#ifndef PTRACE_SETREGS
#define PTRACE_SETREGS	0xd
#endif
'

includes_NetBSD='
#include <sys/types.h>
#include <sys/param.h>
#include <sys/event.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/termios.h>
#include <sys/ttycom.h>
#include <sys/wait.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
#include <netinet/if_ether.h>

// Needed since <sys/param.h> refers to it...
#define schedppq 1
'

includes_OpenBSD='
#include <sys/types.h>
#include <sys/param.h>
#include <sys/event.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/sysctl.h>
#include <sys/termios.h>
#include <sys/ttycom.h>
#include <sys/wait.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_types.h>
#include <net/if_var.h>
#include <net/route.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
#include <netinet/if_ether.h>
#include <net/if_bridge.h>

// We keep some constants not supported in OpenBSD 5.5 and beyond for
// the promise of compatibility.
#define EMUL_ENABLED		0x1
#define EMUL_NATIVE		0x2
#define IPV6_FAITH		0x1d
#define IPV6_OPTIONS		0x1
#define IPV6_RTHDR_STRICT	0x1
#define IPV6_SOCKOPT_RESERVED1	0x3
#define SIOCGIFGENERIC		0xc020693a
#define SIOCSIFGENERIC		0x80206939
#define WALTSIG			0x4
'

includes_SunOS='
#include <limits.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <sys/ioctl.h>
#include <net/bpf.h>
#include <net/if.h>
#include <net/if_arp.h>
#include <net/if_types.h>
#include <net/route.h>
#include <netinet/in.h>
#include <termios.h>
#include <netinet/ip.h>
#include <netinet/ip_mroute.h>
'

includes='
#include <sys/types.h>
#include <sys/file.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <netinet/tcp.h>
#include <errno.h>
#include <sys/signal.h>
#include <signal.h>
#include <sys/resource.h>
#include <time.h>
'
ccflags="$@"

# Write go tool cgo -godefs input.
(
	echo package unix
	echo
	echo '/*'
	indirect="includes_$(uname)"
	echo "${!indirect} $includes"
	echo '*/'
	echo 'import "C"'
	echo 'import "syscall"'
	echo
	echo 'const ('

	# The gcc command line prints all the #defines
	# it encounters while processing the input
	echo "${!indirect} $includes" | $CC -x c - -E -dM $ccflags |
	awk '
		$1 != "#define" || $2 ~ /\(/ || $3 == "" {next}

		$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers
		$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}
		$2 ~ /^(SCM_SRCRT)$/ {next}
		$2 ~ /^(MAP_FAILED)$/ {next}
		$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.

		$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||
		$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}

		$2 !~ /^ETH_/ &&
		$2 !~ /^EPROC_/ &&
		$2 !~ /^EQUIV_/ &&
		$2 !~ /^EXPR_/ &&
		$2 ~ /^E[A-Z0-9_]+$/ ||
		$2 ~ /^B[0-9_]+$/ ||
		$2 == "BOTHER" ||
		$2 ~ /^CI?BAUD(EX)?$/ ||
		$2 == "IBSHIFT" ||
		$2 ~ /^V[A-Z0-9]+$/ ||
		$2 ~ /^CS[A-Z0-9]/ ||
		$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||
		$2 ~ /^IGN/ ||
		$2 ~ /^IX(ON|ANY|OFF)$/ ||
		$2 ~ /^IN(LCR|PCK)$/ ||
		$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||
		$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||
		$2 == "BRKINT" ||
		$2 == "HUPCL" ||
		$2 == "PENDIN" ||
		$2 == "TOSTOP" ||
		$2 == "XCASE" ||
		$2 == "ALTWERASE" ||
		$2 == "NOKERNINFO" ||
		$2 ~ /^PAR/ ||
		$2 ~ /^SIG[^_]/ ||
		$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||
		$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||
		$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||
		$2 ~ /^O?XTABS$/ ||
		$2 ~ /^TC[IO](ON|OFF)$/ ||
		$2 ~ /^IN_/ ||
		$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||
		$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||
		$2 == "ICMPV6_FILTER" ||
		$2 == "SOMAXCONN" ||
		$2 == "NAME_MAX" ||
		$2 == "IFNAMSIZ" ||
		$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||
		$2 ~ /^SYSCTL_VERS/ ||
		$2 ~ /^(MS|MNT)_/ ||
		$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||
		$2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ ||
		$2 ~ /^LINUX_REBOOT_CMD_/ ||
		$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||
		$2 !~ "NLA_TYPE_MASK" &&
		$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||
		$2 ~ /^SIOC/ ||
		$2 ~ /^TIOC/ ||
		$2 ~ /^TCGET/ ||
		$2 ~ /^TCSET/ ||
		$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||
		$2 !~ "RTF_BITS" &&
		$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||
		$2 ~ /^BIOC/ ||
		$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||
		$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ ||
		$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||
		$2 ~ /^CLONE_[A-Z_]+/ ||
		$2 !~ /^(BPF_TIMEVAL)$/ &&
		$2 ~ /^(BPF|DLT)_/ ||
		$2 ~ /^CLOCK_/ ||
		$2 !~ "WMESGLEN" &&
		$2 ~ /^W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", $2, $2)}
		$2 ~ /^__WCOREFLAG$/ {next}
		$2 ~ /^__W[A-Z0-9]+$/ {printf("\t%s = C.%s\n", substr($2,3), $2)}

		{next}
	' | sort

	echo ')'
) >_const.go

# Pull out the error names for later.
errors=$(
	echo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |
	sort
)

# Pull out the signal names for later.
signals=$(
	echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |
	egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |
	sort
)

# Again, writing regexps to a file.
echo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^E[A-Z0-9_]+$/ { print "^\t" $2 "[ \t]*=" }' |
	sort >_error.grep
echo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |
	awk '$1=="#define" && $2 ~ /^SIG[A-Z0-9]+$/ { print "^\t" $2 "[ \t]*=" }' |
	egrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |
	sort >_signal.grep

echo '// mkerrors.sh' "$@"
echo '// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT'
echo
echo "// +build ${GOARCH},${GOOS}"
echo
go tool cgo -godefs -- "$@" _const.go >_error.out
cat _error.out | grep -vf _error.grep | grep -vf _signal.grep
echo
echo '// Errors'
echo 'const ('
cat _error.out | grep -f _error.grep | sed 's/=\(.*\)/= syscall.Errno(\1)/'
echo ')'

echo
echo '// Signals'
echo 'const ('
cat _error.out | grep -f _signal.grep | sed 's/=\(.*\)/= syscall.Signal(\1)/'
echo ')'

# Run C program to print error and syscall strings.
(
	echo -E "
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
#include <string.h>
#include <signal.h>

#define nelem(x) (sizeof(x)/sizeof((x)[0]))

enum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below

int errors[] = {
"
	for i in $errors
	do
		echo -E '	'$i,
	done

	echo -E "
};

int signals[] = {
"
	for i in $signals
	do
		echo -E '	'$i,
	done

	# Use -E because on some systems bash builtin interprets \n itself.
	echo -E '
};

static int
intcmp(const void *a, const void *b)
{
	return *(int*)a - *(int*)b;
}

int
main(void)
{
	int i, j, e;
	char buf[1024], *p;

	printf("\n\n// Error table\n");
	printf("var errors = [...]string {\n");
	qsort(errors, nelem(errors), sizeof errors[0], intcmp);
	for(i=0; i<nelem(errors); i++) {
		e = errors[i];
		if(i > 0 && errors[i-1] == e)
			continue;
		strcpy(buf, strerror(e));
		// lowercase first letter: Bad -> bad, but STREAM -> STREAM.
		if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)
			buf[0] += a - A;
		printf("\t%d: \"%s\",\n", e, buf);
	}
	printf("}\n\n");

	printf("\n\n// Signal table\n");
	printf("var signals = [...]string {\n");
	qsort(signals, nelem(signals), sizeof signals[0], intcmp);
	for(i=0; i<nelem(signals); i++) {
		e = signals[i];
		if(i > 0 && signals[i-1] == e)
			continue;
		strcpy(buf, strsignal(e));
		// lowercase first letter: Bad -> bad, but STREAM -> STREAM.
		if(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)
			buf[0] += a - A;
		// cut trailing : number.
		p = strrchr(buf, ":"[0]);
		if(p)
			*p = '\0';
		printf("\t%d: \"%s\",\n", e, buf);
	}
	printf("}\n\n");

	return 0;
}

'
) >_errors.c

$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out


#!/usr/bin/env bash
dotnet build Azure.Functions.Cli.sln
dotnet publish src/Azure.Functions.Cli/Azure.Functions.Cli.csproj --runtime linux-x64 --output /tmp/cli
# FUNC_PATH=/tmp/cli/func dotnet test test/Azure.Functions.Cli.Tests/Azure.Functions.Cli.Tests.csproj


#!/usr/bin/env bash
# Copyright (c) .NET Foundation and contributors. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.
#
# Original file from https://github.com/dotnet/cli/blob/80d542b8f4eff847a0f72dc8f2c2a29851272778/scripts/obtain/dotnet-install.sh

# Stop script on NZEC
set -e
# Stop script if unbound variable found (use ${var:-} if intentional)
set -u
# By default cmd1 | cmd2 returns exit code of cmd2 regardless of cmd1 success
# This is causing it to fail
set -o pipefail

# Use in the the functions: eval $invocation
invocation='say_verbose "Calling: ${yellow:-}${FUNCNAME[0]} ${green:-}$*${normal:-}"'

# standard output may be used as a return value in the functions
# we need a way to write text on the screen in the functions so that
# it won't interfere with the return value.
# Exposing stream 3 as a pipe to standard output of the script itself
exec 3>&1

# Setup some colors to use. These need to work in fairly limited shells, like the Ubuntu Docker container where there are only 8 colors.
# See if stdout is a terminal
if [ -t 1 ] && command -v tput > /dev/null; then
    # see if it supports colors
    ncolors=$(tput colors)
    if [ -n "$ncolors" ] && [ $ncolors -ge 8 ]; then
        bold="$(tput bold       || echo)"
        normal="$(tput sgr0     || echo)"
        black="$(tput setaf 0   || echo)"
        red="$(tput setaf 1     || echo)"
        green="$(tput setaf 2   || echo)"
        yellow="$(tput setaf 3  || echo)"
        blue="$(tput setaf 4    || echo)"
        magenta="$(tput setaf 5 || echo)"
        cyan="$(tput setaf 6    || echo)"
        white="$(tput setaf 7   || echo)"
    fi
fi

say_warning() {
    printf "%b\n" "${yellow:-}dotnet_install: Warning: $1${normal:-}"
}

say_err() {
    printf "%b\n" "${red:-}dotnet_install: Error: $1${normal:-}" >&2
}

say() {
    # using stream 3 (defined in the beginning) to not interfere with stdout of functions
    # which may be used as return value
    printf "%b\n" "${cyan:-}dotnet-install:${normal:-} $1" >&3
}

say_verbose() {
    if [ "$verbose" = true ]; then
        say "$1"
    fi
}

# This platform list is finite - if the SDK/Runtime has supported Linux distribution-specific assets,
#   then and only then should the Linux distribution appear in this list.
# Adding a Linux distribution to this list does not imply distribution-specific support.
get_legacy_os_name_from_platform() {
    eval $invocation

    platform="$1"
    case "$platform" in
        "centos.7")
            echo "centos"
            return 0
            ;;
        "debian.8")
            echo "debian"
            return 0
            ;;
        "fedora.23")
            echo "fedora.23"
            return 0
            ;;
        "fedora.27")
            echo "fedora.27"
            return 0
            ;;
        "fedora.24")
            echo "fedora.24"
            return 0
            ;;
        "opensuse.13.2")
            echo "opensuse.13.2"
            return 0
            ;;
        "opensuse.42.1")
            echo "opensuse.42.1"
            return 0
            ;;
        "opensuse.42.3")
            echo "opensuse.42.3"
            return 0
            ;;
        "rhel.7"*)
            echo "rhel"
            return 0
            ;;
        "ubuntu.14.04")
            echo "ubuntu"
            return 0
            ;;
        "ubuntu.16.04")
            echo "ubuntu.16.04"
            return 0
            ;;
        "ubuntu.16.10")
            echo "ubuntu.16.10"
            return 0
            ;;
        "ubuntu.18.04")
            echo "ubuntu.18.04"
            return 0
            ;;
        "alpine.3.4.3")
            echo "alpine"
            return 0
            ;;
    esac
    return 1
}

get_linux_platform_name() {
    eval $invocation

    if [ -n "$runtime_id" ]; then
        echo "${runtime_id%-*}"
        return 0
    else
        if [ -e /etc/os-release ]; then
            . /etc/os-release
            echo "$ID.$VERSION_ID"
            return 0
        elif [ -e /etc/redhat-release ]; then
            local redhatRelease=$(</etc/redhat-release)
            if [[ $redhatRelease == "CentOS release 6."* || $redhatRelease == "Red Hat Enterprise Linux Server release 6."* ]]; then
                echo "rhel.6"
                return 0
            fi
        fi
    fi

    say_verbose "Linux specific platform name and version could not be detected: UName = $uname"
    return 1
}

get_current_os_name() {
    eval $invocation

    local uname=$(uname)
    if [ "$uname" = "Darwin" ]; then
        echo "osx"
        return 0
    elif [ "$uname" = "Linux" ]; then
        local linux_platform_name
        linux_platform_name="$(get_linux_platform_name)" || { echo "linux" && return 0 ; }

        if [[ $linux_platform_name == "rhel.6" ]]; then
            echo $linux_platform_name
            return 0
        elif [[ $linux_platform_name == alpine* ]]; then
            echo "linux-musl"
            return 0
        else
            echo "linux"
            return 0
        fi
    fi

    say_err "OS name could not be detected: UName = $uname"
    return 1
}

get_legacy_os_name() {
    eval $invocation

    local uname=$(uname)
    if [ "$uname" = "Darwin" ]; then
        echo "osx"
        return 0
    elif [ -n "$runtime_id" ]; then
        echo $(get_legacy_os_name_from_platform "${runtime_id%-*}" || echo "${runtime_id%-*}")
        return 0
    else
        if [ -e /etc/os-release ]; then
            . /etc/os-release
            os=$(get_legacy_os_name_from_platform "$ID.$VERSION_ID" || echo "")
            if [ -n "$os" ]; then
                echo "$os"
                return 0
            fi
        fi
    fi

    say_verbose "Distribution specific OS name and version could not be detected: UName = $uname"
    return 1
}

machine_has() {
    eval $invocation

    hash "$1" > /dev/null 2>&1
    return $?
}

check_min_reqs() {
    local hasMinimum=false
    if machine_has "curl"; then
        hasMinimum=true
    elif machine_has "wget"; then
        hasMinimum=true
    fi

    if [ "$hasMinimum" = "false" ]; then
        say_err "curl (recommended) or wget are required to download dotnet. Install missing prerequisite to proceed."
        return 1
    fi
    return 0
}

check_pre_reqs() {
    eval $invocation

    if [ "${DOTNET_INSTALL_SKIP_PREREQS:-}" = "1" ]; then
        return 0
    fi

    if [ "$(uname)" = "Linux" ]; then
        if [ ! -x "$(command -v ldconfig)" ]; then
            echo "ldconfig is not in PATH, trying /sbin/ldconfig."
            LDCONFIG_COMMAND="/sbin/ldconfig"
        else
            LDCONFIG_COMMAND="ldconfig"
        fi

        local librarypath=${LD_LIBRARY_PATH:-}
        LDCONFIG_COMMAND="$LDCONFIG_COMMAND -NXv ${librarypath//:/ }"

        [ -z "$($LDCONFIG_COMMAND 2>/dev/null | grep libunwind)" ] && say_warning "Unable to locate libunwind. Probable prerequisite missing; please install libunwind."
        [ -z "$($LDCONFIG_COMMAND 2>/dev/null | grep libssl)" ] && say_warning "Unable to locate libssl. Probable prerequisite missing; please install libssl."
        [ -z "$($LDCONFIG_COMMAND 2>/dev/null | grep libicu)" ] && say_warning "Unable to locate libicu. Probable prerequisite missing; please install libicu."
        [ -z "$($LDCONFIG_COMMAND 2>/dev/null | grep -F libcurl.so)" ] && say_warning "Unable to locate libcurl. Probable prerequisite missing; please install libcurl."
    fi

    return 0
}

# args:
# input - $1
to_lowercase() {
    #eval $invocation

    echo "$1" | tr '[:upper:]' '[:lower:]'
    return 0
}

# args:
# input - $1
remove_trailing_slash() {
    #eval $invocation

    local input="${1:-}"
    echo "${input%/}"
    return 0
}

# args:
# input - $1
remove_beginning_slash() {
    #eval $invocation

    local input="${1:-}"
    echo "${input#/}"
    return 0
}

# args:
# root_path - $1
# child_path - $2 - this parameter can be empty
combine_paths() {
    eval $invocation

    # TODO: Consider making it work with any number of paths. For now:
    if [ ! -z "${3:-}" ]; then
        say_err "combine_paths: Function takes two parameters."
        return 1
    fi

    local root_path="$(remove_trailing_slash "$1")"
    local child_path="$(remove_beginning_slash "${2:-}")"
    say_verbose "combine_paths: root_path=$root_path"
    say_verbose "combine_paths: child_path=$child_path"
    echo "$root_path/$child_path"
    return 0
}

get_machine_architecture() {
    eval $invocation

    if command -v uname > /dev/null; then
        CPUName=$(uname -m)
        case $CPUName in
        armv7l)
            echo "arm"
            return 0
            ;;
        aarch64)
            echo "arm64"
            return 0
            ;;
        esac
    fi

    # Always default to 'x64'
    echo "x64"
    return 0
}

# args:
# architecture - $1
get_normalized_architecture_from_architecture() {
    eval $invocation

    local architecture="$(to_lowercase "$1")"
    case "$architecture" in
        \<auto\>)
            echo "$(get_normalized_architecture_from_architecture "$(get_machine_architecture)")"
            return 0
            ;;
        amd64|x64)
            echo "x64"
            return 0
            ;;
        arm)
            echo "arm"
            return 0
            ;;
        arm64)
            echo "arm64"
            return 0
            ;;
    esac

    say_err "Architecture \`$architecture\` not supported. If you think this is a bug, please report it at https://github.com/dotnet/cli/issues"
    return 1
}

# version_info is a conceptual two line string representing commit hash and 4-part version
# format:
# Line 1: # commit_hash
# Line 2: # 4-part version

# args:
# version_text - stdin
get_version_from_version_info() {
    eval $invocation

    cat | tail -n 1 | sed 's/\r$//'
    return 0
}

# args:
# version_text - stdin
get_commit_hash_from_version_info() {
    eval $invocation

    cat | head -n 1 | sed 's/\r$//'
    return 0
}

# args:
# install_root - $1
# relative_path_to_package - $2
# specific_version - $3
is_dotnet_package_installed() {
    eval $invocation

    local install_root="$1"
    local relative_path_to_package="$2"
    local specific_version="${3//[$'\t\r\n']}"

    local dotnet_package_path="$(combine_paths "$(combine_paths "$install_root" "$relative_path_to_package")" "$specific_version")"
    say_verbose "is_dotnet_package_installed: dotnet_package_path=$dotnet_package_path"

    if [ -d "$dotnet_package_path" ]; then
        return 0
    else
        return 1
    fi
}

# args:
# azure_feed - $1
# channel - $2
# normalized_architecture - $3
# coherent - $4
get_latest_version_info() {
    eval $invocation

    local azure_feed="$1"
    local channel="$2"
    local normalized_architecture="$3"
    local coherent="$4"

    local version_file_url=null
    if [[ "$runtime" == "dotnet" ]]; then
        version_file_url="$uncached_feed/Runtime/$channel/latest.version"
    elif [[ "$runtime" == "aspnetcore" ]]; then
        version_file_url="$uncached_feed/aspnetcore/Runtime/$channel/latest.version"
    elif [ -z "$runtime" ]; then
        if [ "$coherent" = true ]; then
            version_file_url="$uncached_feed/Sdk/$channel/latest.coherent.version"
        else
            version_file_url="$uncached_feed/Sdk/$channel/latest.version"
        fi
    else
        say_err "Invalid value for \$runtime"
        return 1
    fi
    say_verbose "get_latest_version_info: latest url: $version_file_url"

    download "$version_file_url"
    return $?
}

# args:
# azure_feed - $1
# channel - $2
# normalized_architecture - $3
# version - $4
get_specific_version_from_version() {
    eval $invocation

    local azure_feed="$1"
    local channel="$2"
    local normalized_architecture="$3"
    local version="$(to_lowercase "$4")"

    case "$version" in
        latest)
            local version_info
            version_info="$(get_latest_version_info "$azure_feed" "$channel" "$normalized_architecture" false)" || return 1
            say_verbose "get_specific_version_from_version: version_info=$version_info"
            echo "$version_info" | get_version_from_version_info
            return 0
            ;;
        coherent)
            local version_info
            version_info="$(get_latest_version_info "$azure_feed" "$channel" "$normalized_architecture" true)" || return 1
            say_verbose "get_specific_version_from_version: version_info=$version_info"
            echo "$version_info" | get_version_from_version_info
            return 0
            ;;
        *)
            echo "$version"
            return 0
            ;;
    esac
}

# args:
# azure_feed - $1
# channel - $2
# normalized_architecture - $3
# specific_version - $4
construct_download_link() {
    eval $invocation

    local azure_feed="$1"
    local channel="$2"
    local normalized_architecture="$3"
    local specific_version="${4//[$'\t\r\n']}"

    local osname
    osname="$(get_current_os_name)" || return 1

    local download_link=null
    if [[ "$runtime" == "dotnet" ]]; then
        download_link="$azure_feed/Runtime/$specific_version/dotnet-runtime-$specific_version-$osname-$normalized_architecture.tar.gz"
    elif [[ "$runtime" == "aspnetcore" ]]; then
        download_link="$azure_feed/aspnetcore/Runtime/$specific_version/aspnetcore-runtime-$specific_version-$osname-$normalized_architecture.tar.gz"
    elif [ -z "$runtime" ]; then
        download_link="$azure_feed/Sdk/$specific_version/dotnet-sdk-$specific_version-$osname-$normalized_architecture.tar.gz"
    else
        return 1
    fi

    echo "$download_link"
    return 0
}

# args:
# azure_feed - $1
# channel - $2
# normalized_architecture - $3
# specific_version - $4
construct_legacy_download_link() {
    eval $invocation

    local azure_feed="$1"
    local channel="$2"
    local normalized_architecture="$3"
    local specific_version="${4//[$'\t\r\n']}"

    local distro_specific_osname
    distro_specific_osname="$(get_legacy_os_name)" || return 1

    local legacy_download_link=null
    if [[ "$runtime" == "dotnet" ]]; then
        legacy_download_link="$azure_feed/Runtime/$specific_version/dotnet-$distro_specific_osname-$normalized_architecture.$specific_version.tar.gz"
    elif [ -z "$runtime" ]; then
        legacy_download_link="$azure_feed/Sdk/$specific_version/dotnet-dev-$distro_specific_osname-$normalized_architecture.$specific_version.tar.gz"
    else
        return 1
    fi

    echo "$legacy_download_link"
    return 0
}

get_user_install_path() {
    eval $invocation

    if [ ! -z "${DOTNET_INSTALL_DIR:-}" ]; then
        echo "$DOTNET_INSTALL_DIR"
    else
        echo "$HOME/.dotnet"
    fi
    return 0
}

# args:
# install_dir - $1
resolve_installation_path() {
    eval $invocation

    local install_dir=$1
    if [ "$install_dir" = "<auto>" ]; then
        local user_install_path="$(get_user_install_path)"
        say_verbose "resolve_installation_path: user_install_path=$user_install_path"
        echo "$user_install_path"
        return 0
    fi

    echo "$install_dir"
    return 0
}

# args:
# install_root - $1
get_installed_version_info() {
    eval $invocation

    local install_root="$1"
    local version_file="$(combine_paths "$install_root" "$local_version_file_relative_path")"
    say_verbose "Local version file: $version_file"
    if [ ! -z "$version_file" ] | [ -r "$version_file" ]; then
        local version_info="$(cat "$version_file")"
        echo "$version_info"
        return 0
    fi

    say_verbose "Local version file not found."
    return 0
}

# args:
# relative_or_absolute_path - $1
get_absolute_path() {
    eval $invocation

    local relative_or_absolute_path=$1
    echo "$(cd "$(dirname "$1")" && pwd -P)/$(basename "$1")"
    return 0
}

# args:
# input_files - stdin
# root_path - $1
# out_path - $2
# override - $3
copy_files_or_dirs_from_list() {
    eval $invocation

    local root_path="$(remove_trailing_slash "$1")"
    local out_path="$(remove_trailing_slash "$2")"
    local override="$3"
    local osname="$(get_current_os_name)"
    local override_switch=$(
        if [ "$override" = false ]; then
            if [[ "$osname" == "linux-musl" ]]; then
                printf -- "-u";
            else
                printf -- "-n";
            fi
        fi)

    cat | uniq | while read -r file_path; do
        local path="$(remove_beginning_slash "${file_path#$root_path}")"
        local target="$out_path/$path"
        if [ "$override" = true ] || (! ([ -d "$target" ] || [ -e "$target" ])); then
            mkdir -p "$out_path/$(dirname "$path")"
            cp -R $override_switch "$root_path/$path" "$target"
        fi
    done
}

# args:
# zip_path - $1
# out_path - $2
extract_dotnet_package() {
    eval $invocation

    local zip_path="$1"
    local out_path="$2"

    local temp_out_path="$(mktemp -d "$temporary_file_template")"

    local failed=false
    tar -xzf "$zip_path" -C "$temp_out_path" > /dev/null || failed=true

    local folders_with_version_regex='^.*/[0-9]+\.[0-9]+[^/]+/'
    find "$temp_out_path" -type f | grep -Eo "$folders_with_version_regex" | sort | copy_files_or_dirs_from_list "$temp_out_path" "$out_path" false
    find "$temp_out_path" -type f | grep -Ev "$folders_with_version_regex" | copy_files_or_dirs_from_list "$temp_out_path" "$out_path" "$override_non_versioned_files"

    rm -rf "$temp_out_path"

    if [ "$failed" = true ]; then
        say_err "Extraction failed"
        return 1
    fi
}

# args:
# remote_path - $1
# [out_path] - $2 - stdout if not provided
download() {
    eval $invocation

    local remote_path="$1"
    local out_path="${2:-}"

    local failed=false
    if machine_has "curl"; then
        downloadcurl "$remote_path" "$out_path" || failed=true
    elif machine_has "wget"; then
        downloadwget "$remote_path" "$out_path" || failed=true
    else
        failed=true
    fi
    if [ "$failed" = true ]; then
        say_verbose "Download failed: $remote_path"
        return 1
    fi
    return 0
}

downloadcurl() {
    eval $invocation
    local remote_path="$1"
    local out_path="${2:-}"

    # Append feed_credential as late as possible before calling curl to avoid logging feed_credential
    remote_path="${remote_path}${feed_credential}"

    local failed=false
    if [ -z "$out_path" ]; then
        curl --retry 10 -sSL -f --create-dirs "$remote_path" || failed=true
    else
        curl --retry 10 -sSL -f --create-dirs -o "$out_path" "$remote_path" || failed=true
    fi
    if [ "$failed" = true ]; then
        say_verbose "Curl download failed"
        return 1
    fi
    return 0
}

downloadwget() {
    eval $invocation
    local remote_path="$1"
    local out_path="${2:-}"

    # Append feed_credential as late as possible before calling wget to avoid logging feed_credential
    remote_path="${remote_path}${feed_credential}"

    local failed=false
    if [ -z "$out_path" ]; then
        wget -q --tries 10 -O - "$remote_path" || failed=true
    else
        wget --tries 10 -O "$out_path" "$remote_path" || failed=true
    fi
    if [ "$failed" = true ]; then
        say_verbose "Wget download failed"
        return 1
    fi
    return 0
}

calculate_vars() {
    eval $invocation
    valid_legacy_download_link=true

    normalized_architecture="$(get_normalized_architecture_from_architecture "$architecture")"
    say_verbose "normalized_architecture=$normalized_architecture"

    specific_version="$(get_specific_version_from_version "$azure_feed" "$channel" "$normalized_architecture" "$version")"
    say_verbose "specific_version=$specific_version"
    if [ -z "$specific_version" ]; then
        say_err "Could not get version information."
        return 1
    fi

    download_link="$(construct_download_link "$azure_feed" "$channel" "$normalized_architecture" "$specific_version")"
    say_verbose "download_link=$download_link"

    legacy_download_link="$(construct_legacy_download_link "$azure_feed" "$channel" "$normalized_architecture" "$specific_version")" || valid_legacy_download_link=false

    if [ "$valid_legacy_download_link" = true ]; then
        say_verbose "legacy_download_link=$legacy_download_link"
    else
        say_verbose "Cound not construct a legacy_download_link; omitting..."
    fi

    install_root="$(resolve_installation_path "$install_dir")"
    say_verbose "install_root=$install_root"
}

install_dotnet() {
    eval $invocation
    local download_failed=false
    local asset_name=''
    local asset_relative_path=''

    if [[ "$runtime" == "dotnet" ]]; then
        asset_relative_path="shared/Microsoft.NETCore.App"
        asset_name=".NET Core Runtime"
    elif [[ "$runtime" == "aspnetcore" ]]; then
        asset_relative_path="shared/Microsoft.AspNetCore.App"
        asset_name="ASP.NET Core Runtime"
    elif [ -z "$runtime" ]; then
        asset_relative_path="sdk"
        asset_name=".NET Core SDK"
    else
        say_err "Invalid value for \$runtime"
        return 1
    fi

    #  Check if the SDK version is already installed.
    if is_dotnet_package_installed "$install_root" "$asset_relative_path" "$specific_version"; then
        say "$asset_name version $specific_version is already installed."
        return 0
    fi

    mkdir -p "$install_root"
    zip_path="$(mktemp "$temporary_file_template")"
    say_verbose "Zip path: $zip_path"

    say "Downloading link: $download_link"

    # Failures are normal in the non-legacy case for ultimately legacy downloads.
    # Do not output to stderr, since output to stderr is considered an error.
    download "$download_link" "$zip_path" 2>&1 || download_failed=true

    #  if the download fails, download the legacy_download_link
    if [ "$download_failed" = true ]; then
        say "Cannot download: $download_link"

        if [ "$valid_legacy_download_link" = true ]; then
            download_failed=false
            download_link="$legacy_download_link"
            zip_path="$(mktemp "$temporary_file_template")"
            say_verbose "Legacy zip path: $zip_path"
            say "Downloading legacy link: $download_link"
            download "$download_link" "$zip_path" 2>&1 || download_failed=true
        fi
    fi

    if [ "$download_failed" = true ]; then
        say_err "Could not download $asset_name version $specific_version"
        return 1
    fi

    say "Extracting zip from $download_link"
    extract_dotnet_package "$zip_path" "$install_root"

    #  Check if the SDK version is now installed; if not, fail the installation.
    if ! is_dotnet_package_installed "$install_root" "$asset_relative_path" "$specific_version"; then
        say_err "$asset_name version $specific_version failed to install with an unknown error."
        return 1
    fi

    return 0
}

local_version_file_relative_path="/.version"
bin_folder_relative_path=""
temporary_file_template="${TMPDIR:-/tmp}/dotnet.XXXXXXXXX"

channel="LTS"
version="Latest"
install_dir="<auto>"
architecture="<auto>"
dry_run=false
no_path=false
azure_feed="https://dotnetcli.azureedge.net/dotnet"
uncached_feed="https://dotnetcli.blob.core.windows.net/dotnet"
feed_credential=""
verbose=false
runtime=""
runtime_id=""
override_non_versioned_files=true

while [ $# -ne 0 ]
do
    name="$1"
    case "$name" in
        -c|--channel|-[Cc]hannel)
            shift
            channel="$1"
            ;;
        -v|--version|-[Vv]ersion)
            shift
            version="$1"
            ;;
        -i|--install-dir|-[Ii]nstall[Dd]ir)
            shift
            install_dir="$1"
            ;;
        --arch|--architecture|-[Aa]rch|-[Aa]rchitecture)
            shift
            architecture="$1"
            ;;
        --shared-runtime|-[Ss]hared[Rr]untime)
            say_warning "The --shared-runtime flag is obsolete and may be removed in a future version of this script. The recommended usage is to specify '--runtime dotnet'."
            if [ -z "$runtime" ]; then
                runtime="dotnet"
            fi
            ;;
        --runtime|-[Rr]untime)
            shift
            runtime="$1"
            if [[ "$runtime" != "dotnet" ]] && [[ "$runtime" != "aspnetcore" ]]; then
                say_err "Unsupported value for --runtime: '$1'. Valid values are 'dotnet' and 'aspnetcore'."
                exit 1
            fi
            ;;
        --dry-run|-[Dd]ry[Rr]un)
            dry_run=true
            ;;
        --no-path|-[Nn]o[Pp]ath)
            no_path=true
            ;;
        --verbose|-[Vv]erbose)
            verbose=true
            ;;
        --azure-feed|-[Aa]zure[Ff]eed)
            shift
            azure_feed="$1"
            ;;
        --uncached-feed|-[Uu]ncached[Ff]eed)
            shift
            uncached_feed="$1"
            ;;
        --feed-credential|-[Ff]eed[Cc]redential)
            shift
            feed_credential="$1"
            ;;
        --runtime-id|-[Rr]untime[Ii]d)
            shift
            runtime_id="$1"
            ;;
        --skip-non-versioned-files|-[Ss]kip[Nn]on[Vv]ersioned[Ff]iles)
            override_non_versioned_files=false
            ;;
        -?|--?|-h|--help|-[Hh]elp)
            script_name="$(basename "$0")"
            echo ".NET Tools Installer"
            echo "Usage: $script_name [-c|--channel <CHANNEL>] [-v|--version <VERSION>] [-p|--prefix <DESTINATION>]"
            echo "       $script_name -h|-?|--help"
            echo ""
            echo "$script_name is a simple command line interface for obtaining dotnet cli."
            echo ""
            echo "Options:"
            echo "  -c,--channel <CHANNEL>         Download from the channel specified, Defaults to \`$channel\`."
            echo "      -Channel"
            echo "          Possible values:"
            echo "          - Current - most current release"
            echo "          - LTS - most current supported release"
            echo "          - 2-part version in a format A.B - represents a specific release"
            echo "              examples: 2.0; 1.0"
            echo "          - Branch name"
            echo "              examples: release/2.0.0; Master"
            echo "  -v,--version <VERSION>         Use specific VERSION, Defaults to \`$version\`."
            echo "      -Version"
            echo "          Possible values:"
            echo "          - latest - most latest build on specific channel"
            echo "          - coherent - most latest coherent build on specific channel"
            echo "              coherent applies only to SDK downloads"
            echo "          - 3-part version in a format A.B.C - represents specific version of build"
            echo "              examples: 2.0.0-preview2-006120; 1.1.0"
            echo "  -i,--install-dir <DIR>             Install under specified location (see Install Location below)"
            echo "      -InstallDir"
            echo "  --architecture <ARCHITECTURE>      Architecture of dotnet binaries to be installed, Defaults to \`$architecture\`."
            echo "      --arch,-Architecture,-Arch"
            echo "          Possible values: x64, arm, and arm64"
            echo "  --runtime <RUNTIME>                Installs a shared runtime only, without the SDK."
            echo "      -Runtime"
            echo "          Possible values:"
            echo "          - dotnet     - the Microsoft.NETCore.App shared runtime"
            echo "          - aspnetcore - the Microsoft.AspNetCore.App shared runtime"
            echo "  --skip-non-versioned-files         Skips non-versioned files if they already exist, such as the dotnet executable."
            echo "      -SkipNonVersionedFiles"
            echo "  --dry-run,-DryRun                  Do not perform installation. Display download link."
            echo "  --no-path, -NoPath                 Do not set PATH for the current process."
            echo "  --verbose,-Verbose                 Display diagnostics information."
            echo "  --azure-feed,-AzureFeed            Azure feed location. Defaults to $azure_feed, This parameter typically is not changed by the user."
            echo "  --uncached-feed,-UncachedFeed      Uncached feed location. This parameter typically is not changed by the user."
            echo "  --feed-credential,-FeedCredential  Azure feed shared access token. This parameter typically is not specified."
            echo "  --runtime-id                       Installs the .NET Tools for the given platform (use linux-x64 for portable linux)."
            echo "      -RuntimeId"
            echo "  -?,--?,-h,--help,-Help             Shows this help message"
            echo ""
            echo "Obsolete parameters:"
            echo "  --shared-runtime                   The recommended alternative is '--runtime dotnet'."
            echo "      -SharedRuntime                 Installs just the shared runtime bits, not the entire SDK."
            echo ""
            echo "Install Location:"
            echo "  Location is chosen in following order:"
            echo "    - --install-dir option"
            echo "    - Environmental variable DOTNET_INSTALL_DIR"
            echo "    - $HOME/.dotnet"
            exit 0
            ;;
        *)
            say_err "Unknown argument \`$name\`"
            exit 1
            ;;
    esac

    shift
done

check_min_reqs
calculate_vars

if [ "$dry_run" = true ]; then
    say "Payload URL: $download_link"
    if [ "$valid_legacy_download_link" = true ]; then
        say "Legacy payload URL: $legacy_download_link"
    fi
    say "Repeatable invocation: ./$(basename "$0") --version $specific_version --channel $channel --install-dir $install_dir"
    exit 0
fi

check_pre_reqs
install_dotnet

bin_path="$(get_absolute_path "$(combine_paths "$install_root" "$bin_folder_relative_path")")"
if [ "$no_path" = false ]; then
    say "Adding to current process PATH: \`$bin_path\`. Note: This change will be visible only when sourcing script."
    export PATH="$bin_path":"$PATH"
else
    say "Binaries of dotnet can be found in $bin_path"
fi

say "Installation finished successfully."


#! /bin/sh

if [ -z "$AzureWebJobsScriptRoot" ]; then
    cd /home/site/wwwroot
else
    cd "$AzureWebJobsScriptRoot"
fi

echo '{'
echo '"hostJson":'
if [ -f "host.json" ]; then
    cat host.json
else
    echo '{ }'
fi

echo ','

echo '"functionsJson": {'

for d in */; do
    d=$(echo $d | tr -d '/')
    if [ -f "${d}/function.json" ]; then
        echo "\"${d}\": "
        cat "${d}/function.json"
        echo ','
    fi
done
echo '}'
echo '}'


ï»¿#! /bin/bash

# Exit on errors
set -e

PYTHON_PACKAGE_PATH="/.python_packages/lib/site-packages"
if [[ "$PYTHON_VERSION" == "3.6"* ]]; then
    PYTHON_PACKAGE_PATH="/.python_packages/lib/python3.6/site-packages"
fi;

pip install --target="$PYTHON_PACKAGE_PATH" -r /requirements.txt


#! /bin/sh
set -e

unzip -n /file.zip -d /tmp/extract/
chown -R $USER:$USER /tmp/extract
chmod -R +r /tmp/extract
mksquashfs /tmp/extract /file.squashfs -noappend


#! /bin/bash

DIR=$(dirname $0)
IFS=$'\n'

select_version() {
    ## Selects the directory of the version to be generated
    ## Defaults to v3 for now
    if [ "$VERSION" == "4" ]; then
        echo "Version 4 selected"
        DIR=$(dirname $0)/4/bullseye/amd64/base
    elif [ "$VERSION" == "3" ]; then
        echo "Version 4 selected"
        DIR=$(dirname $0)/3.0/buster/amd64/base
    else
        echo "No valid version selected. Must provide a valid version via -3 or -4 flags"
        exit 1
    fi
}

globalize_args() {
    ## This method is used to bring all args preceding any From statements to the top of the file.
    ## Allows for ARGs defined globally in composite images to be global in the compiled dockerfile
    ## list of args in arr with carriage returns at end
    gblarg=$((sed -n '/FROM/q;p' $1) | grep ARG)
    if [ ${#gblarg[@]} == 0 ]; then
        printf "\t No global ARGs in $1 \n"
    else
        printf "\t ARGs globalized for $1 : \n"
        for arg in ${gblarg[@]};
        do
            printf "\t\t $arg \n"
        done
    fi
}

combine_dockerfile() {
    printf $"  Combining $base with $1\n"
    localfile=$(printf $1 | awk -F'\\.\\.' '{print $2}')
    runtime=`echo $localfile | cut -d'/' -f 2`
    runtimeversion=`echo $localfile | cut -d'/' -f 3`
    printf "\t Image Runtime and Version: $runtimeversion \n"

    # Output path

    # File structure creation
    outputdir=$"$DIR/../out/${runtime}"
    if [ "$RELEASE" == "true" ]; then
        printf "\t Release Mode enabled. Updating release dockerfiles.\n"
        outputdir=$"$DIR/../release/${runtime}"
    fi
    mkdir -p $outputdir
    outputfile="$outputdir/${runtimeversion}-appservice.Dockerfile"

    printf $"\t Collecting global arguments in $1 to globalize them in the final dockerfile.\n"
    globalize_args $1
    echo "${gblarg[@]}" | cat - $base $1 > $outputfile

    printf $"\t Completed compilation of $runtimeversion. Output file available at : $outputfile\n"
}

generate_appservice() {
    base="$DIR/host.Dockerfile"
    echo $"Generating Appservice Images for [ $@ ] using base $base"
    for lang in $@;
    do
        langimgs=($(find $DIR/../$lang/ -name "*-composite.template"))
        if [ -z "$langimgs" ]; then
            echo "No composite images found for language : $lang. Skipping compilation..."
        else
            echo $"Found following images for compilation of language $lang: ${langimgs[@]}"
            for version in ${langimgs[@]};
            do
                combine_dockerfile $version
                printf "\n"
            done
            printf $"Completed compilation of $lang images \n\n"
        fi
    done
    echo "Compilation of all images in list: [ $@ ] complete."
    printf "\n"
}

copy_shared_config() {

    echo "Copying shared config files into the following language output directories: "
    for lang in $@;
    do
        outputdir=$"$DIR/../out/${lang}/"
        if [ "$RELEASE" == "true" ]; then
            outputdir=$"$DIR/../release/${lang}/"
        fi
        printf "\t $outputdir\n"
        cp -R $DIR/sharedconfig/* $outputdir
    done
}

clear_outputdir() {
    ## Seems to not be working currently. Further investigation needed
    echo "Clearing output folder..."
    rootdir=$"$DIR/../out/*"
    rm -rf rootdir
}

# Defines a flag -r : Release Mode.  Release mode will generate artifacts in a folder titled /release/
# These .Dockerfile artifacts will be used to create the containers uploaded to ACR. Increases trace-ability.
# Flags must come before parameters.
while getopts ":r43" flag;do
    case ${flag} in
      r)
        RELEASE="true"
        echo "Release Mode is enabled"
        ;;
      4)
        VERSION="4"
        echo "Version 4 selected"
        ;;
      3)
        VERSION="3"
        echo "Version 3 selected"
        ;;
    esac
done

select_version

echo "Dir is : $DIR"

if [ -z $RELEASE ]; then
    clear_outputdir
fi

# Remove flags from input. Store args in array
declare -a argarray
for arg do
    if [ "${arg:0:1}" != '-' ]; then
        echo $arg
        argarray+=($arg)
    fi
done

if [ ${#argarray[@]} == 0 ]; then
    echo "No language arguments supplied for compilation. Please supply a supported language or 'all' as an input."
    exit 1
fi

if [ ${#argarray[@]} == 1 ] && [ "$argarray" == "all" ]; then
    echo "All supported languages targetted."
    supportedlangs=("java" "node" "python" "dotnet" "powershell")
    argarray=(${supportedlangs[@]})
fi

generate_appservice ${argarray[@]}

copy_shared_config ${argarray[@]}


#! /bin/sh -eu

# Copy files from /usr/share/maven/ref into ${MAVEN_CONFIG}
# So the initial ~/.m2 is set with expected content.
# Don't override, as this is just a reference setup

copy_reference_files() {
  local log="$MAVEN_CONFIG/copy_reference_file.log"
  local ref="/usr/share/maven/ref"

  if mkdir -p "${MAVEN_CONFIG}/repository" && touch "${log}" > /dev/null 2>&1 ; then
      cd "${ref}"
      local reflink=""
      if cp --help 2>&1 | grep -q reflink ; then
          reflink="--reflink=auto"
      fi
      if [ -n "$(find "${MAVEN_CONFIG}/repository" -maxdepth 0 -type d -empty 2>/dev/null)" ] ; then
          # destination is empty...
          echo "--- Copying all files to ${MAVEN_CONFIG} at $(date)" >> "${log}"
          cp -rv ${reflink} . "${MAVEN_CONFIG}" >> "${log}"
      else
          # destination is non-empty, copy file-by-file
          echo "--- Copying individual files to ${MAVEN_CONFIG} at $(date)" >> "${log}"
          find . -type f -exec sh -eu -c '
              log="${1}"
              shift
              reflink="${1}"
              shift
              for f in "$@" ; do
                  if [ ! -e "${MAVEN_CONFIG}/${f}" ] || [ -e "${f}.override" ] ; then
                      mkdir -p "${MAVEN_CONFIG}/$(dirname "${f}")"
                      cp -rv ${reflink} "${f}" "${MAVEN_CONFIG}/${f}" >> "${log}"
                  fi
              done
          ' _ "${log}" "${reflink}" {} +
      fi
      echo >> "${log}"
  else
    echo "Can not write to ${log}. Wrong volume permissions? Carrying on ..."
  fi
}

owd="$(pwd)"
copy_reference_files
unset MAVEN_CONFIG

cd "${owd}"
unset owd

exec "$@"


#! /bin/bash

DIR=$(dirname $0)

function print_usage {
  echo -e "Usage: $0 <MajorVersion> <FullVersion>\n"
  echo -e "Requires gnu-sed for it to work. Please install it using `brew install gnu-sed --with-default-names`"
  echo -e "Example: $0 3.0 3.1.1"
  echo -e "Example: $0 4.0 4.10.2"
}

if [ "$1" != "3" ] && [ "$1" != "4" ]; then
  echo -e "MajorVersion must be '3', or '4' Got '$1'\n"
  print_usage
  exit 1
fi

if [ -z "$2" ]; then
  echo -e "Please pass the FullVersion. The whole FullVersion is required.\n"
  print_usage
  exit 1
fi

if [ "$1" == "3" ]; then
   find $DIR/3.0 -name "*Dockerfile" -exec gsed -i "s/\bHOST_VERSION=$1\..*/HOST_VERSION=$2/g" {} \;
else
   find $DIR/$1 -name "*Dockerfile" -exec gsed -i "s/\bHOST_VERSION=$1\..*/HOST_VERSION=$2/g" {} \;
fi


#! /bin/bash

DIR=$(dirname $0)

function print_usage {
  echo -e "Usage: $0 <MajorVersion> <FullVersion>\n"
  echo -e "Example: $0 3.0 3.1.1"
  echo -e "Example: $0 4.0 4.10.2"
}

if [ "$1" != "3" ] && [ "$1" != "4" ]; then
  echo -e "MajorVersion must be '3', or '4' Got '$1'\n"
  print_usage
  exit 1
fi

if [ -z "$2" ]; then
  echo -e "Please pass the FullVersion. The whole FullVersion is required.\n"
  print_usage
  exit 1
fi

if [ "$1" == "3" ]; then
   find $DIR/3.0 -name "*Dockerfile" -exec sed -i "s/\bHOST_VERSION=$1\..*/HOST_VERSION=$2/g" "$0" {} \;
else
   find $DIR/$1 -name "*Dockerfile" -exec sed -i "s/\bHOST_VERSION=$1\..*/HOST_VERSION=$2/g" "$0" {} \;
fi


#! /bin/bash

DIR=$(dirname $0)
IFS=$'\n'

check_sovereign() {
  sharedimages=($(comm -12 <(printf '%s\n' "${stage[@]}"|sort -u) <(printf '%s\n' "${pub[@]}"|sort -u)))
  sovereign=($(((grep "docker push".*appservice ${TARGET}/publish-appservice-stage-sovereign-clouds.yml) | awk -F'-appservice' '{print $1}') | awk -F 'TARGET_REGISTRY' '{print $2}') )
  diffsovereign=($(comm -3 <(printf '%s\n' "${sharedimages[@]}"|sort -u) <(printf '%s\n' "${sovereign[@]}"|sort -u)))
  if [ -z "$diffsovereign" ]; then
    echo -e "Sovereign pipeline verified for ${TARGET}/. Proceed with release.\n"
    exit 0
  else
    echo -e "Sovereign pipeline is invalid. Other than the /base image all pipelines should publish the same -appservice images. The following differences exist for -appservice images in the sovereign pipeline: "
    echo -e ${diffsovereign[@]}
    exit 1
  fi
}

if [ "$1" != "2.0" ] && [ "$1" != "3" ] && [ "$1" != "4" ]; then
  echo -e "MajorVersion must be 2.0, 3, or 4 Got '$1'\n"
  print_usage
  exit 1
fi

if [ "$1" == "2.0" ]; then
   echo -e "MajorVersion 2.0 is not supported by this script. Continuing with NoOp"
   exit 0
fi

if [ "$1" == "3" ]; then
   echo -e "MajorVersion 3 detected. Verifying pipelines in host/3.0/"
   TARGET="./3.0"
else
   echo -e "MajorVersion 4 detected. Verifying pipelines in host/4/"
   TARGET="./4"
fi

stage=($(((grep "docker push".*appservice ${TARGET}/publish-appservice-stage.yml) | awk -F'-appservice' '{print $1}') | awk -F 'TARGET_REGISTRY' '{print $2}') )

pub=($((((grep "docker push".*appservice  ${TARGET}/publish.yml)| grep -v quickstart) | awk -F'-appservice' '{print $1}') | awk -F 'TARGET_REGISTRY' '{print $2}') )

difference=($(comm -3 <(printf '%s\n' "${stage[@]}"|sort -u) <(printf '%s\n' "${pub[@]}"|sort -u)))

if [ -z "$difference" ]; then
  echo -e "No differences between Stage and Publish pipelines.  Verifying sovereign cloud pipeline.\n"
  check_sovereign
  exit 0
fi

if [ ${#difference[@]} == 1 ] && [[ $difference =~ "base" ]]; then
   echo -e "Stage pipeline excludes base image. This is a known difference. Rollout Safe. Verifying sovereign cloud pipeline."
   check_sovereign
   exit 0
else
   echo -e "Publish and stage pipelines inconsistent. Other than the /base image all pipelines should publish the same -appservice images. The following differences exist for -appservice images between the pipelines: "
   echo -e ${difference[@]}
   exit 1
fi


#! /bin/bash

DIR=$(dirname $0)
IFS=$'\n'

fullversion=$1
majorversion=${fullversion:0:1}

if [ "$majorversion" != "2" ] && [ "$majorversion" != "3" ] && [ "$majorversion" != "4" ]; then
  echo -e "MajorVersion must be 2, 3, or 4 Got '$1'\n"
  print_usage
  exit 1
fi

if [ "$majorversion" == "2" ]; then
   echo -e "MajorVersion 2 is not supported by this script. Continuing with NoOp"
   exit 0
fi

if [ "$majorversion" == "3" ]; then
   echo -e "MajorVersion 3 detected. Verifying pipelines in host/3.0/"
   TARGET="./3.0"
else
   echo -e "MajorVersion 4 detected. Verifying pipelines in host/4/"
   TARGET="./4"
fi

repub=($(((grep "docker push".* ${TARGET}/republish.yml) | awk -F 'TARGET_REGISTRY' '{print $2}') ))

pub=($(((((grep "docker push".*  ${TARGET}/publish.yml)| grep -v quickstart)| grep -v nanoserver) | awk -F 'TARGET_REGISTRY' '{print $2}') ))

difference=($(comm -3 <(printf '%s\n' "${repub[@]}"|sort -u) <(printf '%s\n' "${pub[@]}"|sort -u)))

if [ -z "$difference" ]; then
  echo -e "No differences between Republish and Publish pipelines.\n"
  exit 0
fi

echo ${difference[@]} | tr -d '\r'
if [ ${#difference[@]} == 1 ] && [[ $difference == *"nanoserver"* ]]; then
   echo -e "Republish pipeline excludes nanoserver image. This is a known difference. Redeployment Safe. \n"
   exit 0
else
   echo -e "Republish and Publish pipelines inconsistent. Other than the /base image all pipelines should publish the same non-quickstart images. The following differences exist for images between the pipelines: "
   echo -e ${difference[@]}
   exit 1
fi


#!/usr/bin/env bash

export DOTNET_USE_POLLING_FILE_WATCHER=true

if [ -z $PORT ]; then
  export ASPNETCORE_URLS=http://*:80
else
  export ASPNETCORE_URLS=http://*:$PORT
fi

if [ -z $SSH_PORT ]; then
  export SSH_PORT=2222
fi

if [ "$APPSVC_REMOTE_DEBUGGING" == "TRUE" ]; then
    export languageWorkers__node__arguments="--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT"
    export languageWorkers__python__arguments="-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT"
fi

# Get environment variables to show up in SSH session
eval $(printenv | sed -n "s/^\([^=]\+\)=\(.*\)$/export \1=\2/p" | sed 's/"/\\\"/g' | sed '/=/s//="/' | sed 's/$/"/' >> /etc/profile)

# starting sshd process
sed -i "s/SSH_PORT/$SSH_PORT/g" /etc/ssh/sshd_config

service ssh start

if [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then
    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost
else
    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll
fi


#!/usr/bin/env bash

export DOTNET_USE_POLLING_FILE_WATCHER=true

if [ -z $PORT ]; then
  export ASPNETCORE_URLS=http://*:80
else
  export ASPNETCORE_URLS=http://*:$PORT
fi

if [ -z $SSH_PORT ]; then
  export SSH_PORT=2222
fi

if [ "$APPSVC_REMOTE_DEBUGGING" == "TRUE" ]; then
    export languageWorkers__node__arguments="--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT"
    export languageWorkers__python__arguments="-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT"
fi

sed -i "s/SSH_PORT/$SSH_PORT/g" /etc/ssh/sshd_config

service ssh start

if [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then
    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost
else
    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll
fi


 #!/bin/bash

echo "Checking for prerequisites..."
if ! type npm > /dev/null; then
    echo "Prerequisite Check 1: Install Node.js and NPM"
    exit 1
fi

if ! type dotnet > /dev/null; then
    echo "Prerequisite Check 2: Install .NET Core 2.1 SDK or Runtime"
    exit 1
fi

if ! type func > /dev/null; then
    echo "Prerequisite Check 3: Install Azure Functions Core Tools"
    exit 1
fi

echo "Pre-requisites satisfied..."

echo "Creating sample folders..."
DIRECTORY=/tmp/df_test
if [ ! -d "$DIRECTORY" ]; then
  mkdir /tmp/df_test
else
  rm -rf /tmp/df_test/*
fi

SAMPLE=function_chaining
cp -r ../samples/$SAMPLE $DIRECTORY/
cd $DIRECTORY/$SAMPLE
python -m venv env
source env/bin/activate

echo "Provide local path to azure-functions-durable-python clone:"
read lib_path
pip install $lib_path/azure-functions-durable-python
func init .
func extensions install
echo "Done"


#!/bin/bash

mkdir ~/github
cd ~/github
git clone https://github.com/Azure/azure-functions-host.git
cd azure-functions-host
git checkout dev

cd tools/Crank/Agent
sudo find . -name "*.sh" -exec sudo chmod +xr {} \;
sudo find . -name "*.ps1" -exec sudo chmod +xr {} \;

Linux/install-powershell.sh

./setup-crank-agent-raw.ps1 $1 -Verbose


#!/bin/bash

# Following instructions at https://docs.docker.com/engine/install/ubuntu

sudo apt-get update

sudo apt-get install -y \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg-agent \
    software-properties-common

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io

sudo groupadd docker
sudo usermod -aG docker Functions
newgrp docker

sudo setfacl --modify user:Functions:rw /var/run/docker.sock

sudo systemctl enable docker


#!/bin/bash

# From https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-7#ubuntu-1804

# Download the Microsoft repository GPG keys
wget -q https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb

# Register the Microsoft repository GPG keys
sudo dpkg -i packages-microsoft-prod.deb

# Update the list of products
sudo apt-get update

# Enable the "universe" repositories
sudo add-apt-repository universe

# Install PowerShell
sudo apt-get install -y powershell


#!/usr/bin/env bash

docker build -t functions-crank-agent -f Dockerfile ../../


#!/usr/bin/env bash

docker run -it --name functions-crank-agent -d --network host --restart always --privileged \
--mount type=bind,source=/home/Functions/FunctionApps/HelloApp,target=/home/Functions/FunctionApps/HelloApp \
-v /var/run/docker.sock:/var/run/docker.sock functions-crank-agent "$@"


#!/usr/bin/env bash

docker stop functions-crank-agent
docker rm functions-crank-agent


# Simple tool to help for release
# when releasing with bash, simple source it to get asked questions.

# misc check before starting

python -c 'import keyring'
python -c 'import twine'
python -c 'import sphinx'
python -c 'import sphinx_rtd_theme'
python -c 'import nose'

BLACK=$(tput setaf 1)
RED=$(tput setaf 1)
GREEN=$(tput setaf 2)
YELLOW=$(tput setaf 3)
BLUE=$(tput setaf 4)
MAGENTA=$(tput setaf 5)
CYAN=$(tput setaf 6)
WHITE=$(tput setaf 7)
NOR=$(tput sgr0)

echo -n "PREV_RELEASE (X.y.z) [$PREV_RELEASE]: "
read input
PREV_RELEASE=${input:-$PREV_RELEASE}
echo -n "MILESTONE (X.y) [$MILESTONE]: "
read input
MILESTONE=${input:-$MILESTONE}
echo -n "VERSION (X.y.z) [$VERSION]:"
read input
VERSION=${input:-$VERSION}
echo -n "BRANCH (master|X.y) [$BRANCH]:"
read input
BRANCH=${input:-$BRANCH}

ask_section(){
    echo
    echo $BLUE"$1"$NOR
    echo -n $GREEN"Press Enter to continue, S to skip: "$NOR
    read -n1 value
    echo
    if [ -z $value ] || [ $value = 'y' ]  ; then
        return 0
    fi
    return 1
}

echo
if ask_section "Updating what's new with informations from docs/source/whatsnew/pr"
then
    python tools/update_whatsnew.py

    echo
    echo $BLUE"please move the contents of "docs/source/whatsnew/development.rst" to version-X.rst"$NOR
    echo $GREEN"Press enter to continue"$NOR
    read
fi

if ask_section "Gen Stats, and authors"
then

    echo
    echo $BLUE"here are all the authors that contributed to this release:"$NOR
    git log --format="%aN <%aE>" $PREV_RELEASE... | sort -u -f

    echo
    echo $BLUE"If you see any duplicates cancel (Ctrl-C), then edit .mailmap."
    echo $GREEN"Press enter to continue:"$NOR
    read

    echo $BLUE"generating stats"$NOR
    python tools/github_stats.py --milestone $MILESTONE > stats.rst

    echo $BLUE"stats.rst files generated."$NOR
    echo $GREEN"Please merge it with the right file (github-stats-X.rst) and commit."$NOR
    echo $GREEN"press enter to continue."$NOR
    read

fi

echo "Cleaning repository"
git clean -xfdi

echo $GREEN"please update version number in ${RED}IPython/core/release.py${NOR} , Do not commit yet â€“Â we'll do it later."$NOR

echo $GREEN"Press enter to continue"$NOR
read

if ask_section "Build the documentation ?"
then
    make html -C docs
    echo
    echo $GREEN"Check the docs, press enter to continue"$NOR
    read

fi

echo
echo $BLUE"Attempting to build package..."$NOR

tools/build_release
rm dist/*

if ask_section "Should we commit, tag, push... etc ? "
then
   echo
   echo $BLUE"Let's commit : git commit -am \"release $VERSION\" -S"
   echo $GREEN"Press enter to commit"$NOR
   read
   git commit -am "release $VERSION" -S

   echo
   echo $BLUE"git push origin \$BRANCH ($BRANCH)?"$NOR
   echo $GREEN"Make sure you can push"$NOR
   echo $GREEN"Press enter to continue"$NOR
   read
   git push origin $BRANCH

   echo
   echo "Let's tag : git tag -am \"release $VERSION\" \"$VERSION\" -s"
   echo $GREEN"Press enter to tag commit"$NOR
   read
   git tag -am "release $VERSION" "$VERSION" -s

   echo
   echo $BLUE"And push the tag: git push origin \$VERSION ?"$NOR
   echo $GREEN"Press enter to continue"$NOR
   read
   git push origin $VERSION

   echo $GREEN"please update version number and back to .dev in ${RED}IPython/core/release.py"
   echo ${BLUE}"Do not commit yet â€“Â we'll do it later."$NOR

   echo $GREEN"Press enter to continue"$NOR
   read

   echo
   echo "Let's commit : "$BLUE"git commit -am \"back to dev\""$NOR
   echo $GREEN"Press enter to commit"$NOR
   read
   git commit -am "back to dev"

   echo
   echo $BLUE"git push origin \$BRANCH ($BRANCH)?"$NOR
   echo $GREEN"Press enter to continue"$NOR
   read
   git push origin $BRANCH

   echo
   echo $BLUE"let's : git checkout $VERSION"$NOR
   echo $GREEN"Press enter to continue"$NOR
   read
   git checkout $VERSION
fi

if ask_section "Should we build and release ?"
then

    echo
    echo $BLUE"Attempting to build package..."$NOR

    tools/release

    echo $RED
    echo '$ shasum -a 256 dist/*'
    shasum -a 256 dist/*
    echo $NOR

    if ask_section "upload packages ?"
    then
       tools/release upload
    fi
fi


#!/bin/bash

CURRENT_DIR=`pwd`
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
cd $DIR/..

WORKING_DIR=temp
if [ -d "$WORKING_DIR" ]; then rm -rf $WORKING_DIR; fi

dotnet pack -o temp --include-symbols src/Microsoft.Azure.WebJobs.Extensions.Kafka/Microsoft.Azure.WebJobs.Extensions.Kafka.csproj /p:Version=100.100.100-pre

cd $CURRENT_DIR

docker build -f ./test/Microsoft.Azure.WebJobs.Extensions.Kafka.LangEndToEndTests/FunctionApps/java/EventHub/Dockerfile -t azure-functions-kafka-java-eventhub .
docker build -f ./test/Microsoft.Azure.WebJobs.Extensions.Kafka.LangEndToEndTests/FunctionApps/python/EventHub/Dockerfile -t azure-functions-kafka-python-eventhub .

docker build -f ./test/Microsoft.Azure.WebJobs.Extensions.Kafka.LangEndToEndTests/FunctionApps/java/Confluent/Dockerfile -t azure-functions-kafka-java-confluent .
docker build -f ./test/Microsoft.Azure.WebJobs.Extensions.Kafka.LangEndToEndTests/FunctionApps/python/Confluent/Dockerfile -t azure-functions-kafka-python-confluent .


#!/bin/bash

export COMPOSE_INTERACTIVE_NO_CLI=1

# start docker compose
docker-compose -f ./kafka-singlenode-compose.yaml  up --build -d

# wait until kafka is ready to create topic
# need to improve, adding a retry instead of a static sleep
sleep 30


#!/bin/bash

export COMPOSE_INTERACTIVE_NO_CLI=1

# start docker compose
docker-compose -f ./kafka-singlenode-compose.yaml  down


#!/bin/bash

export COMPOSE_INTERACTIVE_NO_CLI=1

# start docker compose
docker-compose up -d

# wait until kafka is ready to create topic
# need to improve, adding a retry instead of a static sleep
sleep 30

docker ps


#!/bin/bash

set -e

function usage() {
    cat <<USAGE
    Usage: $0 <options>
    Options:
        [-p|--functionapp-path] Function app path, relative to the repository root. It can be the project directory or compiled app directory.
                                Default: '.'
        [-u|--base-uri]         Base URI of the function app.
                                Default: 'http://localhost:7071/api/'
        [-e|--endpoint]         OpenAPI document endpoint.
                                Default: 'swagger.json'
        [-o|--output-path]      Output directory to store the generated OpenAPI document, relative to the repository root.
                                Default: 'generated'
        [-f|--output-filename]  Output filename for the generated OpenAPI document.
                                Default: 'swagger.json'
        [-d|--delay]            Delay in second between the function app run and document generation.
                                Default: 30
        [-c|--use-codespaces]   Switch indicating whether to use GitHub Codespaces or not.
        [-h|--help]             Show this message.
USAGE

    exit 1
}

functionapp_path="."
base_uri="http://localhost:7071/api/"
endpoint="swagger.json"
output_path="generated"
output_filename="swagger.json"
delay=30
repository_root=$GITHUB_WORKSPACE

if [[ $# -eq 0 ]]; then
    functionapp_path="."
    base_uri="http://localhost:7071/api/"
    endpoint="swagger.json"
    output_path="generated"
    output_filename="swagger.json"
    delay=30
    repository_root=$GITHUB_WORKSPACE
fi

while [[ "$1" != "" ]]; do
    case $1 in
    -p | --functionapp-path)
        shift
        functionapp_path=$1
        ;;

    -u | --base-uri)
        shift
        base_uri=$1
        ;;

    -e | --endpoint)
        shift
        endpoint=$1
        ;;

    -o | --output-path)
        shift
        output_path=$1
        ;;

    -f | --output-filename)
        shift
        output_filename=$1
        ;;

    -d | --delay)
        shift
        delay=$1
        ;;

    -c | --use_codespaces)
        repository_root=$CODESPACE_VSCODE_FOLDER
        ;;

    -h | --help)
        usage
        exit 1
        ;;

    *)
        usage
        exit 1
        ;;
    esac

    shift
done

current_directory=$(pwd)

cd "$repository_root/$functionapp_path"

# Run the function app in the background
func start --verbose false &

sleep $delay

request_uri="$(echo "$base_uri" | sed 's:/*$::')/$(echo "$endpoint" | sed 's:^/*::')"
filepath="$repository_root/$(echo "$output_path" | sed 's:/*$::')/$(echo "$output_filename" | sed 's:^/*::')"

if [ ! -d "$repository_root/$output_path" ]; then
    mkdir "$repository_root/$output_path"
fi

# Download the OpenAPI document
curl $request_uri > $filepath

# Stop the function app
PID=$(lsof -nP -i4TCP:7071 | grep LISTEN | awk '{print $2}')
if [[ "" !=  "$PID" ]]; then
    kill -9 $PID
fi

cd $current_directory


#!/bin/bash

python -m venv .env
source .env/bin/activate
python -m pip install --upgrade pip==23.0

python -m pip install .

python -m pip install . --no-compile --target "$BUILD_SOURCESDIRECTORY/deps"


#! /bin/bash

# $1 controls whether we allow reload module ("true" or "false")

SCRIPT_DIR="$(dirname $0)"
export PYTHONPATH="$SCRIPT_DIR/namespace_location_a:$SCRIPT_DIR/namespace_location_b"

python $SCRIPT_DIR/azure_namespace_import.py $1

unset PYTHONPATH


#! /bin/bash

# $2 is sys.path from caller
export PYTHONPATH="test_module_dir:$2"
SCRIPT_DIR="$(dirname $0)"

python $SCRIPT_DIR/path_import.py $1

unset PYTHONPATH


#!/usr/bin/env bash

set -euo pipefail
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

# Call "sync" between "chmod" and execution to prevent "text file busy" error in Docker (aufs)
chmod +x "$DIR/run.sh"; sync
"$DIR/run.sh" default-build "$@"


#!/usr/bin/env bash

set -euo pipefail

#
# variables
#

RESET="\033[0m"
RED="\033[0;31m"
YELLOW="\033[0;33m"
MAGENTA="\033[0;95m"
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
[ -z "${DOTNET_HOME:-}" ] && DOTNET_HOME="$HOME/.dotnet"
verbose=false
update=false
reinstall=false
repo_path="$DIR"
channel=''
tools_source=''
tools_source_suffix=''
ci=false

#
# Functions
#
__usage() {
    echo "Usage: $(basename "${BASH_SOURCE[0]}") command [options] [[--] <Arguments>...]"
    echo ""
    echo "Arguments:"
    echo "    command                The command to be run."
    echo "    <Arguments>...         Arguments passed to the command. Variable number of arguments allowed."
    echo ""
    echo "Options:"
    echo "    --verbose                                             Show verbose output."
    echo "    -c|--channel <CHANNEL>                                The channel of KoreBuild to download. Overrides the value from the config file.."
    echo "    --config-file <FILE>                                  The path to the configuration file that stores values. Defaults to korebuild.json."
    echo "    -d|--dotnet-home <DIR>                                The directory where .NET Core tools will be stored. Defaults to '\$DOTNET_HOME' or '\$HOME/.dotnet."
    echo "    --path <PATH>                                         The directory to build. Defaults to the directory containing the script."
    echo "    -s|--tools-source|-ToolsSource <URL>                  The base url where build tools can be downloaded. Overrides the value from the config file."
    echo "    --tools-source-suffix|-ToolsSourceSuffix <SUFFIX>     The suffix to append to tools-source. Useful for query strings."
    echo "    -u|--update                                           Update to the latest KoreBuild even if the lock file is present."
    echo "    --reinstall                                           Reinstall KoreBuild."
    echo "    --ci                                                  Apply CI specific settings and environment variables."
    echo ""
    echo "Description:"
    echo "    This function will create a file \$DIR/korebuild-lock.txt. This lock file can be committed to source, but does not have to be."
    echo "    When the lockfile is not present, KoreBuild will create one using latest available version from \$channel."

    if [[ "${1:-}" != '--no-exit' ]]; then
        exit 2
    fi
}

get_korebuild() {
    local version
    local lock_file="$repo_path/korebuild-lock.txt"
    if [ ! -f "$lock_file" ] || [ "$update" = true ]; then
        __get_remote_file "$tools_source/korebuild/channels/$channel/latest.txt" "$lock_file" "$tools_source_suffix"
    fi
    version="$(grep 'version:*' -m 1 "$lock_file")"
    if [[ "$version" == '' ]]; then
        __error "Failed to parse version from $lock_file. Expected a line that begins with 'version:'"
        return 1
    fi
    version="$(echo "${version#version:}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
    local korebuild_path="$DOTNET_HOME/buildtools/korebuild/$version"

    if [ "$reinstall" = true ] && [ -d "$korebuild_path" ]; then
        rm -rf "$korebuild_path"
    fi

    {
        if [ ! -d "$korebuild_path" ]; then
            mkdir -p "$korebuild_path"
            local remote_path="$tools_source/korebuild/artifacts/$version/korebuild.$version.zip"
            tmpfile="$(mktemp)"
            echo -e "${MAGENTA}Downloading KoreBuild ${version}${RESET}"
            if __get_remote_file "$remote_path" "$tmpfile" "$tools_source_suffix"; then
                unzip -q -d "$korebuild_path" "$tmpfile"
            fi
            rm "$tmpfile" || true
        fi

        echo "!!! Hack to use .NET Core SDK 5.0.301"
        local filePath=`find $korebuild_path -name sdk.version`
        echo "5.0.301" > $filePath

        source "$korebuild_path/KoreBuild.sh"
    } || {
        if [ -d "$korebuild_path" ]; then
            echo "Cleaning up after failed installation"
            rm -rf "$korebuild_path" || true
        fi
        return 1
    }
}

__error() {
    echo -e "${RED}error: $*${RESET}" 1>&2
}

__warn() {
    echo -e "${YELLOW}warning: $*${RESET}"
}

__machine_has() {
    hash "$1" > /dev/null 2>&1
    return $?
}

__get_remote_file() {
    local remote_path=$1
    local local_path=$2
    local remote_path_suffix=$3

    if [[ "$remote_path" != 'http'* ]]; then
        cp "$remote_path" "$local_path"
        return 0
    fi

    local failed=false
    if __machine_has wget; then
        wget --tries 10 --quiet -O "$local_path" "${remote_path}${remote_path_suffix}" || failed=true
    else
        failed=true
    fi

    if [ "$failed" = true ] && __machine_has curl; then
        failed=false
        curl --retry 10 -sSL -f --create-dirs -o "$local_path" "${remote_path}${remote_path_suffix}" || failed=true
    fi

    if [ "$failed" = true ]; then
        __error "Download failed: $remote_path" 1>&2
        return 1
    fi
}

#
# main
#

command="${1:-}"
shift

while [[ $# -gt 0 ]]; do
    case $1 in
        -\?|-h|--help)
            __usage --no-exit
            exit 0
            ;;
        -c|--channel|-Channel)
            shift
            channel="${1:-}"
            [ -z "$channel" ] && __usage
            ;;
        --config-file|-ConfigFile)
            shift
            config_file="${1:-}"
            [ -z "$config_file" ] && __usage
            if [ ! -f "$config_file" ]; then
                __error "Invalid value for --config-file. $config_file does not exist."
                exit 1
            fi
            ;;
        -d|--dotnet-home|-DotNetHome)
            shift
            DOTNET_HOME="${1:-}"
            [ -z "$DOTNET_HOME" ] && __usage
            ;;
        --path|-Path)
            shift
            repo_path="${1:-}"
            [ -z "$repo_path" ] && __usage
            ;;
        -s|--tools-source|-ToolsSource)
            shift
            tools_source="${1:-}"
            [ -z "$tools_source" ] && __usage
            ;;
        --tools-source-suffix|-ToolsSourceSuffix)
            shift
            tools_source_suffix="${1:-}"
            [ -z "$tools_source_suffix" ] && __usage
            ;;
        -u|--update|-Update)
            update=true
            ;;
        --reinstall|-[Rr]einstall)
            reinstall=true
            ;;
        --ci|-[Cc][Ii])
            ci=true
            ;;
        --verbose|-Verbose)
            verbose=true
            ;;
        --)
            shift
            break
            ;;
        *)
            break
            ;;
    esac
    shift
done

if ! __machine_has unzip; then
    __error 'Missing required command: unzip'
    exit 1
fi

if ! __machine_has curl && ! __machine_has wget; then
    __error 'Missing required command. Either wget or curl is required.'
    exit 1
fi

[ -z "${config_file:-}" ] && config_file="$repo_path/korebuild.json"
if [ -f "$config_file" ]; then
    if __machine_has jq ; then
        if jq '.' "$config_file" >/dev/null ; then
            config_channel="$(jq -r 'select(.channel!=null) | .channel' "$config_file")"
            config_tools_source="$(jq -r 'select(.toolsSource!=null) | .toolsSource' "$config_file")"
        else
            __error "$config_file contains invalid JSON."
            exit 1
        fi
    elif __machine_has python ; then
        if python -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'))" >/dev/null ; then
            config_channel="$(python -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['channel'] if 'channel' in obj else '')")"
            config_tools_source="$(python -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['toolsSource'] if 'toolsSource' in obj else '')")"
        else
            __error "$config_file contains invalid JSON."
            exit 1
        fi
    elif __machine_has python3 ; then
        if python3 -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'))" >/dev/null ; then
            config_channel="$(python3 -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['channel'] if 'channel' in obj else '')")"
            config_tools_source="$(python3 -c "import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['toolsSource'] if 'toolsSource' in obj else '')")"
        else
            __error "$config_file contains invalid JSON."
            exit 1
        fi
    else
        __error 'Missing required command: jq or python. Could not parse the JSON file.'
        exit 1
    fi

    [ ! -z "${config_channel:-}" ] && channel="$config_channel"
    [ ! -z "${config_tools_source:-}" ] && tools_source="$config_tools_source"
fi

[ -z "$channel" ] && channel='master'
[ -z "$tools_source" ] && tools_source='https://aspnetcore.blob.core.windows.net/buildtools'

get_korebuild
set_korebuildsettings "$tools_source" "$DOTNET_HOME" "$repo_path" "$config_file" "$ci"
invoke_korebuild_command "$command" "$@"


#!/bin/bash

set -x
set -e

chmod 777 *.sh
sudo apt-get update
sudo apt-get install -y build-essential libssl-dev libffi-dev libpython3-dev python3-dev python3-pip wget curl
sudo -H pip3 install --upgrade pip
sudo -H pip3 install --upgrade blobxfer==1.0.0
sudo -H pip3 install --upgrade azure-cosmosdb-table==1.0.0
sudo -H pip3 install --upgrade azure-batch==3.0.0