#!/bin/sh
set -u

# Variables
CADDY=/usr/sbin/caddy
: "${SVDIR:=$HOME/.local/service}"
APK_UPGRADE="doas apk upgrade --update-cache --available"
CONTAINER_PRUNE="podman image prune"

# Colours
if [ -t 1 ] && [ -z "${NO_COLOR:-}" ] ; then
	BLUE='\033[1;34m'
	GREEN='\033[1;32m'
	RED='\033[1;31m'
	RESET='\033[0m'
else
	BLUE='' GREEN='' RED='' RESET=''
fi
PREFIX="${BLUE}[upgrade-system]${RESET}"

# Functions
log() { printf "%b %b\n" "$PREFIX" "$*"; }
log_ok() { printf "%b %b\n" "$PREFIX" "${GREEN}$*${RESET}"; }
log_err() { printf "%b %b\n" "$PREFIX" "${RED}$*${RESET}"; }
print_help() {
	printf "upgrade-system (v0.1)\n\n"
	printf "Usage: upgrade-system [-cs] (-y)\n\n"
	printf "Script to simplify updating the system and/or containers.\n\n"
	printf "\t-c\tUpdate the containers\n"
	printf "\t-s\tUpdate the system packages\n"
	printf "\t-y\tDon't require interaction\n"
}

# Getopts
c=0; s=0; y=0
while getopts "csy" opt ; do
  case "$opt" in
    c) c=1;;
    s) s=1;;
    y) y=1;;
    \?) print_help; exit 1;;
  esac
done
shift $((OPTIND-1))

if [ $c -eq 0 ] && [ $s -eq 0 ] ; then
	print_help
	exit 1
fi

# The interactive flag :)
if [ "$y" -eq 1 ] ; then
	CONTAINER_PRUNE="$CONTAINER_PRUNE --force"
else
	APK_UPGRADE="$APK_UPGRADE --interactive"
fi

# Making sure we aren't root
if [ "$(id -u)" -eq 0 ] ; then
	log_err "Run this script as a user!"
	exit 1
fi

# Upgrade system packages
if [ "$s" -eq 1 ] ; then
	log "Updating & Upgrading packages..."
	if $APK_UPGRADE ; then
		log_ok "Succesfully upgraded packages!"
	else
		log_err "Update failed or aborted!"
		exit 1
	fi

	# Give caddy the the correct rights after upgrade
	log "Making sure caddy has the correct rights..."
	if getcap "$CADDY" | grep -q 'cap_net_bind_service=ep' ; then
		log_ok "Caddy already has the correct rights."
	else
		log "Setcapping caddy..."
		if doas setcap cap_net_bind_service=+ep "$CADDY" ; then
			log_ok "Setcapping succesful!"
		else
			log_err "Setcapping failed!"
			exit 1
		fi
	fi
fi

# Upgrade containers
if [ "$c" -eq 1 ] ; then
	log "Pulling the newest images..."
	for image in $(podman image list --format '{{.Repository}}:{{.Tag}}') ; do
		podman pull "$image"
	done

	# Restarting containers
	log "Restarting the pods..."
	for pod in "$SVDIR"/* ; do
		[ ! -f "$pod/down" ] && sv restart "$pod"
	done

	# Pruning old images
	log "Pruning old images..."
	$CONTAINER_PRUNE
fi

# Suggest rebooting system
if [ "$s" -eq 1 ] ; then
       log "You should probably reboot your system."
fi

exit 0
