#!/bin/bash

# SPDX-FileCopyrightText: Copyright (c) 2021 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: MIT
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.

# This is a script to install snap from snap store

set -e

function usage()
{
	if [ -n "${1}" ]; then
		echo "${1}"
	fi

	echo "Usage:"
	echo "${script_name} [options]"
	echo ""
	echo "Available options are:"
	echo ""
	echo "  -h | --help"
	echo "          Show this usage"
	echo ""
	echo "  -i <snap_name> | --install <snap_name>"
	echo "          Install snap package"
	echo ""
	echo "Example:"
	echo "${script_name} -i <snap_name>"
}

function install_snap()
{
	for i in {1..3}; do
	        if ping -c 3 api.snapcraft.io > /dev/null 2>&1; then
			break
		elif [[ "${i}" =~ "3" ]]; then
			echo "ERROR: Cannot connect to snap store."
			exit 1
		else
			sleep 1
	        fi
	done

	for i in {1..3}; do
		if systemctl start snapd; then
			break
		elif [[ "${i}" =~ "3" ]]; then
			echo "ERROR: Cannot start snapd service."
			exit 2
		else
			sleep 1
		fi
	done

	for i in {1..3}; do
		if systemctl start snapd.seeded; then
			break
		elif [[ "${i}" =~ "3" ]]; then
			echo "ERROR: Cannot start snapd.seeded service."
			exit 2
		else
			sleep 1
		fi
	done

	for i in {1..3}; do
		if snap install "${1}"; then
			break
		elif [[ "${i}" =~ "3" ]]; then
			echo "ERROR: Cannot install ${1} snap."
			exit 3
		else
			sleep 1
		fi
	done

	echo "${1} installation is finished."
}

function parse_args()
{
	while [ -n "${1}" ]; do
		case "${1}" in
		-h | --help)
			usage
			exit 0
			;;
		-i | --install)
			[ -n "${2}" ] || usage "Not enough parameters"
			install_snap "${2}"
			exit 0
			;;
		*)
			usage "Unknown option: ${1}"
			exit 0
		;;
		esac
	done
}

script_name="$(basename "${0}")"
parse_args "${@}"
