wrapper: check if /etc/wsl.conf exists

wrapper: check if /etc/wsl.conf exists

#!/bin/bash

# getting the arguments
pwd_win="$1"
shift
cmd="$@"

# loading the custom environment
wslalias_dir="$HOME/.wsl-alias"
wslalias_interactive="0"
if [ -z "$cmd" ]; then
  wslalias_interactive="1"
fi
if [ -f "$wslalias_dir/env.sh" ]; then
  source "$wslalias_dir/env.sh"
fi

# find the Windows drive mount root (thx to github.com/hustlahusky)
wsl_mount_root="/mnt/"
if [ -f "/etc/wsl.conf" ]; then
  if grep -q root /etc/wsl.conf; then
    wsl_mount_root=$(cat /etc/wsl.conf | awk '/root/ {print $3}')
  fi
fi

# parsing the path
pwd_wsl=$(echo "$pwd_win" | sed 's/\\/\//g')
pwd_wsl=$(echo "$pwd_wsl" | sed 's/://g')
pwd_wsl=$(echo "$pwd_wsl" | sed 's/^./\L&\E/')
pwd_wsl="$wsl_mount_root$pwd_wsl"

# mounting the drive if its not mounted
pwd_drive=${pwd_wsl:${#wsl_mount_root}:1}
pwd_drive_ls=$(ls -A "$wsl_mount_root$pwd_drive" 2>/dev/null)
if [ ! -d "$pwd_wsl" ] || [ -z "$pwd_drive_ls" ]; then
  user=$(whoami)
  user_uid=$(id -u "$user")
  user_gid=$(id -g "$user")
  echo "wsl: attempting to mount drive $pwd_drive:"
  mkdir -p "$wsl_mount_root$pwd_drive"
  sudo mount -o uid=$user_uid,gid=$user_gid -t drvfs $pwd_drive: $wsl_mount_root$pwd_drive
fi

cd "$pwd_wsl" 2>/dev/null
if [ -z "$cmd" ]; then
  cmd="$SHELL"
fi

# replace Windows file path in arguments (thx to github.com/hustlahusky)
while [[ $cmd =~ (.*)([A-Za-z]):(.*) ]]; do
  letter=$(echo "${BASH_REMATCH[2]}" | tr '[:upper:]' '[:lower:]')
  cmd=${BASH_REMATCH[1]}${wsl_mount_root}${letter}${BASH_REMATCH[3]}
done

eval "$cmd; exit $?"

#!/bin/bash

# getting the arguments
pwd_win="$1"
shift
cmd="$@"

# loading the custom environment
wslalias_dir="$HOME/.wsl-alias"
wslalias_interactive="0"
if [ -z "$cmd" ]; then
  wslalias_interactive="1"
fi
if [ -f "$wslalias_dir/env.sh" ]; then
  source "$wslalias_dir/env.sh"
fi

wsl_mount_root="/mnt/"
if grep -q root /etc/wsl.conf; then
  wsl_mount_root=$(cat /etc/wsl.conf | awk '/root/ {print $3}')
fi

# parsing the path
pwd_wsl=$(echo "$pwd_win" | sed 's/\\/\//g')
pwd_wsl=$(echo "$pwd_wsl" | sed 's/://g')
pwd_wsl=$(echo "$pwd_wsl" | sed 's/^./\L&\E/')
pwd_wsl="$wsl_mount_root$pwd_wsl"

# mounting the drive if its not mounted
pwd_drive=${pwd_wsl:${#wsl_mount_root}:1}
pwd_drive_ls=$(ls -A "$wsl_mount_root$pwd_drive" 2>/dev/null)
if [ ! -d "$pwd_wsl" ] || [ -z "$pwd_drive_ls" ]; then
  user=$(whoami)
  user_uid=$(id -u "$user")
  user_gid=$(id -g "$user")
  echo "wsl: attempting to mount drive $pwd_drive:"
  mkdir -p "$wsl_mount_root$pwd_drive"
  sudo mount -o uid=$user_uid,gid=$user_gid -t drvfs $pwd_drive: $wsl_mount_root$pwd_drive
fi

cd "$pwd_wsl" 2>/dev/null
if [ -z "$cmd" ]; then
  cmd="$SHELL"
fi

# Replace Windows file path in arguments
while [[ $cmd =~ (.*)([A-Za-z]):(.*) ]]; do
  letter=$(echo "${BASH_REMATCH[2]}" | tr '[:upper:]' '[:lower:]')
  cmd=${BASH_REMATCH[1]}${wsl_mount_root}${letter}${BASH_REMATCH[3]}
done

eval "$cmd; exit $?"


add VirtualBox uninstallers

add VirtualBox uninstallers

#!/bin/bash

#WORKSPACE_REPO="https://github.com/crobays/workspace/archive/master.zip"
WORKSPACE_REPO="http://gitlab.userx.nl/crobays/workspace/repository/archive.zip?ref=master"
VMWARE_FUSION_DMG_LINK="https://download3.vmware.com/software/fusion/file/VMware-Fusion-6.0.4-1887983.dmg"
SILENT_LEVEL=1 # 0 = none, 1 = only downloads, 2 = all requests
DOWNLOADS_DIRECTORY="$HOME/Downloads"
PROVIDER="${1:-virtualbox}"
PROVIDER="${PROVIDER//_/-}"
WORKSPACE="${2:-$HOME/workspace}"
update_uninstaller=1

start ()
{
	if [ "$PROVIDER" != "virtualbox" ] && [ "$PROVIDER" != "vmware-fusion" ]
	then
		error "Invalid provider: $PROVIDER: use virtualbox or vmware-fusion"
		exit
	fi
	success 'Installation Started'
	set_up_workspace
	add_shell_profile_to_bash_profile
	install_vagrant
	if [ "$PROVIDER" == "virtualbox" ] && [ ! -d "/Applications/VirtualBox.app" ]
	then
		install_virtualbox
	elif [ "$PROVIDER" == "vmware-fusion" ] && [ ! -d "/Applications/VMWare Fusion.app" ] && [ ! -d "$HOME/Applications/VMWare Fusion.app" ]
	then
		install_vmware_fusion
	fi
	add_projects
}

# --- ask workspace directory ---------------------------------------------------

set_up_workspace()
{
	# Save hostname, username and timezone
	echo "Reading your system's timezone. Administrator privileges will be required..."
	timezone="$(sudo systemsetup -gettimezone)"
	timezone="${timezone/Time Zone: /}"
	hostname="$(hostname)"

	if [ -f "$WORKSPACE/.system/uninstall.sh" ]
	then
		info "Found uninstaller... Trashing old workspace files..."
		sudo bash "$WORKSPACE/.system/uninstall.sh"
		info "Installing new Workspace..."
		sleep 5
	fi

	if [ -d "$WORKSPACE" ]
	then
		echo "${WORKSPACE/$HOME/~} already exists. Remove or choose another directory."
		exit
	fi

	echo "-- Workspace start --"

	mkdir -p "$WORKSPACE"

	if [ ! -d "$WORKSPACE" ]
	then
		error "No permission to create $WORKSPACE"
		exit
	fi

	# --- download base files ---------------------
	silent_flag=""
	if [ $SILENT_LEVEL -gt 1 ]
	then
		silent_flag="--silent"
	fi
	curl --location $silent_flag --url "$WORKSPACE_REPO" --output "$DOWNLOADS_DIRECTORY/vagrant-workspace.zip"
	unzip "$DOWNLOADS_DIRECTORY/vagrant-workspace.zip" -d "$WORKSPACE"
	rm "$DOWNLOADS_DIRECTORY/vagrant-workspace.zip"
	remove_sub_dir "$WORKSPACE"
	add_to_uninstaller "trash \"$WORKSPACE\""
	cp -r "$WORKSPACE/config-boilerplate" "$WORKSPACE/config"
	rand_mac_addr="00:$(( ( RANDOM % 89 ) + 10 )):00:00:00:01"
	echo -e "{\n\t\"username\": \"$USER\",\n\t\"hostname\": \"${hostname%.*}\",\n\t\"timezone\": \"$timezone\",\n\t\"provider\": \"$PROVIDER\",\n\t\"memory\": 512,\n\t\"cpus\": 1,\n\t\"network\": \"public\",\n\t\"interface\": false,\n\t\"start-mac-addr\": \"$rand_mac_addr\"\n}" > "$WORKSPACE/env.json"

	echo "-- Workspace end --"
}

add_projects ()
{
	echo "-- Projects start --"

	mkdir -p "$WORKSPACE/projects" && success "Added projects directory"

	echo "-- Projects end --"
}

add_to_uninstaller ()
{
	if [ $update_uninstaller ]
	then
		if [ "$1" != "" ]
		then
			addition="$1"
		else
			addition=""
			while read -r line
			do
				addition="$addition$line\n"
			done
		fi
		uninstaller_script="$WORKSPACE/.system/uninstall.sh"
		mkdir -p "$(dirname "$uninstaller_script")"
		if [ ! -f "$uninstaller_script" ]
		then
			echo -e "#!/bin/bash\ntrash() {\n\tif [ -f \"\$1\" ] || [ -d \"\$1\" ]\n\tthen\n\t\tsudo mv -f \"\$1\" \"\$HOME/.Trash/\$(basename \"\$1\")-\$(date +\"%y-%m-%d_%H;%M;%S\").bak\"\n\t\tsleep 2\n\tfi\n}\n" > "$uninstaller_script"
		fi

		uninstaller="$(cat "$uninstaller_script")"
		if [ "${uninstaller//$addition/}" == "$uninstaller" ]
		then
			echo -e "${addition//$HOME/\$HOME}\n" >> "$uninstaller_script"
		fi
	fi
}

add_shell_profile_to_bash_profile ()
{
	# Add coreos alias to bash_profile file
	bash_profile_file="$HOME/.bash_profile"
	start_line="# === Workspace aliases start ==="
	end_line="# === Workspace aliases end ==="
	add_bash_line="$start_line\nexport WORKSPACE=\"${WORKSPACE/$HOME/\$HOME}\"\nalias coreos=\"cd \$WORKSPACE && \$WORKSPACE/coreos\"\nalias workspace=\"cd \$WORKSPACE && \$WORKSPACE/coreos -c workspace\"\n$end_line"
	if [ -f "$bash_profile_file" ]
	then
		bash_profile="$(cat "$bash_profile_file")"
		if [ "${bash_profile/$add_bash_line/}" == "$bash_profile" ]
		then
			add_line=1
		fi
	else
		add_line=1
	fi

	if [ add_line ]
	then
		echo -e "$add_bash_line" >> "$bash_profile_file"

		add_to_uninstaller << EOF
			if [ -f "$bash_profile_file" ]
			then
				echo -e "\\\n" >> $bash_profile_file
				new_bash_profile_file=""
				while read line
				do
					if [ ! \$write_line ] && [ "\$line" != "" ]
					then
						write_line="yes"
					fi

					if [ ! \$write_line ]
					then
						continue
					fi

					if [ "\$line" == "$start_line" ]
					then
						write_line="no"
					fi

					if [ "\$write_line" == "yes" ]
					then
						new_bash_profile_file="\$new_bash_profile_file\$line\\\n"
					fi

					if [ "\$line" == "$end_line" ]
					then
						write_line="yes"
					fi

				done < $bash_profile_file

				if [ ! -n "\$new_bash_profile_file" ]
				then
					if [ -f "$bash_profile_file" ]
					then
						rm "$bash_profile_file"
					fi
				else
					echo -e "\$new_bash_profile_file" > $bash_profile_file
				fi
			fi
EOF
	fi

	source "$bash_profile_file"
}

install_vagrant ()
{
	# -- install Vagrant ------------------------------------------------------------
	application_name="Vagrant"
	command="vagrant"
	download_and_install \
		"$command" \
		"http://www.vagrantup.com/downloads" \
		"vagrant*.dmg" \
		"" \
		"$application_name"

	if [ -d "$HOME/Applications" ]
	then
		command_location="$(which $command)"
		sudo mv -f "/Applications/$application_name" "$HOME/Applications/$application_name"
		ln -sf "$HOME/Applications/$application_name/bin/$command" "$command_location"
		add_to_uninstaller "trash \"$HOME/Applications/$application_name\""
		add_to_uninstaller "trash \"$command_location\""
	fi
}

install_virtualbox ()
{
	# -- install VirtualBox ------------------------------------------------------------
	virtual_box_downloads_link="https://www.virtualbox.org/wiki/Downloads"
	download_and_install \
		"" \
		"$virtual_box_downloads_link" \
		"VirtualBox*-OSX.dmg" \
		"" \
		"VirtualBox.app"

	download_and_install \
		"" \
		"$virtual_box_downloads_link" \
		"Oracle_VM_VirtualBox_Extension_Pack-*.vbox-extpack" \
		"" \
		"VirtualBox Extension Pack"

	add_to_uninstaller "trash \"$HOME/Library/VirtualBox\""
	add_to_uninstaller "trash \"$HOME/Library/Application Support/VirtualBox\""
	add_to_uninstaller "trash \"/Library/Python/2.6/site-packages/vboxapi\""
	add_to_uninstaller "trash \"/Library/Python/2.6/site-packages/vboxapi-1.0-py2.6.egg-info\""
	add_to_uninstaller "trash \"/Library/Python/2.7/site-packages/vboxapi\""
	add_to_uninstaller "trash \"/Library/Python/2.7/site-packages/vboxapi-1.0-py2.7.egg-info\""
}

install_vmware_fusion ()
{
	# -- install VMWare Fusion ------------------------------------------------------------
	dest="$DOWNLOADS_DIRECTORY/$(basename $VMWARE_FUSION_DMG_LINK)"
	application_name="VMware Fusion.app"
	echo "-- $application_name start --"

	if [ ! -f "$dest" ]
	then
		download \
			"$VMWARE_FUSION_DMG_LINK" \
			"$dest" \
			"$application_name"
	fi
	install \
		"" \
		"$dest" \
		"$application_name"

	if [ -d "$HOME/Applications" ]
	then
		sudo mv -f "/Applications/$application_name" "$HOME/Applications/$application_name"
		add_to_uninstaller "trash \"$HOME/Applications/$application_name\""
	fi

	add_to_uninstaller "trash \"$HOME/Library/Preferences/VMWare Fusion\""
	add_to_uninstaller "trash \"$HOME/Library/Caches/com.vmware.fusion\""
	add_to_uninstaller "trash \"$HOME/Library/Preferences/com.vmware.fusionStartMenu.plist\""
	add_to_uninstaller "trash \"$HOME/Library/Preferences/com.vmware.fusion.LSSharedFileList.plist\""
	add_to_uninstaller "trash \"$HOME/Library/Application Support/VMWare Fusion\""
	add_to_uninstaller "trash \"$HOME/Library/Preferences/com.vmware.fusion.plist\""
	add_to_uninstaller "trash \"$HOME/Library/Logs/VMWare Fusion\""

	echo "-- $application_name end --"
	# TODO: fix HGFS issue: echo "answer AUTO_KMODS_ENABLED yes" | sudo tee -a /etc/vmware-tools/locations
}

black="\e[0;30m"
red="\e[0;31m"
green="\e[0;32m"
orange="\e[0;33m"
blue="\e[0;34m"
purple="\e[0;35m"
turquase="\e[0;36m"
NC="\e[0m"

info ()
{
	printf "$blue"
	echo "$1"
	printf "$NC"
}

success ()
{
	printf "$green"
	echo "$1"
	printf "$NC"
}

error ()
{
	printf "$red"
	echo "$1"
	printf "$NC"
}

# === Download and install scripts: ================================

download_and_install ()
{
	command="$1"
	downloads_link="$2"
	download_link_base_pattern="$3"
	specific_version="$4"
	application_name="$5"

	function version()
	{
		version="$($1 --version | sed -n 1p)"
		if [ "$version" == "" ]
		then
			version="$($1 version | sed -n 1p)"
		fi
		capital=$(echo $1 | head -c 1 | tr [a-z] [A-Z]; echo $1 | tail -c +2)
		version="${version/$capital/}"
		version="${version/$1/}"
		version="${version/v/}"
		version="${version/V/}"
		version="${version/version/}"
		version="${version/Version/}"
		version="${version/ /}"
		echo "$version"
	}

	if [ "$downloads_link" == "" ]
	then
		echo "Missing second argument: downloads link"
		exiting="yes"
	fi

	if [ "$download_link_base_pattern" == "" ]
	then
		echo "Missing third argument: download link pattern"
		exiting="yes"
	fi

	if [ "$exiting" == "yes" ]
	then
		exit
	fi

	if [ "$application_name" == "" ] && [ "$command" != "" ]
	then
		application_name=$(echo $command | head -c 1 | tr [a-z] [A-Z]; echo $1 | tail -c +2)
	fi

	echo "-- $application_name start --"

	install=""
	if [ "$command" != "" ]
	then
		if [ "$(which $command)" == "" ]
		then
			echo "$application_name not installed"
			install="yes"
		else
			current_version="$(version $command)"
			echo "Current $application_name version: $current_version"
		fi
	fi

	echo "Fetching downloads page: $downloads_link..."
	download_link="$(find_download_link "$downloads_link" "$download_link_base_pattern")"
	if [ "$download_link" == "" ]
	then
		error "No download link found on $downloads_link"
	else
		if [ "$latest_version" != "" ]
		then
			info "Latest $application_name version: $latest_version ($downloads_link)"

			download_version="$latest_version"

			if [ "$specific_version" != "" ]
			then
				download_version="$specific_version"
				download_link="${download_link//$latest_version/$download_version}"
				info "Forcing $application_name version: $specific_version";
			fi

			if [ "$current_version" != "$download_version" ]
			then
				install="yes"
			fi
		else
			install="yes"
		fi

		if [ "$install" == "yes" ]
		then
			if [ "${download_link:0:1}" == "/" ] && [ "${download_link:0:2}" != "//" ]
			then
				domain_name=$(echo $downloads_link | cut -d'/' -f3)
				download_link="$domain_name$download_link"
			fi
			dest="$DOWNLOADS_DIRECTORY/$(basename $download_link)"
			sudo mkdir -p $(dirname $DOWNLOADS_DIRECTORY)
			if [ ! -f "$dest" ]
			then
				download \
					"$download_link" \
					"$dest" \
					"$application_name"
			fi
			install \
				"$command" \
				"$dest" \
				"$application_name"
		elif [ "$current_version" != "" ]
		then
			success "$application_name already on latest version: $current_version"
		else
			success "$application_name already installed"
		fi
		info "Download link: $download_link"

	fi

	echo "-- $application_name end --"
}

download()
{
	download_link="$1"
	dest="$2"
	application_name="$3"

	minus_one="-1"
	if [ "${dest:$minus_one:1}" == "/" ]
	then
		dest="$dest$(basename $download_link)"
	fi

	if [ -f "$dest" ]
	then
		rm -rf "$dest"
	fi

	info "Downloading latest $application_name $download_link..."
	silent_flag=""
	if [ $SILENT_LEVEL -gt 0 ]
	then
		silent_flag="--silent"
	fi
	curl --location $silent_flag --output "$dest" --url "$download_link"
}

install()
{
	command="$1"
	package="$2"
	application_name="$3"

	filename=$(basename "$package")
	extension="${filename##*.}"

	volume_name="$application_name"
	volume_name="${volume_name%.*}"
	volume_name="${volume_name// /-}"
	volume_name="$(echo $volume_name | awk '{print tolower($0)}')"
	extraction_path="$HOME/${filename%.*}-extraction"
	mkdir -p "$extraction_path"
	usr="/usr/local"
	sudo mkdir -p "$usr"

	case "$extension" in
		dmg)
			volume_path="/Volumes/$volume_name"
			hdiutil attach -mountpoint "$volume_path" "$package"
			osascript -e 'tell application "Finder"' -e 'close front window' -e 'end tell'
			echo "Please wait a sec..."
			sudo cp -rf $volume_path/* $extraction_path/
			hdiutil detach "$volume_path"
			;;
		zip)
			if [ "$(which apt-get)" != "" ]
	    	then
	    		apt-get install unzip
			fi

			unzip -o "$package" -d "$extraction_path"
			;;
		gz|bz2)
			if [ -d "$extraction_path" ]
			then
				rm -rf "$extraction_path"
			fi
			case "$extension" in
				gz)
					method="z"
					;;
				bz2)
					method="b"
					;;
			esac
			tar "xfv$method" "$package" --directory "$extraction_path"
			remove_sub_dir "$extraction_path"
			;;
		vbox-extpack)
			cp -f "$package" "$WORKSPACE/.system/$(basename "$package")"
			;;
		?)
			error "Unable to install $extension-files"
			exit
			;;
	esac

	application_path="Applications"
	dest_application_path="/$application_path"
	app_path=""
	pkg="$(ls $extraction_path | grep .pkg | head -1)"
	app="$(ls $extraction_path | grep .app | head -1)"
	if [ "$pkg" != "" ]
	then
		sudo installer -verboseR -pkg "$extraction_path/$pkg" -target /
		app_path="$dest_application_path/$application_name"
	elif [ "$app" != "" ]
	then
		app_path="$extraction_path/$app"
	fi

	# -- Move to home Applications directory if there is one ------------------------
	if [ "$app_path" != "" ] && [ -d "$app_path" ]
	then
		dest_app_path="$dest_application_path/$(basename "$app_path")"
		if [ "$app_path" != "$dest_app_path" ]
		then
			sudo mv -f "$app_path" "$dest_app_path"
		fi

		success "$application_name installed."
		add_to_uninstaller "trash \"$dest_app_path\""
	fi

	if [ "$command" != "" ]
	then
		if [ -d "$extraction_path/bin" ]
		then
			sudo mv -f "$extraction_path" "$usr/$command"
			export PATH="$PATH:$usr/$command/bin"
		else
			sudo mkdir -p "$usr/bin"
			sudo mv $extraction_path/* "$usr/bin/"
		fi

		if [ "$(which $command)" != "" ]
		then
			success "$application_name $(version $command)"
		else
			error "Something went wrong installing $application_name"
		fi
	fi

	if [ -d "$extraction_path" ]
	then
		sudo rm -rf "$extraction_path"
	fi
}

find_download_link()
{
	downloads_link="$1"
	download_link_base_pattern="$2"
	download_link_base_front=""
	download_link_base_rear=""
	latest_version=""

	IFS='*' read -ra str <<< "$download_link_base_pattern"
	for i in "${str[@]}"
	do
	    if [ "$download_link_base_front" == "" ]
	    then
	    	download_link_base_front="$i"
	    elif [ "$download_link_base_rear" == "" ]
	    then
	    	download_link_base_rear="$i"
	    fi
	done
	silent_flag=""
	silent_flag=""
	if [ $SILENT_LEVEL -gt 1 ]
	then
		silent_flag="--silent"
	fi

	# Find download link
	find_download_link_html=$(curl --location $silent_flag --url "$downloads_link")
	find_download_link_html="${find_download_link_html//href=\"/ }"
	find_download_link_html="${find_download_link_html//$download_link_base_rear/$download_link_base_rear }"
	for s in $find_download_link_html
	do
		if [ "${s%$download_link_base_rear}" != "$s" ]
		then
			file_name="$(basename $s)"
			latest_version="${file_name/${download_link_base_front}_/}"
			latest_version="${latest_version/${download_link_base_front}-/}"
			latest_version="${latest_version/${download_link_base_front}/}"
			latest_version="${latest_version/_${download_link_base_rear}/}"
			latest_version="${latest_version/-${download_link_base_rear}/}"
			latest_version="${latest_version/${download_link_base_rear}/}"
			if [ "$latest_version" == "master" ]
			then
				continue
			fi
			echo "$s"
			return
		fi
	done
}

# Removes a directory which is in between two directories: /home/subdir/directory becomes /home/directory
remove_sub_dir ()
{
	if [ ! -d "$1" ]
	then
		error "$1 is not a directory"
		exit
	fi
	count=$(ls -1A "$1" | wc -l)
	if [ $count -eq 1 ]
	then
		remove_sub_dir_dir="$1/$(ls "$1")"
		if [ ! -d "$remove_sub_dir_dir" ]
		then
			echo "$remove_sub_dir_dir is not a directory"
			exit
		fi
		ls -1A "$remove_sub_dir_dir" | while read -r file
		do
		    mv "$remove_sub_dir_dir/$file" "$remove_sub_dir_dir/../"
		done
		rmdir "$remove_sub_dir_dir"
	else
		echo "$count items in $1"
		exit
	fi
}

start

#!/bin/bash

#WORKSPACE_REPO="https://github.com/crobays/workspace/archive/master.zip"
WORKSPACE_REPO="http://gitlab.userx.nl/crobays/workspace/repository/archive.zip?ref=master"
VMWARE_FUSION_DMG_LINK="https://download3.vmware.com/software/fusion/file/VMware-Fusion-6.0.4-1887983.dmg"
SILENT_LEVEL=1 # 0 = none, 1 = only downloads, 2 = all requests
DOWNLOADS_DIRECTORY="$HOME/Downloads"
PROVIDER="${1:-virtualbox}"
PROVIDER="${PROVIDER//_/-}"
WORKSPACE="${2:-$HOME/workspace}"
update_uninstaller=1

start ()
{
	if [ "$PROVIDER" != "virtualbox" ] && [ "$PROVIDER" != "vmware-fusion" ]
	then
		error "Invalid provider: $PROVIDER: use virtualbox or vmware-fusion"
		exit
	fi
	success 'Installation Started'
	set_up_workspace
	add_shell_profile_to_bash_profile
	install_vagrant
	if [ "$PROVIDER" == "virtualbox" ] && [ ! -d "/Applications/VirtualBox.app" ]
	then
		install_virtualbox
	elif [ "$PROVIDER" == "vmware-fusion" ] && [ ! -d "/Applications/VMWare Fusion.app" ] && [ ! -d "$HOME/Applications/VMWare Fusion.app" ]
	then
		install_vmware_fusion
	fi
	add_projects
}

# --- ask workspace directory ---------------------------------------------------

set_up_workspace()
{
	# Save hostname, username and timezone
	echo "Reading your system's timezone. Administrator privileges will be required..."
	timezone="$(sudo systemsetup -gettimezone)"
	timezone="${timezone/Time Zone: /}"
	hostname="$(hostname)"

	if [ -f "$WORKSPACE/.system/uninstall.sh" ]
	then
		info "Found uninstaller... Trashing old workspace files..."
		sudo bash "$WORKSPACE/.system/uninstall.sh"
		info "Installing new Workspace..."
		sleep 5
	fi

	if [ -d "$WORKSPACE" ]
	then
		echo "${WORKSPACE/$HOME/~} already exists. Remove or choose another directory."
		exit
	fi

	echo "-- Workspace start --"

	mkdir -p "$WORKSPACE"

	if [ ! -d "$WORKSPACE" ]
	then
		error "No permission to create $WORKSPACE"
		exit
	fi

	# --- download base files ---------------------
	silent_flag=""
	if [ $SILENT_LEVEL -gt 1 ]
	then
		silent_flag="--silent"
	fi
	curl --location $silent_flag --url "$WORKSPACE_REPO" --output "$DOWNLOADS_DIRECTORY/vagrant-workspace.zip"
	unzip "$DOWNLOADS_DIRECTORY/vagrant-workspace.zip" -d "$WORKSPACE"
	rm "$DOWNLOADS_DIRECTORY/vagrant-workspace.zip"
	remove_sub_dir "$WORKSPACE"
	add_to_uninstaller "trash \"$WORKSPACE\""
	cp -r "$WORKSPACE/config-boilerplate" "$WORKSPACE/config"
	rand_mac_addr="00:$(( ( RANDOM % 89 ) + 10 )):00:00:00:01"
	echo -e "{\n\t\"username\": \"$USER\",\n\t\"hostname\": \"${hostname%.*}\",\n\t\"timezone\": \"$timezone\",\n\t\"provider\": \"$PROVIDER\",\n\t\"memory\": 512,\n\t\"cpus\": 1,\n\t\"network\": \"public\",\n\t\"interface\": false,\n\t\"start-mac-addr\": \"$rand_mac_addr\"\n}" > "$WORKSPACE/env.json"

	echo "-- Workspace end --"
}

add_projects ()
{
	echo "-- Projects start --"

	mkdir -p "$WORKSPACE/projects" && success "Added projects directory"

	echo "-- Projects end --"
}

add_to_uninstaller ()
{
	if [ $update_uninstaller ]
	then
		if [ "$1" != "" ]
		then
			addition="$1"
		else
			addition=""
			while read -r line
			do
				addition="$addition$line\n"
			done
		fi
		uninstaller_script="$WORKSPACE/.system/uninstall.sh"
		mkdir -p "$(dirname "$uninstaller_script")"
		if [ ! -f "$uninstaller_script" ]
		then
			echo -e "#!/bin/bash\ntrash() {\n\tif [ -f \"\$1\" ] || [ -d \"\$1\" ]\n\tthen\n\t\tsudo mv -f \"\$1\" \"\$HOME/.Trash/\$(basename \"\$1\")-\$(date +\"%y-%m-%d_%H;%M;%S\").bak\"\n\t\tsleep 2\n\tfi\n}\n" > "$uninstaller_script"
		fi

		uninstaller="$(cat "$uninstaller_script")"
		if [ "${uninstaller//$addition/}" == "$uninstaller" ]
		then
			echo -e "${addition//$HOME/\$HOME}\n" >> "$uninstaller_script"
		fi
	fi
}

add_shell_profile_to_bash_profile ()
{
	# Add coreos alias to bash_profile file
	bash_profile_file="$HOME/.bash_profile"
	start_line="# === Workspace aliases start ==="
	end_line="# === Workspace aliases end ==="
	add_bash_line="$start_line\nexport WORKSPACE=\"${WORKSPACE/$HOME/\$HOME}\"\nalias coreos=\"cd \$WORKSPACE && \$WORKSPACE/coreos\"\nalias workspace=\"cd \$WORKSPACE && \$WORKSPACE/coreos -c workspace\"\n$end_line"
	if [ -f "$bash_profile_file" ]
	then
		bash_profile="$(cat "$bash_profile_file")"
		if [ "${bash_profile/$add_bash_line/}" == "$bash_profile" ]
		then
			add_line=1
		fi
	else
		add_line=1
	fi

	if [ add_line ]
	then
		echo -e "$add_bash_line" >> "$bash_profile_file"

		add_to_uninstaller << EOF
			if [ -f "$bash_profile_file" ]
			then
				echo -e "\\\n" >> $bash_profile_file
				new_bash_profile_file=""
				while read line
				do
					if [ ! \$write_line ] && [ "\$line" != "" ]
					then
						write_line="yes"
					fi

					if [ ! \$write_line ]
					then
						continue
					fi

					if [ "\$line" == "$start_line" ]
					then
						write_line="no"
					fi

					if [ "\$write_line" == "yes" ]
					then
						new_bash_profile_file="\$new_bash_profile_file\$line\\\n"
					fi

					if [ "\$line" == "$end_line" ]
					then
						write_line="yes"
					fi

				done < $bash_profile_file

				if [ ! -n "\$new_bash_profile_file" ]
				then
					if [ -f "$bash_profile_file" ]
					then
						rm "$bash_profile_file"
					fi
				else
					echo -e "\$new_bash_profile_file" > $bash_profile_file
				fi
			fi
EOF
	fi

	source "$bash_profile_file"
}

install_vagrant ()
{
	# -- install Vagrant ------------------------------------------------------------
	application_name="Vagrant"
	command="vagrant"
	download_and_install \
		"$command" \
		"http://www.vagrantup.com/downloads" \
		"vagrant*.dmg" \
		"" \
		"$application_name"

	if [ -d "$HOME/Applications" ]
	then
		command_location="$(which $command)"
		sudo mv -f "/Applications/$application_name" "$HOME/Applications/$application_name"
		ln -sf "$HOME/Applications/$application_name/bin/$command" "$command_location"
		add_to_uninstaller "trash \"$HOME/Applications/$application_name\""
		add_to_uninstaller "trash \"$command_location\""
	fi
}

install_virtualbox ()
{
	# -- install VirtualBox ------------------------------------------------------------
	virtual_box_downloads_link="https://www.virtualbox.org/wiki/Downloads"
	download_and_install \
		"" \
		"$virtual_box_downloads_link" \
		"VirtualBox*-OSX.dmg" \
		"" \
		"VirtualBox.app"

	download_and_install \
		"" \
		"$virtual_box_downloads_link" \
		"Oracle_VM_VirtualBox_Extension_Pack-*.vbox-extpack" \
		"" \
		"VirtualBox Extension Pack"

	add_to_uninstaller "trash $HOME/Library/Preferences/VirtualBox"

}

install_vmware_fusion ()
{
	# -- install VMWare Fusion ------------------------------------------------------------
	dest="$DOWNLOADS_DIRECTORY/$(basename $VMWARE_FUSION_DMG_LINK)"
	application_name="VMware Fusion.app"
	echo "-- $application_name start --"

	if [ ! -f "$dest" ]
	then
		download \
			"$VMWARE_FUSION_DMG_LINK" \
			"$dest" \
			"$application_name"
	fi
	install \
		"" \
		"$dest" \
		"$application_name"

	if [ -d "$HOME/Applications" ]
	then
		sudo mv -f "/Applications/$application_name" "$HOME/Applications/$application_name"
		add_to_uninstaller "trash \"$HOME/Applications/$application_name\""
	fi

	add_to_uninstaller "trash \"$HOME/Library/Preferences/VMWare Fusion\""
	add_to_uninstaller "trash \"$HOME/Library/Caches/com.vmware.fusion\""
	add_to_uninstaller "trash \"$HOME/Library/Preferences/com.vmware.fusionStartMenu.plist\""
	add_to_uninstaller "trash \"$HOME/Library/Preferences/com.vmware.fusion.LSSharedFileList.plist\""
	add_to_uninstaller "trash \"$HOME/Library/Application Support/VMWare Fusion\""
	add_to_uninstaller "trash \"$HOME/Library/Preferences/com.vmware.fusion.plist\""
	add_to_uninstaller "trash \"$HOME/Library/Logs/VMWare Fusion\""

	echo "-- $application_name end --"
	# TODO: fix HGFS issue: echo "answer AUTO_KMODS_ENABLED yes" | sudo tee -a /etc/vmware-tools/locations
}

black="\e[0;30m"
red="\e[0;31m"
green="\e[0;32m"
orange="\e[0;33m"
blue="\e[0;34m"
purple="\e[0;35m"
turquase="\e[0;36m"
NC="\e[0m"

info ()
{
	printf "$blue"
	echo "$1"
	printf "$NC"
}

success ()
{
	printf "$green"
	echo "$1"
	printf "$NC"
}

error ()
{
	printf "$red"
	echo "$1"
	printf "$NC"
}

# === Download and install scripts: ================================

download_and_install ()
{
	command="$1"
	downloads_link="$2"
	download_link_base_pattern="$3"
	specific_version="$4"
	application_name="$5"

	function version()
	{
		version="$($1 --version | sed -n 1p)"
		if [ "$version" == "" ]
		then
			version="$($1 version | sed -n 1p)"
		fi
		capital=$(echo $1 | head -c 1 | tr [a-z] [A-Z]; echo $1 | tail -c +2)
		version="${version/$capital/}"
		version="${version/$1/}"
		version="${version/v/}"
		version="${version/V/}"
		version="${version/version/}"
		version="${version/Version/}"
		version="${version/ /}"
		echo "$version"
	}

	if [ "$downloads_link" == "" ]
	then
		echo "Missing second argument: downloads link"
		exiting="yes"
	fi

	if [ "$download_link_base_pattern" == "" ]
	then
		echo "Missing third argument: download link pattern"
		exiting="yes"
	fi

	if [ "$exiting" == "yes" ]
	then
		exit
	fi

	if [ "$application_name" == "" ] && [ "$command" != "" ]
	then
		application_name=$(echo $command | head -c 1 | tr [a-z] [A-Z]; echo $1 | tail -c +2)
	fi

	echo "-- $application_name start --"

	install=""
	if [ "$command" != "" ]
	then
		if [ "$(which $command)" == "" ]
		then
			echo "$application_name not installed"
			install="yes"
		else
			current_version="$(version $command)"
			echo "Current $application_name version: $current_version"
		fi
	fi

	echo "Fetching downloads page: $downloads_link..."
	download_link="$(find_download_link "$downloads_link" "$download_link_base_pattern")"
	if [ "$download_link" == "" ]
	then
		error "No download link found on $downloads_link"
	else
		if [ "$latest_version" != "" ]
		then
			info "Latest $application_name version: $latest_version ($downloads_link)"

			download_version="$latest_version"

			if [ "$specific_version" != "" ]
			then
				download_version="$specific_version"
				download_link="${download_link//$latest_version/$download_version}"
				info "Forcing $application_name version: $specific_version";
			fi

			if [ "$current_version" != "$download_version" ]
			then
				install="yes"
			fi
		else
			install="yes"
		fi

		if [ "$install" == "yes" ]
		then
			if [ "${download_link:0:1}" == "/" ] && [ "${download_link:0:2}" != "//" ]
			then
				domain_name=$(echo $downloads_link | cut -d'/' -f3)
				download_link="$domain_name$download_link"
			fi
			dest="$DOWNLOADS_DIRECTORY/$(basename $download_link)"
			sudo mkdir -p $(dirname $DOWNLOADS_DIRECTORY)
			if [ ! -f "$dest" ]
			then
				download \
					"$download_link" \
					"$dest" \
					"$application_name"
			fi
			install \
				"$command" \
				"$dest" \
				"$application_name"
		elif [ "$current_version" != "" ]
		then
			success "$application_name already on latest version: $current_version"
		else
			success "$application_name already installed"
		fi
		info "Download link: $download_link"

	fi

	echo "-- $application_name end --"
}

download()
{
	download_link="$1"
	dest="$2"
	application_name="$3"

	minus_one="-1"
	if [ "${dest:$minus_one:1}" == "/" ]
	then
		dest="$dest$(basename $download_link)"
	fi

	if [ -f "$dest" ]
	then
		rm -rf "$dest"
	fi

	info "Downloading latest $application_name $download_link..."
	silent_flag=""
	if [ $SILENT_LEVEL -gt 0 ]
	then
		silent_flag="--silent"
	fi
	curl --location $silent_flag --output "$dest" --url "$download_link"
}

install()
{
	command="$1"
	package="$2"
	application_name="$3"

	filename=$(basename "$package")
	extension="${filename##*.}"

	volume_name="$application_name"
	volume_name="${volume_name%.*}"
	volume_name="${volume_name// /-}"
	volume_name="$(echo $volume_name | awk '{print tolower($0)}')"
	extraction_path="$HOME/${filename%.*}-extraction"
	mkdir -p "$extraction_path"
	usr="/usr/local"
	sudo mkdir -p "$usr"

	case "$extension" in
		dmg)
			volume_path="/Volumes/$volume_name"
			hdiutil attach -mountpoint "$volume_path" "$package"
			osascript -e 'tell application "Finder"' -e 'close front window' -e 'end tell'
			echo "Please wait a sec..."
			sudo cp -rf $volume_path/* $extraction_path/
			hdiutil detach "$volume_path"
			;;
		zip)
			if [ "$(which apt-get)" != "" ]
	    	then
	    		apt-get install unzip
			fi

			unzip -o "$package" -d "$extraction_path"
			;;
		gz|bz2)
			if [ -d "$extraction_path" ]
			then
				rm -rf "$extraction_path"
			fi
			case "$extension" in
				gz)
					method="z"
					;;
				bz2)
					method="b"
					;;
			esac
			tar "xfv$method" "$package" --directory "$extraction_path"
			remove_sub_dir "$extraction_path"
			;;
		vbox-extpack)
			cp -f "$package" "$WORKSPACE/.system/$(basename "$package")"
			;;
		?)
			error "Unable to install $extension-files"
			exit
			;;
	esac

	application_path="Applications"
	dest_application_path="/$application_path"
	app_path=""
	pkg="$(ls $extraction_path | grep .pkg | head -1)"
	app="$(ls $extraction_path | grep .app | head -1)"
	if [ "$pkg" != "" ]
	then
		sudo installer -verboseR -pkg "$extraction_path/$pkg" -target /
		app_path="$dest_application_path/$application_name"
	elif [ "$app" != "" ]
	then
		app_path="$extraction_path/$app"
	fi

	# -- Move to home Applications directory if there is one ------------------------
	if [ "$app_path" != "" ] && [ -d "$app_path" ]
	then
		dest_app_path="$dest_application_path/$(basename "$app_path")"
		if [ "$app_path" != "$dest_app_path" ]
		then
			sudo mv -f "$app_path" "$dest_app_path"
		fi

		success "$application_name installed."
		add_to_uninstaller "trash \"$dest_app_path\""
	fi

	if [ "$command" != "" ]
	then
		if [ -d "$extraction_path/bin" ]
		then
			sudo mv -f "$extraction_path" "$usr/$command"
			export PATH="$PATH:$usr/$command/bin"
		else
			sudo mkdir -p "$usr/bin"
			sudo mv $extraction_path/* "$usr/bin/"
		fi

		if [ "$(which $command)" != "" ]
		then
			success "$application_name $(version $command)"
		else
			error "Something went wrong installing $application_name"
		fi
	fi

	if [ -d "$extraction_path" ]
	then
		sudo rm -rf "$extraction_path"
	fi
}

find_download_link()
{
	downloads_link="$1"
	download_link_base_pattern="$2"
	download_link_base_front=""
	download_link_base_rear=""
	latest_version=""

	IFS='*' read -ra str <<< "$download_link_base_pattern"
	for i in "${str[@]}"
	do
	    if [ "$download_link_base_front" == "" ]
	    then
	    	download_link_base_front="$i"
	    elif [ "$download_link_base_rear" == "" ]
	    then
	    	download_link_base_rear="$i"
	    fi
	done
	silent_flag=""
	silent_flag=""
	if [ $SILENT_LEVEL -gt 1 ]
	then
		silent_flag="--silent"
	fi

	# Find download link
	find_download_link_html=$(curl --location $silent_flag --url "$downloads_link")
	find_download_link_html="${find_download_link_html//href=\"/ }"
	find_download_link_html="${find_download_link_html//$download_link_base_rear/$download_link_base_rear }"
	for s in $find_download_link_html
	do
		if [ "${s%$download_link_base_rear}" != "$s" ]
		then
			file_name="$(basename $s)"
			latest_version="${file_name/${download_link_base_front}_/}"
			latest_version="${latest_version/${download_link_base_front}-/}"
			latest_version="${latest_version/${download_link_base_front}/}"
			latest_version="${latest_version/_${download_link_base_rear}/}"
			latest_version="${latest_version/-${download_link_base_rear}/}"
			latest_version="${latest_version/${download_link_base_rear}/}"
			if [ "$latest_version" == "master" ]
			then
				continue
			fi
			echo "$s"
			return
		fi
	done
}

# Removes a directory which is in between two directories: /home/subdir/directory becomes /home/directory
remove_sub_dir ()
{
	if [ ! -d "$1" ]
	then
		error "$1 is not a directory"
		exit
	fi
	count=$(ls -1A "$1" | wc -l)
	if [ $count -eq 1 ]
	then
		remove_sub_dir_dir="$1/$(ls "$1")"
		if [ ! -d "$remove_sub_dir_dir" ]
		then
			echo "$remove_sub_dir_dir is not a directory"
			exit
		fi
		ls -1A "$remove_sub_dir_dir" | while read -r file
		do
		    mv "$remove_sub_dir_dir/$file" "$remove_sub_dir_dir/../"
		done
		rmdir "$remove_sub_dir_dir"
	else
		echo "$count items in $1"
		exit
	fi
}

start


add get_geo script

add get_geo script

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/kidaa/crystal-1.git/'


send all rubinius compilation to /tmp

send all rubinius compilation to /tmp

error: pathspec 'rbx/options.zsh' did not match any file(s) known to git


added rvm config

added rvm config

[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*

error: pathspec 'ruby/rvm.zsh' did not match any file(s) known to git


Update publish script to public CocoaPods

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/SRGSSR/SRGMediaPlayer-iOS.git/'


resume changed

resume changed

git add .
git commit -m "resume changed"
git push origin master

error: pathspec 'push_resume.sh' did not match any file(s) known to git


Initial commit. Added experimental shell script.

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/NateTheGreat68/snapmerge.git/'


Added shell prompt config created by vim promptline plugin

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/technicalbradah/.dotfiles.git/'


fix: typo

fix: typo

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/kLm8/scripts.git/'


add utility for reformat ddf file

add utility for reformat ddf file

#!/bin/bash

display_usage() {
  echo
  echo "Usage: $0"
  echo
  echo " <DDF file>    File of DDF table (semicolon separated and w/o header)"
  echo
}

argument="$1"

if [[ -z $argument ]] ; then
  raise_error "Expected argument to be present"
  display_usage
else
  sed 's/;/\t/g' $argument | awk '{print $1 "\t" $2}'
fi

error: pathspec 'reformat_ddf.sh' did not match any file(s) known to git


Add rails aliases for testing

Add rails aliases for testing

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/benhanzl/dotfiles.git/'


Tweaks for 0RTT testing

Tweaks for 0RTT testing

#! /usr/bin/env bash

rm -f /cores/*.core

set -e

# by default, test quant
c=${1:-quant}
s=${2:-quant}

# port to run servers on
addr=127.0.0.1
port=4433 # mozquic server can only run on 4433 at the moment
path=/index.html
dir=/Users/lars/Sites/lars/output
cert=/etc/letsencrypt/live/slate.eggert.org/fullchain.pem
key=/etc/letsencrypt/live/slate.eggert.org/privkey.pem

# (re-)build the client (and possibly server) to test
if [ "$c" == wcquant ] || [ "$s" == wcquant ] ||
   [ "$c" == wsquant ] || [ "$s" == wsquant ]; then
        delay=0.1
        vagrant ssh -c "\
                mkdir -p /vagrant/Linux; \
                cd /vagrant/Linux; \
                cmake -GNinja .. && ninja"
else
        delay=0.1
        ninja "$c"
        [ "$c" != "$s" ] && ninja "$s"
fi

set +e

export ASAN_OPTIONS=strict_string_checks=1:strict_init_order=1:detect_stack_use_after_return=1:detect_leaks=1:check_initialization_order=1:sleep_before_dying=30:alloc_dealloc_mismatch=1:detect_invalid_pointer_pairs=1
# export UBSAN_OPTIONS=suppressions=../misc/ubsan.supp:print_stacktrace=1

# commands to run the different clients against $addr:$port
case $c in
        quant)
                cc="bin/client -v5 https://$addr:$port$path" # https://$addr:$port$path"
                ;;
        wsquant)
                cc="bin/client -i vboxnet3 -v5 https://172.28.128.3:$port$path"
                ;;
        wcquant)
                cc="vagrant ssh -c \"\
                        /vagrant/Linux/bin/client -i enp0s8 -v5 \
                                https://172.28.128.1:$port$path\""
                ;;
        quicly)
                cc="external/quicly-prefix/src/quicly-build/cli \
                        -l /tmp/quicly-c.log -s /tmp/quicly-session -v \
                        -p $path $addr $port"
                ;;
        minq)
                cc="env MINQ_LOG=aead,connection,ack,handshake,tls,server,udp \
                        GOPATH=$(pwd)/external/go go run \
                        external/go/src/github.com/ekr/minq/bin/client/main.go \
                        -addr $addr:$port -http $path"
                ;;
        ngtcp2)
                touch /tmp/ngtcp2-session /tmp/ngtcp2-tp
                cc="echo GET $path > /tmp/ngtcp2-req | \
                        external/ngtcp2-prefix/src/ngtcp2/examples/client \
                        -d /tmp/ngtcp2-req $addr $port --session-file=/tmp/ngtcp2-session \
                        --tp-file=/tmp/ngtcp2-tp"
                ;;
        mozquic)
                cc="env MOZQUIC_LOG=all:9 \
                        MOZQUIC_NSS_CONFIG=external/mozquic-prefix/src/mozquic/sample/nss-config \
                        DYLD_LIBRARY_PATH=external/mozquic-prefix/src/dist/$(cat external/mozquic-prefix/src/dist/latest)/lib \
                        external/mozquic-prefix/src/mozquic/client \
                                -peer $addr:$port -get $path \
                                -ignorePKI -send-close"
                ;;
        picoquic)
                cc="external/picoquic-prefix/src/picoquic/picoquicdemo \
                        $addr $port -1"
                ;;
esac

# commands to run the different servers on  $addr:$port
case $s in
        quant)
                sc="bin/server -v5 -p $port -d $dir"
                ;;
        wsquant)
                sc="vagrant ssh -c \"\
                        /vagrant/Linux/bin/server -i enp0s8 -v5 -p $port \
                                -c ~/slate.eggert.org/fullchain.pem \
                                -k ~/slate.eggert.org/privkey.pem \
                                -d /usr/share/apache2/default-site\""
                ;;
        wcquant)
                sc="bin/server -v5 -i vboxnet3 -p $port -d $dir"
                ;;
        quicly)
                sc="external/quicly-prefix/src/quicly-build/cli \
                        -l /tmp/quicly-s.log -v \
                        -k $key -c $cert $addr $port"
                ;;
        minq)
                sc="env MINQ_LOG=aead,connection,ack,handshake,tls,server,udp \
                        GOPATH=$(pwd)/external/go go run \
                        external/go/src/github.com/ekr/minq/bin/server/main.go \
                        -addr $addr:$port -http -key $key -stateless-reset \
                        -cert $cert -server-name $addr"
                ;;
        ngtcp2)
                sc="external/ngtcp2-prefix/src/ngtcp2/examples/server \
                        -d $dir $addr $port $key $cert"
                ;;
        mozquic)
                sc="env MOZQUIC_LOG=all:9 \
                        MOZQUIC_NSS_CONFIG=external/mozquic-prefix/src/mozquic/sample/nss-config \
                        DYLD_LIBRARY_PATH=external/mozquic-prefix/src/dist/$(cat external/mozquic-prefix/src/dist/latest)/lib \
                        external/mozquic-prefix/src/mozquic/server \
                        -ignorePKI -send-close -0rtt"
                ;;
        picoquic)
                sc="external/picoquic-prefix/src/picoquic/picoquicdemo \
                        -p $port -k $key -c $cert -1"
                ;;
        ats)
                sed -i"" -e "s/.*proxy.config.http.server_ports.*/CONFIG proxy.config.http.server_ports STRING $port:quic/g" external/etc/trafficserver/records.config
                echo "dest_ip=* ssl_cert_name=$cert ssl_key_name=$key" > external/etc/trafficserver/ssl_multicert.config
                echo "map / http://127.0.0.1:8000/" > external/etc/trafficserver/remap.config
                sc="external/bin/traffic_server"
                ;;
esac

# # if we are on MacOS X, configure the firewall to add delay and loss
# if [ -x /usr/sbin/dnctl ]; then
#         # create pipes to limit bandwidth and add loss
#         sudo dnctl pipe 1 config delay 750
#         sudo dnctl pipe 2 config delay 750 #bw 64Kbit/s delay 250 queue 10Kbytes #plr 0.25
#         sudo pfctl -f - <<EOF
#                 dummynet out proto udp from any to $addr port $port pipe 1
#                 dummynet out proto udp from $addr port $port to any pipe 2
# EOF
#         sudo pfctl -e || true
# fi

tmux -CC \
        new-session "sleep $delay; $cc; sleep 1" \; \
        split-window -h "$sc; sleep 1" \; \
        set remain-on-exit on

# ats doesn't exit cleanly
pkill -9 traffic_server

# if we are on MacOS X, unconfigure the firewall
if [ -x /usr/sbin/dnctl ]; then
        sudo dnctl -f flush
        sudo pfctl -f /etc/pf.conf -d
fi

#! /usr/bin/env bash

rm -f /cores/*.core

set -e

# by default, test quant
c=${1:-quant}
s=${2:-quant}

# port to run servers on
addr=127.0.0.1
port=4433 # mozquic server can only run on 4433 at the moment
path=/index.html
dir=/Users/lars/Sites/lars/output
cert=/etc/letsencrypt/live/slate.eggert.org/fullchain.pem
key=/etc/letsencrypt/live/slate.eggert.org/privkey.pem

# (re-)build the client (and possibly server) to test
if [ "$c" == wcquant ] || [ "$s" == wcquant ] ||
   [ "$c" == wsquant ] || [ "$s" == wsquant ]; then
        delay=0.1
        vagrant ssh -c "\
                mkdir -p /vagrant/Linux; \
                cd /vagrant/Linux; \
                cmake -GNinja .. && ninja"
else
        delay=0.1
        ninja "$c"
        [ "$c" != "$s" ] && ninja "$s"
fi

set +e

export ASAN_OPTIONS=strict_string_checks=1:strict_init_order=1:detect_stack_use_after_return=1:detect_leaks=1:check_initialization_order=1:sleep_before_dying=30:alloc_dealloc_mismatch=1:detect_invalid_pointer_pairs=1
# export UBSAN_OPTIONS=suppressions=../misc/ubsan.supp:print_stacktrace=1

# commands to run the different clients against $addr:$port
case $c in
        quant)
                cc="bin/client -v5 https://$addr:$port$path" # https://$addr:$port$path"
                ;;
        wsquant)
                cc="bin/client -i vboxnet3 -v5 https://172.28.128.3:$port$path"
                ;;
        wcquant)
                cc="vagrant ssh -c \"\
                        /vagrant/Linux/bin/client -i enp0s8 -v5 \
                                https://172.28.128.1:$port$path\""
                ;;
        quicly)
                cc="external/quicly-prefix/src/quicly-build/cli \
                        -l /tmp/quicly-c.log -s /tmp/quicly-session -v \
                        -p $path $addr $port"
                ;;
        minq)
                cc="env MINQ_LOG=aead,connection,ack,handshake,tls,server,udp \
                        GOPATH=$(pwd)/external/go go run \
                        external/go/src/github.com/ekr/minq/bin/client/main.go \
                        -addr $addr:$port -http $path"
                ;;
        ngtcp2)
                touch /tmp/ngtcp2-session /tmp/ngtcp2-tp
                cc="echo GET / > /tmp/ngtcp2-req | \
                        external/ngtcp2-prefix/src/ngtcp2/examples/client \
                        -d /tmp/ngtcp2-req $addr $port --session-file=/tmp/ngtcp2-session \
                        --tp-file=/tmp/ngtcp2-tp"
                ;;
        mozquic)
                cc="env MOZQUIC_LOG=all:9 \
                        MOZQUIC_NSS_CONFIG=external/mozquic-prefix/src/mozquic/sample/nss-config \
                        DYLD_LIBRARY_PATH=external/mozquic-prefix/src/dist/$(cat external/mozquic-prefix/src/dist/latest)/lib \
                        external/mozquic-prefix/src/mozquic/client \
                                -peer $addr:$port -get $path -send-close"
                ;;
        picoquic)
                cc="external/picoquic-prefix/src/picoquic/picoquicdemo \
                        $addr $port -r"
                ;;
esac

# commands to run the different servers on  $addr:$port
case $s in
        quant)
                sc="bin/server -v5 -p $port -d $dir"
                ;;
        wsquant)
                sc="vagrant ssh -c \"\
                        /vagrant/Linux/bin/server -i enp0s8 -v5 -p $port \
                                -c ~/slate.eggert.org/fullchain.pem \
                                -k ~/slate.eggert.org/privkey.pem \
                                -d /usr/share/apache2/default-site\""
                ;;
        wcquant)
                sc="bin/server -v5 -i vboxnet3 -p $port -d $dir"
                ;;
        quicly)
                sc="external/quicly-prefix/src/quicly-build/cli \
                        -l /tmp/quicly-s.log -v \
                        -k $key -c $cert $addr $port"
                ;;
        minq)
                sc="env MINQ_LOG=aead,connection,ack,handshake,tls,server,udp \
                        GOPATH=$(pwd)/external/go go run \
                        external/go/src/github.com/ekr/minq/bin/server/main.go \
                        -addr $addr:$port -http -key $key -stateless-reset \
                        -cert $cert -server-name $addr"
                ;;
        ngtcp2)
                sc="external/ngtcp2-prefix/src/ngtcp2/examples/server \
                        -d $dir $addr $port $key $cert"
                ;;
        mozquic)
                sc="env MOZQUIC_LOG=all:9 \
                        MOZQUIC_NSS_CONFIG=external/mozquic-prefix/src/mozquic/sample/nss-config \
                        DYLD_LIBRARY_PATH=external/mozquic-prefix/src/dist/$(cat external/mozquic-prefix/src/dist/latest)/lib \
                        external/mozquic-prefix/src/mozquic/server -send-close"
                ;;
        picoquic)
                sc="external/picoquic-prefix/src/picoquic/picoquicdemo \
                        -p $port -k $key -c $cert"
                ;;
        ats)
                sed -i"" -e "s/.*proxy.config.http.server_ports.*/CONFIG proxy.config.http.server_ports STRING $port:quic/g" external/etc/trafficserver/records.config
                echo "dest_ip=* ssl_cert_name=$cert ssl_key_name=$key" > external/etc/trafficserver/ssl_multicert.config
                echo "map / http://127.0.0.1:8000/" > external/etc/trafficserver/remap.config
                sc="external/bin/traffic_server"
                ;;
esac

# # if we are on MacOS X, configure the firewall to add delay and loss
# if [ -x /usr/sbin/dnctl ]; then
#         # create pipes to limit bandwidth and add loss
#         sudo dnctl pipe 1 config delay 750
#         sudo dnctl pipe 2 config delay 750 #bw 64Kbit/s delay 250 queue 10Kbytes #plr 0.25
#         sudo pfctl -f - <<EOF
#                 dummynet out proto udp from any to $addr port $port pipe 1
#                 dummynet out proto udp from $addr port $port to any pipe 2
# EOF
#         sudo pfctl -e || true
# fi

tmux -CC \
        new-session "sleep $delay; $cc; sleep 1" \; \
        split-window -h "$sc; sleep 1" \; \
        set remain-on-exit on

# ats doesn't exit cleanly
pkill -9 traffic_server

# if we are on MacOS X, unconfigure the firewall
if [ -x /usr/sbin/dnctl ]; then
        sudo dnctl -f flush
        sudo pfctl -f /etc/pf.conf -d
fi


Add add script that helps you add items

Add add script that helps you add items

error: pathspec 'COBOL/Gnu/add.sh' did not match any file(s) known to git


Support all OS X versions, maybe

Support all OS X versions, maybe

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/sachin21/dotfiles.git/'


[YDB-22]: Adds the test script back

[YDB-22]: Adds the test script back

Not really sure what happened to this..

#!/usr/bin/env bash
source /usr/local/opt/chruby/share/chruby/chruby.sh
chruby ruby

xcodebuild -workspace framework/YapDatabaseExtensions.xcworkspace -scheme YapDatabaseExtensions test

error: pathspec 'scripts/test.sh' did not match any file(s) known to git


Prep to track curr sequence.

Prep to track curr sequence.

#!/bin/bash

### Functions pertaining to keeping track of progress and restarting in the event of a crash. ###

### in_stage $VAR

in_stage () {

}

error: pathspec 'sequence_fns.sh' did not match any file(s) known to git


Create install-postgresql.sh

Create install-postgresql.sh

#!/bin/bash
# LaraScale PostgreSQL package for Ubuntu 14.04

# Am I root?
if [ "x$(id -u)" != 'x0' ]; then
    echo
    echo "================ Error ================="
    echo "This script can only be executed by root"
    echo "========================================"
    echo
    exit 1
fi

# Check OS
if [ "$(head -n1 /etc/issue | cut -f 1 -d ' ')" != 'Ubuntu' ] && [ "$(lsb_release -r|awk '{print $2}')" != '14.04' ]; then
    echo
    echo "================== Error ====================="
    echo "This script may be run only on Ubuntu 14.04.4"
    echo "=============================================="
    echo
    exit 1
fi

gen_pass() {
    MATRIX='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
    LENGTH=16
    while [ ${n:=1} -le $LENGTH ]; do
        PASS="$PASS${MATRIX:$(($RANDOM%${#MATRIX})):1}"
        let n+=1
    done
    echo "$PASS"
}

clear
echo
echo
echo '  ██╗      █████╗ ██████╗  █████╗ ███████╗ ██████╗ █████╗ ██╗     ███████╗ '
echo '  ██║     ██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔════╝██╔══██╗██║     ██╔════╝ '
echo '  ██║     ███████║██████╔╝███████║███████╗██║     ███████║██║     █████╗   '
echo '  ██║     ██╔══██║██╔══██╗██╔══██║╚════██║██║     ██╔══██║██║     ██╔══╝   '
echo '  ███████╗██║  ██║██║  ██║██║  ██║███████║╚██████╗██║  ██║███████╗███████╗ '
echo '  ╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝╚══════╝ ╚═════╝╚═╝  ╚═╝╚══════╝╚══════╝ '
echo
echo '                             LaraScale PostgreSQL package for Ubuntu 14.04 '
echo -e "\n\n"

echo
echo "=========== Install overview ==========="
echo
echo "- Nginx (stable >= 1.10)"
echo "- PHP 7 (stable >= 7.0.10) with PHP-FPM "
echo "- Memcached Server"
echo "- PostgreSQL 9.6"
echo "- Composer + Laravel 5.2"
echo

read -p 'Ok, install right now? [y/n]): ' answer
if [ "$answer" != 'y' ] && [ "$answer" != 'Y'  ]; then
    clear
    echo 'Goodbye my friend!'
    exit 1
fi

echo
#echo "- Checking system updates, please wait..."
#apt-get update -y --force-yes -qq > /dev/null 2>&1
#echo "- System update, please wait..."
#apt-get upgrade -y --force-yes -qq > /dev/null 2>&1

echo "- System utils installing..."
apt-get install mc zip unzip htop python-software-properties software-properties-common build-essential -y > /dev/null 2>&1

add-apt-repository ppa:ondrej/php -y > /dev/null 2>&1
apt-get update -y --force-yes -qq > /dev/null 2>&1

echo
echo "=========== Install PHP7 with modules: ==========="
echo

echo "1) php7.0-fpm"
echo "2) php7.0-common"
echo "3) php7.0-gd"
echo "4) php7.0-pgsql"
echo "5) php7.0-curl"
echo "6) php7.0-cli"
echo "7) php-pear"
echo "8) php7.0-dev"
echo "9) php7.0-imap"
echo "10) php7.0-mcrypt"
echo "11) php7.0-readline"
echo "12) php7.0-mbstring"
echo "13) php7.0-json"
echo "14) php7.0-zip"
echo "15) php7.0-memcached"
echo "16) php7.0-imagick"

echo
echo "- Installing, please wait..."
echo

apt-get install php7.0-fpm php7.0-common php7.0-gd php7.0-mysql php7.0-curl php7.0-cli php-pear php7.0-dev php7.0-imap php7.0-mcrypt php7.0-readline php7.0-mbstring php7.0-json php7.0-zip memcached php7.0-memcached php7.0-imagick imagemagick -y --force-yes -qq > /dev/null 2>&1

echo
echo "==> PHP7 installed succesful!"
echo

echo
echo "=========== Install Nginx ==========="
echo

add-apt-repository ppa:nginx/stable -y > /dev/null 2>&1
apt-get update -y --force-yes -qq > /dev/null 2>&1

echo
echo "- Installing, please wait..."
echo

apt-get install nginx -y --force-yes -qq > /dev/null 2>&1

rm /etc/nginx/sites-available/default > /dev/null 2>&1
wget https://raw.githubusercontent.com/globalmac/Larascale/master/nginx/default -O /etc/nginx/sites-available/default > /dev/null 2>&1

echo
echo "==> Nginx installed succesful!"
echo

echo
echo "=========== Install PostgreSQL 9.6 ==========="
echo

PSQL_ROOT_PASSWORD=$(gen_pass)
PSQL_PASSWORD=$(gen_pass)

echo
echo "- Cleaning up, please wait..."
echo

apt-get update -y > /dev/null 2>&1
apt-get upgrade -y > /dev/null 2>&1
apt-get clean -y > /dev/null 2>&1
apt-get autoclean -y > /dev/null 2>&1
apt-get autoremove -y > /dev/null 2>&1

echo
echo "- Installing, please wait..."
echo

sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ `lsb_release -cs`-pgdg main" >> /etc/apt/sources.list.d/pgdg.list' -y > /dev/null 2>&1

wget -q https://www.postgresql.org/media/keys/ACCC4CF8.asc -O - | sudo apt-key add - > /dev/null 2>&1
apt-get update -y > /dev/null 2>&1
apt-get install postgresql postgresql-contrib -y > /dev/null 2>&1

echo
echo "- Setting up PostgreSQL..."
echo

sudo -i -u postgres psql -q -c "ALTER USER postgres WITH PASSWORD '$PSQL_ROOT_PASSWORD';"
sudo -i -u postgres psql -q -c "create database larascale with encoding='UNICODE';"
sudo -i -u postgres psql -q -c "create user larascale with password '$PSQL_PASSWORD';"
sudo -i -u postgres psql -q -c "grant all privileges on database larascale to larascale;"

echo
echo "==> PostgreSQL 9.6 installed succesful!"
echo

echo
echo "=========== Adding larascale user ==========="
echo

useradd -g sudo -d /var/www/larascale -m -s /bin/bash larascale > /dev/null 2>&1
larascale_password=$(gen_pass)

echo -e "$larascale_password\n$larascale_password\n" | passwd larascale > /dev/null 2>&1

mkdir -p /var/www/larascale/sites > /dev/null 2>&1
chown -R larascale:www-data /var/www/larascale > /dev/null 2>&1

echo
echo "==> User larascale - added successfully!"
echo

echo
echo "=========== Installing Composer & Laravel 5.2 ==========="
echo

cd /var/www/larascale
curl -sS https://getcomposer.org/installer | php > /dev/null 2>&1
mv composer.phar /usr/local/bin/composer > /dev/null 2>&1 > /dev/null 2>&1

echo
echo "Installing Laravel 5.2 by Composer, please wait, it can be more than 3-5 minutes..."
echo

composer create-project --prefer-dist laravel/laravel sites "5.2.*" > /dev/null 2>&1
# If you want install Lrarvel 5.3 use below
#composer create-project --prefer-dist laravel/laravel sites > /dev/null 2>&1
chown -R larascale:www-data /var/www/larascale > /dev/null 2>&1
cd sites
chmod -R 777 storage > /dev/null 2>&1
chmod -R 777 bootstrap/cache > /dev/null 2>&1

service php7.0-fpm restart > /dev/null 2>&1
service nginx restart > /dev/null 2>&1
service mysql restart > /dev/null 2>&1

echo "==========="
echo "Installation complete successfully! Your new Laravel is ready!"
echo "1) SSH user:"
echo "Login: larascale"
echo "Password: $larascale_password"
echo "2) PostgreSQL info:"
echo "Login: postgres"
echo "Password: $PSQL_ROOT_PASSWORD"
echo
echo "Login: larascale"
echo "Password: $PSQL_PASSWORD"
echo
echo "Your Laravel site run on - http://$(ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1')"
echo ""
echo "==========="

apt-get clean -y > /dev/null 2>&1
apt-get autoclean -y > /dev/null 2>&1
apt-get autoremove -y > /dev/null 2>&1

exit 0

error: pathspec 'install-postgresql.sh' did not match any file(s) known to git


Add Travis check for duplicate includes

Add Travis check for duplicate includes

This enforces parts of the project header include guidelines (added by @sipa in #10575).

#!/bin/bash
#
# Copyright (c) 2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Check for duplicate includes.

filter_suffix() {
    git ls-files | grep -E "^src/.*\.${1}"'$' | grep -Ev "/(leveldb|secp256k1|univalue)/"
}

EXIT_CODE=0
for HEADER_FILE in $(filter_suffix h); do
    DUPLICATE_INCLUDES_IN_HEADER_FILE=$(grep -E "^#include " < "${HEADER_FILE}" | sort | uniq -d)
    if [[ ${DUPLICATE_INCLUDES_IN_HEADER_FILE} != "" ]]; then
        echo "Duplicate include(s) in ${HEADER_FILE}:"
        echo "${DUPLICATE_INCLUDES_IN_HEADER_FILE}"
        echo
        EXIT_CODE=1
    fi
    CPP_FILE=${HEADER_FILE/%\.h/.cpp}
    if [[ ! -e $CPP_FILE ]]; then
        continue
    fi
    DUPLICATE_INCLUDES_IN_HEADER_AND_CPP_FILES=$(grep -hE "^#include " <(sort -u < "${HEADER_FILE}") <(sort -u < "${CPP_FILE}") | grep -E "^#include " | sort | uniq -d)
    if [[ ${DUPLICATE_INCLUDES_IN_HEADER_AND_CPP_FILES} != "" ]]; then
        echo "Include(s) from ${HEADER_FILE} duplicated in ${CPP_FILE}:"
        echo "${DUPLICATE_INCLUDES_IN_HEADER_AND_CPP_FILES}"
        echo
        EXIT_CODE=1
    fi
done
for CPP_FILE in $(filter_suffix cpp); do
    DUPLICATE_INCLUDES_IN_CPP_FILE=$(grep -E "^#include " < "${CPP_FILE}" | sort | uniq -d)
    if [[ ${DUPLICATE_INCLUDES_IN_CPP_FILE} != "" ]]; then
        echo "Duplicate include(s) in ${CPP_FILE}:"
        echo "${DUPLICATE_INCLUDES_IN_CPP_FILE}"
        echo
        EXIT_CODE=1
    fi
done
exit ${EXIT_CODE}

error: pathspec 'contrib/devtools/lint-includes.sh' did not match any file(s) known to git


Add utxo snapshot script to devtools

Add utxo snapshot script to devtools

#!/usr/bin/env bash
#
# Copyright (c) 2019 The Bitcoin Core developers
# Copyright (c) 2020 The Unobtanium Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
export LC_ALL=C

set -ueo pipefail

if (( $# < 3 )); then
  echo 'Usage: utxo_snapshot.sh <generate-at-height> <snapshot-out-path> <unobtanium-cli-call ...>'
  echo
  echo "  if <snapshot-out-path> is '-', don't produce a snapshot file but instead print the "
  echo "  expected assumeutxo hash"
  echo
  echo 'Examples:'
  echo
  echo "  ./contrib/devtools/utxo_snapshot.sh 1539488 utxo.dat ./src/unobtanium-cli -datadir=\$(pwd)/testdata"
  echo '  ./contrib/devtools/utxo_snapshot.sh 1539488 - ./src/unobtanium-cli'
  exit 1
fi

GENERATE_AT_HEIGHT="${1}"; shift;
OUTPUT_PATH="${1}"; shift;
# Most of the calls we make take a while to run, so pad with a lengthy timeout.
UNOBTANIUM_CLI_CALL="${*} -rpcclienttimeout=9999999"

# Block we'll invalidate/reconsider to rewind/fast-forward the chain.
PIVOT_BLOCKHASH=$($UNOBTANIUM_CLI_CALL getblockhash $(( GENERATE_AT_HEIGHT + 1 )) )

(>&2 echo "Rewinding chain back to height ${GENERATE_AT_HEIGHT} (by invalidating ${PIVOT_BLOCKHASH}); this may take a while")
${UNOBTANIUM_CLI_CALL} invalidateblock "${PIVOT_BLOCKHASH}"

if [[ "${OUTPUT_PATH}" = "-" ]]; then
  (>&2 echo "Generating txoutset info...")
  ${UNOBTANIUM_CLI_CALL} gettxoutsetinfo | grep hash_serialized_2 | sed 's/^.*: "\(.\+\)\+",/\1/g'
else
  (>&2 echo "Generating UTXO snapshot...")
  ${UNOBTANIUM_CLI_CALL} dumptxoutset "${OUTPUT_PATH}"
fi

(>&2 echo "Restoring chain to original height; this may take a while")
${UNOBTANIUM_CLI_CALL} reconsiderblock "${PIVOT_BLOCKHASH}"

error: pathspec 'contrib/devtools/utxo_snapshot.sh' did not match any file(s) known to git


true order things should happen in

true order things should happen in

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/enckse/core-scripts.git/'


add script to move a repo

add script to move a repo

#!/usr/bin/env bash
#
# Move a repository to another organization.
#
# Usage:
#   repo-move.sh [OPTIONS] <source org/repo> <target org>
#
# Options:
#   --i-know-what-im-doing Suppress any warning (useful for scripting!)
#   -n                     Dry-run; only show what would be done.
#   -h, --help             Display this message.
#
# Example:
#   repo-move.sh org1/repo org2
#

BASE_DIR=$(cd "${0%/*}/.." && pwd)
. "$BASE_DIR/lib-ghe.sh"

while [ $# -gt 0 ]; do
    case $1 in
        (--i-know-what-im-doing) NO_WARNING=1; shift;;
        (-n) DRY_RUN=1; shift;;
        (-h|--help) usage 2>&1;;
        (--) shift; break;;
        (-*) usage "$1: unknown option";;
        (*) break;;
    esac
done

SOURCE_SLUG=$1
if [ -z "$SOURCE_SLUG" ]; then
    usage "Source org/repo is a required parameter!"
fi

TARGET_ORG=$2
if [ -z "$TARGET_ORG" ]; then
    usage "Target org is a required parameter!"
fi

[ -n "$NO_WARNING" ] || warning "This script moves '$SOURCE_SLUG' to '$TARGET_ORG' on $GHE_HOST!"

execute << EOF
    github-env bin/runner -e production "'
        repo = Repository.nwo \"$SOURCE_SLUG\";
        target_org = User / \"$TARGET_ORG\";
        staff_user = User / \"$GHE_USER\";
        if repo and target_org and staff_user;
            repo.async_transfer_ownership_to(target_org, actor: staff_user, target_teams: []);
        else
            puts \"ERROR: Repo or target org does not exist.\";
        end;
    '"
EOF

error: pathspec 'admin/repo-move.sh' did not match any file(s) known to git


very simple ydt

very simple ydt

#!/bin/bash

INSTALL_DIR="/opt/poky/1.5.1"

# HOST data
HOST_ARCH=$(uname -m)
HOST_OS=$(uname -o)
HOST_KERNEL_VERSION=$(uname -r)

# TARGET
TARGET_ARCH=(i586 x86_64 powerpc mips armv7a armv5te)

# YOCTO data
YOCTO_VERSION="1.5.1"
YOCTO_DISTRO="poky"
YOCTO_REPO="http://downloads.yoctoproject.org/releases/yocto/yocto-${YOCTO_VERSION}"

declare -a TARGETS=("qemumips" "qemuppc" "qemux86" "qemux86-64" "genericx86" "genericx86-64" "beagleboard" "mpc8315e-rdb" "routerstationpro")
PACKAGE_MANAGER="rpm"
IMAGE_TYPE="core-image-sato"
MACHINE="" #will be one of targets

###############################
# install full yocto          #
###############################
install_full_yocto() {
  cd ${INSTALL_DIR}
  git clone git://git.yoctoproject.org/${YOCTO_DISTRO}
  source ${YOCTO_DISTRO}/oe-init-build-env

#alter conf/local.conf
  sed -i 's/MACHINE ??= \"qemux86\"/MACHINE ??= \"${MACHINE}\"/g' conf/local.conf

  bitbake core-image-minimal
}

############################
# toolchain installer      #
############################
install_toolchain_only() {
  wget ${YOCTO_REPO}/toolchain/${HOST_ARCH}/${YOCTO_DISTRO}-eglibc-${HOST_ARCH}-${IMAGE_TYPE}-<arch>-toolchain-${YOCTO_VERSION}.sh
}

############################
# nothing to do with NSA   #
############################
collect_user_data() {
  echo -e "install directory [${INSTALL_DIR}]:"
  read INSTDIR
  echo -e "target"
  read TRG
  echo -e "package manager [rpm], but also [tar, deb, ipk] available:"
  read PKG
  echo -e "image type [core-image-sato], but also [
}

#########################################################################################
#                                                                                #
# MAIN FUNCTION                                                                         #
#########################################################################################

echo -e "welcom to simple YOCTO installer"
echo -e "##################################################"

echo -e "do you want to proceed with:"
echo -e "[1] full YOCTO install"
echo -e "[2] toolchain only"
echo ""
read CHOICE

case "${CHOICE}" in
1) collect_user_data
  install_full_yocto
  ;;
2) collect_user_data
  install_toolchain_only
  ;;
*) echo "wrong choice"
  ;;
esac

error: pathspec 'ydt_simple.sh' did not match any file(s) known to git


Build scripts for ppc64le/Linux.

Build scripts for ppc64le/Linux.

# ----------------------------------------------------------------------------
#
# Package	: corosync
# Version	: 2.99.1
# Source repo	: https://github.com/corosync/corosync.git
# Tested on	: ubuntu_16.04
# Script License: Apache License, Version 2 or later
# Maintainer	: Atul Sowani <sowania@us.ibm.com>
#
# Disclaimer: This script has been tested in non-root mode on given
# ==========  platform using the mentioned version of the package.
#             It may not work as expected with newer versions of the
#             package and/or distribution. In such case, please
#             contact "Maintainer" of this script.
#
# ----------------------------------------------------------------------------
#!/bin/bash

# Install dependencies.
sudo apt-get update -y
sudo apt-get install -y git make gcc automake autoconf libnss3-dev libtool \
    libsctp-dev check pkg-config groff libpam0g-dev liblz4-dev doxygen \
    zlib1g zlib1g-dev libssl-dev liblzo2-dev liblzma-dev libbz2-dev \
    libxml2-dev
WDIR=`pwd`

# Install libqb.
cd /tmp
git clone git://github.com/asalkeld/libqb.git
cd libqb && ./autogen.sh && ./configure && \
  make && make check && \
  sudo make install

# build libknet.
cd /tmp
git clone https://github.com/fabbione/kronosnet && \
  cd kronosnet && ./autogen.sh && ./configure && \
  sed -i -e 's/-Werror//' libknet/tests/Makefile && \
  sed -i -e 's/LIBS = /LIBS = -lpthread /' libknet/tests/Makefile && \
  make && sudo make install

cd $WDIR
git clone https://github.com/corosync/corosync.git
cd corosync
./autogen.sh && ./configure && \
  make && make check && \
  sudo make install

error: pathspec 'corosync/corosync_ubuntu_16.04.sh' did not match any file(s) known to git


[STORM-260]/Make live action execution asynchronous with POST call

* Implement helper script that will populate local repo for developers.

#!/bin/sh

REPO_DIR=/opt/stackstorm/repo

USER="vagrant:vagrant"

BASEDIR=`dirname ${0}`
CONTENT_FOLDER=`realpath ${BASEDIR}/../../content`

CONTENT_SETS="devel"

FORCE='false'

print_usage() {
    echo "usage: populate_stackstorm_repo.sh [--force]"
    echo ""
    echo "    --force    forcibly overwrite anything already in the repo"
    echo ""
    exit 1
}

if [ "$#" -ne "0" ]; then
    while [ "$#" -gt "0" ]
    do
        case $1 in

        --force)
                FORCE='true'
                shift
                ;;
        *)
                echo "error: unknown option '${1}' ... aborting"
                print_usage
                shift
                ;;
        esac
    done
fi

if [ -e ${REPO_DIR} ] && [ "${FORCE}" != "true" ]; then
    echo "error: repo already exists. Aborting population"
    exit 1
fi

echo "Creating repo folder: ${REPO_DIR}"
sudo mkdir -p ${REPO_DIR}
sudo chown -R ${USER} ${REPO_DIR}

echo "Copying content sets from ${CONTENT_FOLDER} to repo folder"

for set in ${CONTENT_SETS}; do
    echo "    copying content set: ${set}"
    cp -Rp ${CONTENT_FOLDER}/${set}/* ${REPO_DIR}
done

echo "Finished copying content"
echo "Repo is ready for use"

error: pathspec 'devel/scripts/populate_stackstorm_repo.sh' did not match any file(s) known to git


Add tool for running scripts on remote machines

#!/bin/bash
##### -*- mode:shell-script; indent-tabs-mode:nil; sh-basic-offset:2 -*-
##### Author: Travis Cross <tc@traviscross.com>

#set -xv

err () {
  echo "$1" 1>&2
  exit 1
}

ssh_args=""
script=""
while getopts "f:p:" o; do
  case "$o" in
    f) script="$OPTARG" ;;
    p) ssh_args="-p $OPTARG" ;;
  esac
done
shift $(($OPTIND-1))

url="$1"

if [ ! "$url" ]; then
  err "Usage: $0 [-f script] ssh-url"
fi

remote_command () {
  ssh $ssh_args "$url" "$1"
}

remote_run () {
  remote_command \
    "rf=\$(mktemp /tmp/remote-run-XXXXXXXX); \
cat > \$rf && chmod +x \$rf && \$rf; rm -f \$rf"
}

if test -n "$script"; then
  cat "$script" | remote_run
else
  remote_run
fi

error: pathspec 'remote-run.sh' did not match any file(s) known to git


add script to perform icon tagging

add script to perform icon tagging

#!/bin/sh

#  tag-icons.sh
#  Trgnmtry
#
#  Created by Andrew McKnight on 4/1/17.
#  Copyright © 2017 Two Ring Software. All rights reserved.

XCODE_ICON_TAGGER_SCRIPT_MODE="$1"

function invoke_tagger() {
    XCODE_ICON_TAGGER_TOOL_MODE="$1"
    OPTIONAL_CUSTOM_ICON_TAG_TEXT="$2"

    sh ${SRCROOT}/Vendor/XcodeIconTagger/tagIcons.sh            \
        $XCODE_ICON_TAGGER_TOOL_MODE                            \
        ${SRCROOT}/Trgnmtry/Assets.xcassets/AppIcon.appiconset  \
        $OPTIONAL_CUSTOM_ICON_TAG_TEXT
}

if [[ $XCODE_ICON_TAGGER_SCRIPT_MODE = "tag" ]]; then
    if [[ "$TARGET_NAME" = "Trgnmtry Touches" ]]; then
        invoke_tagger "custom" "Touches"
    else
        if [[ $CONFIGURATION = "Beta" ]]; then
            invoke_tagger "version"
        elif [[ $CONFIGURATION = "Debug" ]]; then
            invoke_tagger "commit"
        fi
    fi
else
    invoke_tagger "cleanup"
fi

error: pathspec 'Scripts/tag-icons.sh' did not match any file(s) known to git


added sync.sh

added sync.sh

cp -r ../../sophena-data/csv/* ./data/csv
cp -r ../../sophena-data/json/* ./data/json

error: pathspec 'sophdat/sync.sh' did not match any file(s) known to git


raspberry pi bootstrap

raspberry pi bootstrap

# Initialization for raspberry pi 3
# Assuming debian installation

sudo apt-get update -y
sudo apt-get dist-upgrade -y
sudo apt-get upgrade -y
sudo apt-get autoremove -y

sudo apt-get install build-essential
sudo apt-get install htop

# Emacs
# sudo nano /etc/apt/sources.list
# uncomment the 3rd line so that archive is on
sudo apt-get update
sudo apt-get build-dep emacs24
cd ~/lib
wget http://ftp.gnu.org/gnu/emacs/emacs-25.2.tar.gz
tar -zxf emacs-25.2.tar.gz
cd emacs-25.2
./configure
sudo make install
sudo lib-src/blessmail /usr/local/libexec/emacs/25.2/armv7l-unknown-linux-gnueabihf/movemail
git clone https://github.com/syl20bnr/spacemacs ~/.emacs.d

error: pathspec 'pi_init.sh' did not match any file(s) known to git


initial version of the go installer

initial version of the go installer

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/serDrem/incubator-trafficcontrol.git/'


op 'start' removed assumption that execution is ./vhostctl.sh

on operation 'start' removed the assumption that the execution is on the
same directory ./vhostctl.sh ($CWD) as it's not true for the execution from
taskd and it breaks the docker build command.

#!/bin/bash

# functions
show_help()
{
  echo "Usage: ./vhostctl.sh [OPTIONS]

Options:

  -A, --application               Application name. Apps supported: Wordpress, Drupal.
  -C, --operation                 Operation commands:
                                    start - to build and start containers with the application
                                    clone - to copy containers with new names and replace configuration with new URL
                                    fullclone - to setup new containers from scratch and replicate existing data
                                    backup - to save current state of existing containers
                                    restore - to restore containers to previous state
  -SD, --source-domain            Source domain name. Used for 'clone' operation.
  -DD, --destination-domain       Destination domain name. For 'clone' operation different domain name should be passed.
  -B, --backup-name               Backup name.
  -R, --restore-name              Restore previously backed up name.

Usage examples:
  ./vhostctl.sh -A=wordpress -C=start -DD=t3st.some.domain
  ./vhostctl.sh -A=wordpress -C=fullclone -SD=t3st.some.domain -DD=t4st.some.domain
  ./vhostctl.sh -A=wordpress -C=clone -SD=t3st.some.domain -DD=t4st.some.domain
  ./vhostctl.sh -C=backup  -DD=t3st.some.domain -B=t3st_backup1
  ./vhostctl.sh -C=restore -DD=t3st.some.domain -R=t3st_backup1
"
}

self_bin=$(readlink -e "$0")
if [ $? -ne 0 ]; then
  echo "Error: unable to detect self path" 1>&2
  exit 1
fi
self_dir=${self_bin%/*}

# parse option arguments
for i in "$@"
do
case $i in
    -A=*|--application=*)
    app="${i#*=}"
    shift # past argument=value
    ;;
    -C=*|--operation=*)
    operation="${i#*=}"
    shift # past argument=value
    ;;
    -SD=*|--source-domain=*)
    source_domain="${i#*=}"
    shift # past argument=value
    ;;
    -DD=*|--destination-domain=*)
    domain="${i#*=}"
    shift # past argument=value
    ;;
    -B=*|--backup-name=*)
    backup_name="${i#*=}"
    shift # past argument=value
    ;;
    -R=*|--restore-name=*)
    restore_name="${i#*=}"
    shift # past argument=value
    ;;
    *)
    show_help
            # unknown option
    ;;
esac
done

# define to use sudo or not
if [ "$UID" -eq 0 ]; then
  sudo=""
else
  sudo="sudo"
fi
# define installation tool
if [ -f /usr/bin/yum ]; then
  installation_tool="yum install -y"
elif [ -f /usr/bin/apt-get ]; then
  installation_tool="apt-get install -y"
else
  echo "OS not supported. Exiting ..."
  exit 1
fi

update_nginx_config()
{
  # check for nginx installation
  if [ ! -f /usr/sbin/nginx ]; then
    ${sudo} ${installation_tool} nginx
  fi
  # get ip address of web container
  if [ "$operation" == "start" ]; then
    container_name="${domain}_${app}_web"
  elif [ "$operation" == "clone" ]; then
    container_name="${domain}_${app}_web"
  elif [ "$operation" == "fullclone" ]; then
    container_name="${domain}_${app}_web_clone"
  elif [ "$operation" == "restore" ]; then
    container_name=$CONTAINER_WEB_NAME
  fi
  container_ip_address=`docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)|grep "${container_name}"|awk -F" - " '{print $2}'`
  # create config
  cat << EOF > /tmp/${domain}.conf
server {
  listen       80;
  server_name  ${domain};
  location / {
    proxy_set_header Host ${domain};
    proxy_pass http://${container_ip_address};
  }
}
EOF
  ${sudo} mv /tmp/${domain}.conf /etc/nginx/sites-enabled/${domain}.conf
  # restart nginx instead reload to avoid error with not running instance
  ${sudo} service nginx restart
}

patch_definition_files_and_build()
{
  source_user=`echo "${source_domain}" | awk -F'[.]' '{print $1}'`
  source_domain_name=`echo "${source_domain}" | awk -F"${source_user}." '{print $2}'`
  user=`echo "${domain}" | awk -F'[.]' '{print $1}'`
  domain_name=`echo "${domain}" | awk -F"${user}." '{print $2}'`

  local compose_file="$self_dir/original/docker-compose.yml"
  local template_file="$compose_file.orig"
  local sed_str=""

  cp -f  "$template_file" "$compose_file"

  sed_str="\
    s/CONTAINER_NAME_VAR/${domain}_${app}/;
    s/SRC_USER_VAR/${source_user}/;
    s/SRC_DOMAIN_VAR/${source_domain_name}/;
    s/t3st/${user}/;
    s/some.domain/${domain_name}/;"

  if [ "$app" == "drupal" ]; then
    sed_str+="s/wordpress-v4/${app}-v7/;"
    sed_str+="s/wordpress/${app}/;"
  fi

  sed -i "$sed_str" "$compose_file"

  /usr/local/bin/docker-compose -f "$compose_file" up --build -d
  rm -f "$compose_file"
  update_nginx_config
}

docker_get_ids_and_names_of_containers()
{
  CONTAINER_WEB_ID=`docker ps|grep ${domain}_${app}_web|awk '{print $1}'`
  CONTAINER_DB_ID=`docker ps|grep ${domain}_${app}_db|awk '{print $1}'`
  # useful for call from clone operation
  if [ "$operation" == "clone" ]; then
    CONTAINER_WEB_ID=`docker ps|grep ${source_domain}_${app}_web|awk '{print $1}'`
    CONTAINER_DB_ID=`docker ps|grep ${source_domain}_${app}_db|awk '{print $1}'`
  fi
  CONTAINER_WEB_NAME=`docker inspect -f '{{.Name}}' ${CONTAINER_WEB_ID}|awk -F'/' '{print $2}'`
  CONTAINER_DB_NAME=`docker inspect -f '{{.Name}}' ${CONTAINER_DB_ID}|awk -F'/' '{print $2}'`
}

# check for Docker installation
if [ ! -f /usr/bin/docker ]; then
  ${sudo} ${installation_tool} docker
fi

# check for Docker Compose binary
if [ ! -f /usr/local/bin/docker-compose ]; then
  curl -L https://github.com/docker/compose/releases/download/1.7.1/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
  chmod +x /usr/local/bin/docker-compose
fi

# check for devpanel_cache image
if [ `docker images devpanel_cache|grep -c devpanel_cache` -eq 0 ]; then
  docker build -t devpanel_cache:v2 "$self_dir/cache"
fi

# main logic
if [ "$app" -a "$operation" == "start" -a "$domain" ]; then
  patch_definition_files_and_build
elif [ "$app" -a "$operation" == "clone" -a "$source_domain" -a "$domain" ]; then
  # parse variables
  source_user=`echo "${source_domain}" | awk -F'[.]' '{print $1}'`
  source_domain_name=`echo "${source_domain}" | awk -F"${source_user}." '{print $2}'`
  user=`echo "${domain}" | awk -F'[.]' '{print $1}'`
  domain_name=`echo "${domain}" | awk -F"${user}." '{print $2}'`
  docker_get_ids_and_names_of_containers
  # save current state of containers as images
  docker commit ${CONTAINER_WEB_NAME} ${domain}_web
  docker commit ${CONTAINER_DB_NAME}  ${domain}_db
  # get ids of images
  IMAGE_WEB_NAME=`docker images|grep ${domain}_web|awk '{print $1}'`
  IMAGE_DB_NAME=`docker images|grep ${domain}_db|awk '{print $1}'`
  # let container know that it was cloned
  echo "CLONE=true" > ./clone_info
  ${sudo} cp -f ./clone_info ./original/data_volume/databases/
  # get current path and set it for mount point
  data_volume_mount_path="$(pwd)/original/data_volume"
  # start cloned containers
  docker run -v ${data_volume_mount_path}:/data    -d --name=${domain}_${app}_db  ${IMAGE_DB_NAME}
  docker run -v ${data_volume_mount_path}:/data:ro -d --name=${domain}_${app}_web ${IMAGE_WEB_NAME}
  # get destination containers ids
  CONTAINER_WEB_ID=`docker ps|grep ${user}.${domain_name}_${app}_web|awk '{print $1}'`
  CONTAINER_DB_ID=`docker ps|grep ${user}.${domain_name}_${app}_db|awk '{print $1}'`
  # get variables for db data replacement
  DB_IP=`awk -F':' '{print $1}' ./original/data_volume/databases/db_info`
  PORT=`awk -F':' '{print $2}' ./original/data_volume/databases/db_info`
  PASSWORD=`awk -F':' '{print $4}' ./original/data_volume/databases/db_info`
  USER=`awk -F':' '{print $3}' ./original/data_volume/databases/db_info`
  DOMAIN=${source_domain_name}
  DST_USER=${user}
  DST_DOMAIN=${domain_name}
  # replace db data with new URL
  if [ "$app" == "wordpress" ]; then
    # wait until mysql starts
    while [ `docker exec -it ${CONTAINER_DB_ID} netstat -ltpn|grep -c ${PORT}` -eq 0 ]; do sleep 1; done
    docker exec -it ${CONTAINER_DB_ID} mysql ${app} -h localhost -P ${PORT} -u w_${USER} --password=${PASSWORD} --socket=/home/clients/databases/b_${USER}/mysql/mysql.sock -e \
      "UPDATE wp_options SET option_value = replace(option_value, 'http://${USER}.${DOMAIN}', 'http://${DST_USER}.${DST_DOMAIN}');"
    # check if it was replaced correctly
    if [ `docker exec -it ${CONTAINER_DB_ID} mysql ${app} -h localhost -P ${PORT} -u w_${USER} --password=${PASSWORD} --socket=/home/clients/databases/b_${USER}/mysql/mysql.sock -e \
      "select * from wp_options;"|grep -c ${DST_USER}` -eq 2 ]; then
        echo "DB cloned correctly."
    else
        echo "Error: URL was not replaced correctly in MySQL."
        exit 1
    fi
  else
    echo "Error: Only Wordpress supported at the moment."
    exit 1
  fi
  # update container's apache2 config with new URL
  docker exec -it ${CONTAINER_WEB_ID} sed -i "s/${USER}.${DOMAIN}/${DST_USER}.${DST_DOMAIN}/" /opt/webenabled/compat/apache_include/virtwww/w_${USER}.conf
  docker exec -it ${CONTAINER_WEB_ID} sed -i "s/${USER}-gen.${DOMAIN}/${DST_USER}-gen.${DST_DOMAIN}/" /opt/webenabled/compat/apache_include/virtwww/w_${USER}.conf
  docker exec -it ${CONTAINER_WEB_ID} /bin/sh -c "echo '${DB_IP} db' >> /etc/hosts"
  if [ `docker exec -it ${CONTAINER_WEB_ID} grep db /etc/hosts|wc -l` -gt 0 -a `docker exec -it ${CONTAINER_WEB_ID} grep -c ${DST_USER} /opt/webenabled/compat/apache_include/virtwww/w_${USER}.conf|wc -l` -gt 0 ]; then
    if [ `docker exec -it ${CONTAINER_WEB_ID} grep ServerName /etc/apache2/apache2.conf|wc -l` -eq 0 ]; then
      docker exec -it ${CONTAINER_WEB_ID} /bin/sh -c "echo 'ServerName localhost' >> /etc/apache2/apache2.conf"
    fi
    docker exec -it ${CONTAINER_WEB_ID} apache2ctl graceful
    echo "WEB cloned correctly."
  else
    echo "Error: Domain in Apache configuration was not replaced correctly."
    exit 1
  fi
  # update host's nginx config with new IP of cloned web container
  update_nginx_config ${domain}_${app}_web
elif [ "$app" -a "$operation" == "fullclone" -a "$source_domain" -a "$domain" ]; then
  cd clone
  patch_definition_files_and_build
elif [ "$operation" == "backup" -a "$backup_name" -a "$domain" ]; then
  # get ids of current containers
  docker_get_ids_and_names_of_containers
  # save current state of containers as images
  docker commit ${CONTAINER_WEB_NAME} ${domain}_${backup_name}_bkp_web
  docker commit ${CONTAINER_DB_NAME}  ${domain}_${backup_name}_bkp_db
elif [ "$operation" == "restore" -a "$restore_name" -a "$domain" ]; then
  # get ids of current containers
  docker_get_ids_and_names_of_containers
  # remove source containers to avoid name conflicts
  docker rm -f ${CONTAINER_WEB_ID}
  docker rm -f ${CONTAINER_DB_ID}
  # get ids of images
  IMAGE_WEB_NAME=`docker images|grep ${domain}_${restore_name}_bkp_web|awk '{print $1}'`
  IMAGE_DB_NAME=`docker images|grep ${domain}_${restore_name}_bkp_db|awk '{print $1}'`
  # start backed up containers
  docker run -d --name=${CONTAINER_DB_NAME}  ${IMAGE_DB_NAME}
  docker run -d --name=${CONTAINER_WEB_NAME} ${IMAGE_WEB_NAME}
  # update nginx config with new IP of web container
  update_nginx_config ${CONTAINER_WEB_NAME}
else
  show_help
  exit 1
fi

#!/bin/bash

# functions
show_help()
{
  echo "Usage: ./vhostctl.sh [OPTIONS]

Options:

  -A, --application               Application name. Apps supported: Wordpress, Drupal.
  -C, --operation                 Operation commands:
                                    start - to build and start containers with the application
                                    clone - to copy containers with new names and replace configuration with new URL
                                    fullclone - to setup new containers from scratch and replicate existing data
                                    backup - to save current state of existing containers
                                    restore - to restore containers to previous state
  -SD, --source-domain            Source domain name. Used for 'clone' operation.
  -DD, --destination-domain       Destination domain name. For 'clone' operation different domain name should be passed.
  -B, --backup-name               Backup name.
  -R, --restore-name              Restore previously backed up name.

Usage examples:
  ./vhostctl.sh -A=wordpress -C=start -DD=t3st.some.domain
  ./vhostctl.sh -A=wordpress -C=fullclone -SD=t3st.some.domain -DD=t4st.some.domain
  ./vhostctl.sh -A=wordpress -C=clone -SD=t3st.some.domain -DD=t4st.some.domain
  ./vhostctl.sh -C=backup  -DD=t3st.some.domain -B=t3st_backup1
  ./vhostctl.sh -C=restore -DD=t3st.some.domain -R=t3st_backup1
"
}

# parse option arguments
for i in "$@"
do
case $i in
    -A=*|--application=*)
    app="${i#*=}"
    shift # past argument=value
    ;;
    -C=*|--operation=*)
    operation="${i#*=}"
    shift # past argument=value
    ;;
    -SD=*|--source-domain=*)
    source_domain="${i#*=}"
    shift # past argument=value
    ;;
    -DD=*|--destination-domain=*)
    domain="${i#*=}"
    shift # past argument=value
    ;;
    -B=*|--backup-name=*)
    backup_name="${i#*=}"
    shift # past argument=value
    ;;
    -R=*|--restore-name=*)
    restore_name="${i#*=}"
    shift # past argument=value
    ;;
    *)
    show_help
            # unknown option
    ;;
esac
done

# define to use sudo or not
if [ "$UID" -eq 0 ]; then
  sudo=""
else
  sudo="sudo"
fi
# define installation tool
if [ -f /usr/bin/yum ]; then
  installation_tool="yum install -y"
elif [ -f /usr/bin/apt-get ]; then
  installation_tool="apt-get install -y"
else
  echo "OS not supported. Exiting ..."
  exit 1
fi

update_nginx_config()
{
  # check for nginx installation
  if [ ! -f /usr/sbin/nginx ]; then
    ${sudo} ${installation_tool} nginx
  fi
  # get ip address of web container
  if [ "$operation" == "start" ]; then
    container_name="${domain}_${app}_web"
  elif [ "$operation" == "clone" ]; then
    container_name="${domain}_${app}_web"
  elif [ "$operation" == "fullclone" ]; then
    container_name="${domain}_${app}_web_clone"
  elif [ "$operation" == "restore" ]; then
    container_name=$CONTAINER_WEB_NAME
  fi
  container_ip_address=`docker inspect -f '{{.Name}} - {{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $(docker ps -aq)|grep "${container_name}"|awk -F" - " '{print $2}'`
  # create config
  cat << EOF > /tmp/${domain}.conf
server {
  listen       80;
  server_name  ${domain};
  location / {
    proxy_set_header Host ${domain};
    proxy_pass http://${container_ip_address};
  }
}
EOF
  ${sudo} mv /tmp/${domain}.conf /etc/nginx/sites-enabled/${domain}.conf
  # restart nginx instead reload to avoid error with not running instance
  ${sudo} service nginx restart
}

patch_definition_files_and_build()
{
  source_user=`echo "${source_domain}" | awk -F'[.]' '{print $1}'`
  source_domain_name=`echo "${source_domain}" | awk -F"${source_user}." '{print $2}'`
  user=`echo "${domain}" | awk -F'[.]' '{print $1}'`
  domain_name=`echo "${domain}" | awk -F"${user}." '{print $2}'`
  cp -f docker-compose.yml.orig docker-compose.yml
  sed -i "s/CONTAINER_NAME_VAR/${domain}_${app}/" docker-compose.yml
  sed -i "s/SRC_USER_VAR/${source_user}/" docker-compose.yml
  sed -i "s/SRC_DOMAIN_VAR/${source_domain_name}/" docker-compose.yml
  sed -i "s/t3st/${user}/" docker-compose.yml
  sed -i "s/some.domain/${domain_name}/" docker-compose.yml
  if [ "$app" == "drupal" ]; then
    sed -i "s/wordpress-v4/${app}-v7/" docker-compose.yml
    sed -i "s/wordpress/${app}/" docker-compose.yml
  fi
  /usr/local/bin/docker-compose up --build -d
  rm -f docker-compose.yml
  update_nginx_config
}

docker_get_ids_and_names_of_containers()
{
  CONTAINER_WEB_ID=`docker ps|grep ${domain}_${app}_web|awk '{print $1}'`
  CONTAINER_DB_ID=`docker ps|grep ${domain}_${app}_db|awk '{print $1}'`
  # useful for call from clone operation
  if [ "$operation" == "clone" ]; then
    CONTAINER_WEB_ID=`docker ps|grep ${source_domain}_${app}_web|awk '{print $1}'`
    CONTAINER_DB_ID=`docker ps|grep ${source_domain}_${app}_db|awk '{print $1}'`
  fi
  CONTAINER_WEB_NAME=`docker inspect -f '{{.Name}}' ${CONTAINER_WEB_ID}|awk -F'/' '{print $2}'`
  CONTAINER_DB_NAME=`docker inspect -f '{{.Name}}' ${CONTAINER_DB_ID}|awk -F'/' '{print $2}'`
}

# check for Docker installation
if [ ! -f /usr/bin/docker ]; then
  ${sudo} ${installation_tool} docker
fi

# check for Docker Compose binary
if [ ! -f /usr/local/bin/docker-compose ]; then
  curl -L https://github.com/docker/compose/releases/download/1.7.1/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose
  chmod +x /usr/local/bin/docker-compose
fi

# check for devpanel_cache image
if [ `docker images devpanel_cache|grep -c devpanel_cache` -eq 0 ]; then
  docker build -t devpanel_cache:v2 ./cache
fi

# main logic
if [ "$app" -a "$operation" == "start" -a "$domain" ]; then
  cd original
  patch_definition_files_and_build
elif [ "$app" -a "$operation" == "clone" -a "$source_domain" -a "$domain" ]; then
  # parse variables
  source_user=`echo "${source_domain}" | awk -F'[.]' '{print $1}'`
  source_domain_name=`echo "${source_domain}" | awk -F"${source_user}." '{print $2}'`
  user=`echo "${domain}" | awk -F'[.]' '{print $1}'`
  domain_name=`echo "${domain}" | awk -F"${user}." '{print $2}'`
  docker_get_ids_and_names_of_containers
  # save current state of containers as images
  docker commit ${CONTAINER_WEB_NAME} ${domain}_web
  docker commit ${CONTAINER_DB_NAME}  ${domain}_db
  # get ids of images
  IMAGE_WEB_NAME=`docker images|grep ${domain}_web|awk '{print $1}'`
  IMAGE_DB_NAME=`docker images|grep ${domain}_db|awk '{print $1}'`
  # let container know that it was cloned
  echo "CLONE=true" > ./clone_info
  ${sudo} cp -f ./clone_info ./original/data_volume/databases/
  # get current path and set it for mount point
  data_volume_mount_path="$(pwd)/original/data_volume"
  # start cloned containers
  docker run -v ${data_volume_mount_path}:/data    -d --name=${domain}_${app}_db  ${IMAGE_DB_NAME}
  docker run -v ${data_volume_mount_path}:/data:ro -d --name=${domain}_${app}_web ${IMAGE_WEB_NAME}
  # get destination containers ids
  CONTAINER_WEB_ID=`docker ps|grep ${user}.${domain_name}_${app}_web|awk '{print $1}'`
  CONTAINER_DB_ID=`docker ps|grep ${user}.${domain_name}_${app}_db|awk '{print $1}'`
  # get variables for db data replacement
  DB_IP=`awk -F':' '{print $1}' ./original/data_volume/databases/db_info`
  PORT=`awk -F':' '{print $2}' ./original/data_volume/databases/db_info`
  PASSWORD=`awk -F':' '{print $4}' ./original/data_volume/databases/db_info`
  USER=`awk -F':' '{print $3}' ./original/data_volume/databases/db_info`
  DOMAIN=${source_domain_name}
  DST_USER=${user}
  DST_DOMAIN=${domain_name}
  # replace db data with new URL
  if [ "$app" == "wordpress" ]; then
    # wait until mysql starts
    while [ `docker exec -it ${CONTAINER_DB_ID} netstat -ltpn|grep -c ${PORT}` -eq 0 ]; do sleep 1; done
    docker exec -it ${CONTAINER_DB_ID} mysql ${app} -h localhost -P ${PORT} -u w_${USER} --password=${PASSWORD} --socket=/home/clients/databases/b_${USER}/mysql/mysql.sock -e \
      "UPDATE wp_options SET option_value = replace(option_value, 'http://${USER}.${DOMAIN}', 'http://${DST_USER}.${DST_DOMAIN}');"
    # check if it was replaced correctly
    if [ `docker exec -it ${CONTAINER_DB_ID} mysql ${app} -h localhost -P ${PORT} -u w_${USER} --password=${PASSWORD} --socket=/home/clients/databases/b_${USER}/mysql/mysql.sock -e \
      "select * from wp_options;"|grep -c ${DST_USER}` -eq 2 ]; then
        echo "DB cloned correctly."
    else
        echo "Error: URL was not replaced correctly in MySQL."
        exit 1
    fi
  else
    echo "Error: Only Wordpress supported at the moment."
    exit 1
  fi
  # update container's apache2 config with new URL
  docker exec -it ${CONTAINER_WEB_ID} sed -i "s/${USER}.${DOMAIN}/${DST_USER}.${DST_DOMAIN}/" /opt/webenabled/compat/apache_include/virtwww/w_${USER}.conf
  docker exec -it ${CONTAINER_WEB_ID} sed -i "s/${USER}-gen.${DOMAIN}/${DST_USER}-gen.${DST_DOMAIN}/" /opt/webenabled/compat/apache_include/virtwww/w_${USER}.conf
  docker exec -it ${CONTAINER_WEB_ID} /bin/sh -c "echo '${DB_IP} db' >> /etc/hosts"
  if [ `docker exec -it ${CONTAINER_WEB_ID} grep db /etc/hosts|wc -l` -gt 0 -a `docker exec -it ${CONTAINER_WEB_ID} grep -c ${DST_USER} /opt/webenabled/compat/apache_include/virtwww/w_${USER}.conf|wc -l` -gt 0 ]; then
    if [ `docker exec -it ${CONTAINER_WEB_ID} grep ServerName /etc/apache2/apache2.conf|wc -l` -eq 0 ]; then
      docker exec -it ${CONTAINER_WEB_ID} /bin/sh -c "echo 'ServerName localhost' >> /etc/apache2/apache2.conf"
    fi
    docker exec -it ${CONTAINER_WEB_ID} apache2ctl graceful
    echo "WEB cloned correctly."
  else
    echo "Error: Domain in Apache configuration was not replaced correctly."
    exit 1
  fi
  # update host's nginx config with new IP of cloned web container
  update_nginx_config ${domain}_${app}_web
elif [ "$app" -a "$operation" == "fullclone" -a "$source_domain" -a "$domain" ]; then
  cd clone
  patch_definition_files_and_build
elif [ "$operation" == "backup" -a "$backup_name" -a "$domain" ]; then
  # get ids of current containers
  docker_get_ids_and_names_of_containers
  # save current state of containers as images
  docker commit ${CONTAINER_WEB_NAME} ${domain}_${backup_name}_bkp_web
  docker commit ${CONTAINER_DB_NAME}  ${domain}_${backup_name}_bkp_db
elif [ "$operation" == "restore" -a "$restore_name" -a "$domain" ]; then
  # get ids of current containers
  docker_get_ids_and_names_of_containers
  # remove source containers to avoid name conflicts
  docker rm -f ${CONTAINER_WEB_ID}
  docker rm -f ${CONTAINER_DB_ID}
  # get ids of images
  IMAGE_WEB_NAME=`docker images|grep ${domain}_${restore_name}_bkp_web|awk '{print $1}'`
  IMAGE_DB_NAME=`docker images|grep ${domain}_${restore_name}_bkp_db|awk '{print $1}'`
  # start backed up containers
  docker run -d --name=${CONTAINER_DB_NAME}  ${IMAGE_DB_NAME}
  docker run -d --name=${CONTAINER_WEB_NAME} ${IMAGE_WEB_NAME}
  # update nginx config with new IP of web container
  update_nginx_config ${CONTAINER_WEB_NAME}
else
  show_help
  exit 1
fi


add AOO up.sh, similar to LO's one

add AOO up.sh, similar to LO's one

not perfect yet (doesn't do installation), but it's a start

time sh -c "git pull -r && \
	autoconf && \
	./configure --with-epm-url=http://www.msweet.org/files/project2/epm-3.7-source.tar.gz --enable-verbose --without-stlport --enable-category-b --enable-wiki-publisher --enable-opengl --enable-dbus --enable-gstreamer --enable-bundled-dictionaries --with-package-format=archive
	make -f Makefile clean && \
	make -f Makefile " 2>&1 |tee log

error: pathspec 'openoffice/up.sh' did not match any file(s) known to git