#!/usr/bin/env bash

CONTAINER_OS=ubuntu
CONTAINER_VERSION=18.04
CONTAINER_NAME=$(basename `git rev-parse --show-toplevel`)

function cprint {
	ERR='\033[0;31m'
	OK='\033[0;32m'
	INFO='\033[0;33m'
	END='\033[0m'
	while IFS= read -r L; do
	case "${1}" in 
		err) echo -e "LXDBuild ${ERR}Error: ${L}${END}";;
		ok) echo -e "LXDBuild ${OK}${L}${END}";;
		info) echo -e "LXDBuild ${INFO}${L}${END}";;
	esac
	done < <(printf "%s\n" "${2}")
}

function container_sh {
	if [ $# -eq 1 ]; then
		cprint "info" "${1}"
	fi
	lxc exec ${CONTAINER_NAME} -- sh -c "${1}"
	return $?
}

function container_home {
	container_sh "echo $(echo '${HOME}')" 1
	return $?
}

function container_snap_sh {
	container_sh "cd $(container_home)/${CONTAINER_NAME} && ${1}"
	return $?
}

function check_installed {
	cprint "ok" "Checks if ${1} '${2}' is installed"

	case ${1} in
		dpkg) CHECK="$(dpkg-query -W --showformat='${Status}\n' ${2})";;
		snap) CHECK="$(snap list ${2})";;
	esac

	if [ $? -ne 0 ]; then 
		if [ $# -eq 3  ]; then
			cprint "err" "Missing ${2}: Exiting.";
			exit 1
		fi
		cprint "err" "Missing ${2}."
		while true; do
			read -p "Install? Y/N: " A
			case ${A} in
				[Yy]* ) 
					if [ "${1}" == "dpkg" ]; then
						sudo apt install "${2}"
					elif [ "${1}" == "snap" ]; then
						sudo snap install "${2}"
					fi
					break;;
				[Nn]* ) echo "no"; break;;
				* ) echo "Unknown";;
			esac
		done
		check_installed "${1}" "${2}" "test"
		return $?
	else
		cprint "ok" "${CHECK}"
		return 0
	fi
}

function init_container {
	RETRY=$( [ $# -eq 2 ] && echo 1 || echo "0" )
	if [ $(lxc list "${CONTAINER_NAME}" | grep "${CONTAINER_NAME}" | wc -l) -eq 0 ]; then 
		lxc launch "${CONTAINER_OS}:${CONTIANER_VERSION}" "${CONTAINER_NAME}"
		RET=$?
		if [ ${RET} -ne 0 ] && [ "${RETRY}" -eq 0 ]; then
			cprint "err" "${RET}|${RETRY}Must init LXD"
			lxd init
			init_container "false" 
		elif [ ${RET} -ne 0 ]; then
			cprint "err" "${RET} Can not init LDX. Exiting."
			exit 1
		fi

	else
		if [ $(lxc info "${CONTAINER_NAME}" | grep "Running" | wc -l) -eq 0 ]; then
			lxc start "${CONTAINER_NAME}"
		fi
	fi 
	container_sh "echo '* Container initialized'"
	if [ $? -ne 0 ]; then
		cprint "err" "Can not init container ${CONTAINER_NAME}. Exiting."
		exit 1
	fi
	return 0;
}

if [ "${CONTAINER_NAME}" != "$(basename $(pwd))" ]; then
	cprint "err" "Run script from root folder of project"
	exit 1
fi

CURRF="$(md5sum "${0}")"

git pull

if [ "${CURRF}" != "$(md5sum "${0}")" ]; then
	cprint "File changes on last pull. Restarting..."
	${SELF}
	exit 1
fi


check_installed "dpkg" "snapd"
check_installed "snap" "lxd"
init_container

while true; do
	container_sh "ping -c 1 google.no 2> /dev/null"
	[ $? -eq 0 ] && break || cprint "info" "Waiting for network"
done

cprint "info" "Updating container"
container_sh "apt update && apt upgrade -y && apt dist-upgrade -y"

cprint "info" "Looking for snapcraft"
container_sh "snap list snapcraft"

if [ $? -ne 0 ]; then
	cprint "ok" " - Installing snapcraft"
	container_sh "snap install snapcraft --classic"
fi

container_snap_sh 'ls'
if [ $? -ne 0 ]; then
	cprint "info" "Pushing $(pwd) to ${CONTAINER_NAME}:$(container_home)"
	lxc file push "$(pwd)" "${CONTAINER_NAME}/$(container_home)" -rq
else
	cprint "Pulling repo"
	container_snap_sh "git pull"
fi

TAG=$(git tag | tail -n 1)
while true; do 
	read -p "Check out latest tag ${TAG}? Y=yes, M=master, Enter=no change: " A
	case ${A} in 
		[Yy]* ) container_snap_sh "git checkout ${TAG}"; break;;
		[Mm]* ) container_snap_sh "git checkout master"; break;;
		* ) cprint "info" "Not checking out anything"; break;;
	esac
done

cprint "info" "Building snap"
RET=-1
if [ "$(container_sh "ls $(container_home)/${CONTAINER_NAME} | grep prime | wc -l")" == "1" ]; then
	container_snap_sh "snapcraft prime --destructive-mode"
	if [ $? -ne 0 ]; then
		container_snap_sh "snapcraft clean --destructive-mode"
		container_snap_sh "snapcraft --destructive-mode"
		RET=$?
	fi
else
	container_snap_sh "snapcraft --destructive-mode"
	RET=$?
fi
if [ ${RET} -eq 0 ]; then
	FILE=$(container_snap_sh "ls | grep .snap --max-count=1")
	lxc file pull "${CONTAINER_NAME}/$(container_home)/${CONTAINER_NAME}/${FILE}" "$(pwd)"
else
	cprint "err" "Failed to build snap"
fi