#!/bin/sh
# Install Kizashi on a server, or update it to the newest version.
#   curl -fsSL https://kizashi.systems/dl/install.sh | sudo sh -s monitor.example.com
#   curl -fsSL https://kizashi.systems/dl/install.sh | sudo sh    # update, any time
# (or download it first and run: sudo sh install.sh [name]). It also installs
# the kizashi command: sudo kizashi update, status, logs, backup and so on.
# It needs 64-bit Linux, a DNS name that points at the server, and ports 80
# and 443 open to it. On Ubuntu and Debian, and on RHEL and its relatives
# (AlmaLinux, Rocky Linux), it installs what else it needs: Docker with the
# Compose plugin (from Docker's own packages) and a few small tools, and it
# opens ports 80 and 443 in firewalld when that is running. Everything goes in
# /opt/kizashi (KIZASHI_DIR): the Compose files, .env with the installation's
# secrets, and ./backups. The database lives in a Docker volume.
# This file is published to kizashi.systems by scripts/publish-download.sh.
set -eu
base=${KIZASHI_DOWNLOAD:-https://kizashi.systems/dl}
dir=${KIZASHI_DIR:-/opt/kizashi}
domain=${1:-}

main() {
# Commands must not read the rest of this script when it is piped into sh.
exec </dev/null

say() { printf '%s\n' "$*"; }
die() {
	printf 'Kizashi install: %s\n' "$*" >&2
	exit 1
}

[ "$(id -u)" = 0 ] || die "run it as root (with sudo)"
[ "$(uname -s)" = Linux ] && [ "$(uname -m)" = x86_64 ] || die "Kizashi runs on 64-bit (x86_64) Linux; this is $(uname -s) $(uname -m)"
new=1
if [ -f "$dir/.env" ]; then
	new=0
elif [ -z "$domain" ]; then
	die "give the name the server will be reached at, for example: curl -fsSL https://kizashi.systems/dl/install.sh | sudo sh -s monitor.example.com"
else
	printf '%s' "$domain" | grep -Eq '^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)+$' ||
		die "\"$domain\" is not a DNS name (for example monitor.example.com)"
fi
# The package manager: apt (Ubuntu, Debian) or dnf (RHEL, AlmaLinux, Rocky).
pm=
if command -v apt-get >/dev/null; then
	pm=apt
elif command -v dnf >/dev/null; then
	pm=dnf
fi
export DEBIAN_FRONTEND=noninteractive
# Docker's own package repository for dnf (its RHEL packages suit the relatives too).
docker_repo() {
	[ -f /etc/yum.repos.d/docker-ce.repo ] ||
		curl -fsSL -o /etc/yum.repos.d/docker-ce.repo https://download.docker.com/linux/rhel/docker-ce.repo ||
		die "cannot reach download.docker.com"
}

missing=
for c in curl openssl sha256sum gzip tar; do
	command -v $c >/dev/null || missing="$missing $c"
done
if [ -n "$missing" ]; then
	[ -n "$pm" ] || die "please install:$missing"
	say "Installing:$missing"
	if [ $pm = apt ]; then
		apt-get update -qq >/dev/null && apt-get install -y -qq curl openssl ca-certificates coreutils gzip tar >/dev/null ||
			die "could not install:$missing"
	else
		# Only what is missing: minimal images have curl-minimal and coreutils-single.
		dnf install -y -q $(printf '%s\n' $missing | sed 's/^sha256sum$/coreutils/') >/dev/null ||
			die "could not install:$missing"
	fi
fi
if command -v docker >/dev/null && docker --version 2>/dev/null | grep -qi podman; then
	die "the docker command here is Podman's (podman-docker); Kizashi needs Docker itself. Remove Podman first (dnf remove podman-docker podman buildah runc), then run this again"
fi
if ! command -v docker >/dev/null; then
	[ -n "$pm" ] || die "Docker is not installed. Install it with: curl -fsSL https://get.docker.com | sudo sh"
	say "Installing Docker (this takes a minute or two)"
	if [ $pm = apt ]; then
		curl -fsSL https://get.docker.com -o /tmp/get-docker.sh && sh /tmp/get-docker.sh >/tmp/get-docker.log 2>&1 ||
			die "could not install Docker; see /tmp/get-docker.log"
		rm -f /tmp/get-docker.sh
	else
		docker_repo
		dnf install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin >/tmp/get-docker.log 2>&1 ||
			die "could not install Docker; see /tmp/get-docker.log (if it conflicts with Podman, remove Podman first: dnf remove podman buildah runc)"
	fi
fi
if ! docker compose version >/dev/null 2>&1; then
	[ -n "$pm" ] || die "the Docker Compose plugin is not installed (package docker-compose-plugin)"
	say "Installing the Docker Compose plugin"
	if [ $pm = apt ]; then
		apt-get update -qq >/dev/null
		apt-get install -y -qq docker-compose-plugin >/dev/null 2>&1 || apt-get install -y -qq docker-compose-v2 >/dev/null 2>&1 ||
			die "could not install the Docker Compose plugin"
	else
		docker_repo
		dnf install -y -q docker-compose-plugin >/dev/null 2>&1 || die "could not install the Docker Compose plugin"
	fi
fi
if ! docker info >/dev/null 2>&1; then
	systemctl enable --now docker >/dev/null 2>&1 || service docker start >/dev/null 2>&1 || true
	i=0
	until docker info >/dev/null 2>&1; do
		i=$((i + 1))
		[ $i -lt 30 ] || die "Docker is not running (systemctl start docker)"
		sleep 1
	done
fi

if [ $new = 1 ]; then
	if command -v ss >/dev/null && ss -ltnH 2>/dev/null | awk '{print $4}' | grep -Eq '[:.](80|443)$'; then
		die "something on this server already uses port 80 or 443 (a web server?); Kizashi needs both"
	fi
	# firewalld (on by default on RHEL and its relatives) blocks the web ports.
	if command -v firewall-cmd >/dev/null && firewall-cmd --state >/dev/null 2>&1; then
		say "Opening ports 80 and 443 in the firewall"
		for p in '' --permanent; do
			firewall-cmd -q $p --add-port=80/tcp --add-port=443/tcp --add-port=443/udp ||
				say "Note: could not open ports 80 and 443 in firewalld; open them yourself"
		done
	fi
	getent hosts "$domain" >/dev/null || say "Note: $domain does not resolve yet. Point it at this server, or the HTTPS certificate cannot be issued."
fi

version=$(curl -fsSL "$base/latest.txt") || die "cannot reach $base"
printf '%s' "$version" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$' || die "unexpected version \"$version\" from $base"
# The kizashi command (sudo kizashi update, and so on), refreshed on every run.
# Written to a new file and renamed into place: "kizashi update" is that
# command, still running while it runs this installer, and a shell reads its
# script as it goes, so rewriting the file under it would run whatever new
# text lands where it left off.
cli=$(mktemp /usr/local/bin/.kizashi.XXXXXX)
{
	printf '#!/bin/sh\n# Run Kizashi on this server; written by its installer (%s/install.sh).\n' "$base"
	printf 'dir=%s\nbase=%s\n' "$dir" "$base"
	cat <<-'END'
		set -eu
		# All in main, called on the last line, then exit: the shell has read
		# the whole script before it runs any of it.
		main() {
		usage() {
			cat <<-'TEXT'
				Usage: sudo kizashi <command>
				  update     update to the newest version (your settings and data are kept)
				  version    the installed and the newest version
				  status     what's running
				  logs       follow Kizashi's log (Ctrl+C to stop)
				  backup     back up the database now, into the backups folder
				  restart    restart Kizashi
				  stop       stop everything (your data is kept)
				  start      start everything again
			TEXT
		}
		case ${1:-} in
		'' | help | -h | --help) usage; exit 0 ;;
		esac
		[ "$(id -u)" = 0 ] || { echo "run it as root: sudo kizashi $1" >&2; exit 1; }
		cd "$dir"
		case $1 in
		update) curl -fsSL "$base/install.sh" | KIZASHI_DIR="$dir" KIZASHI_DOWNLOAD="$base" sh ;;
		version)
			echo "installed: $(cat .version 2>/dev/null || echo unknown)"
			echo "newest:    $(curl -fsSL "$base/latest.txt" 2>/dev/null || echo "unknown (cannot reach $base)")"
			;;
		status) docker compose ps --format 'table {{.Service}}\t{{.Status}}' ;;
		logs) docker compose logs -f --tail 100 core ;;
		backup) docker compose exec -T backup backup-db.sh now ;;
		restart) docker compose restart core ;;
		stop) docker compose down ;;
		start) docker compose up -d --no-build ;;
		web-update)
			# Run by kizashi-update.service when an admin presses Update now in
			# the web app: a database backup, then this installer. What it does
			# goes to update/progress, which the web app reads.
			p=$dir/update/progress
			rm -f "$dir/update/request/update-now"
			st() {
				{ printf 'state=%s\nat=%s\n' "$1" "$(date -u +%Y-%m-%dT%H:%M:%SZ)"; [ -z "${2:-}" ] || printf '%s\n' "$2"; } >"$p/status.tmp"
				mv -f "$p/status.tmp" "$p/status"
			}
			st running
			t=$(mktemp)
			if {
				echo "== Backing up the database"
				docker compose exec -T backup backup-db.sh now &&
					echo "== Downloading the installer" &&
					curl -fsSL -o "$t" "$base/install.sh" &&
					echo "== Updating" &&
					KIZASHI_DIR="$dir" KIZASHI_DOWNLOAD="$base" sh "$t"
			} >"$p/update.log" 2>&1; then
				st done "version=$(cat .version 2>/dev/null)"
			else
				st failed "message=$(grep -v '^$' "$p/update.log" | tail -n 1 | cut -c1-300)"
			fi
			rm -f "$t"
			;;
		*) usage >&2; exit 1 ;;
		esac
		}
		main "$@"; exit
	END
} >"$cli"
chmod 755 "$cli"
mv -f "$cli" /usr/local/bin/kizashi
# sudo on RHEL and its relatives leaves /usr/local/bin out of the PATH.
[ "$pm" != dnf ] || ln -sf /usr/local/bin/kizashi /usr/bin/kizashi

if [ $new = 0 ] && [ "$(cat "$dir/.version" 2>/dev/null)" = "$version" ] && docker image inspect "gotrtg:$version" >/dev/null 2>&1; then
	say "Kizashi $version is installed already, the newest version."
	exit 0
fi

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
say "Downloading Kizashi $version"
curl -fsSL -o "$tmp/SHA256SUMS" "$base/$version/SHA256SUMS"
curl -fsSL -o "$tmp/kizashi-files.tar.gz" "$base/$version/kizashi-files.tar.gz"
curl -fL --progress-bar -o "$tmp/kizashi-image.tar.gz" "$base/$version/kizashi-image.tar.gz"
(cd "$tmp" && sha256sum -c --quiet SHA256SUMS) || die "the download is damaged; run the installer again"

say "Loading the program"
gzip -dc "$tmp/kizashi-image.tar.gz" | docker load -q >/dev/null
docker tag "gotrtg:$version" gotrtg:current
mkdir -p "$dir"
tar -xzf "$tmp/kizashi-files.tar.gz" -C "$dir"

# The updater behind Update now in the web app. The core may only drop a
# file into update/request (its own user's folder); systemd sees it and runs
# kizashi web-update as root, which backs up the database and runs this
# installer, writing its progress into update/progress (root's, read-only to
# the core). The core cannot pick a version or run anything.
install -d -m 755 "$dir/update" "$dir/update/progress"
install -d -m 700 -o 65532 -g 65532 "$dir/update/request" # the core's user (distroless nonroot)
if [ -d /run/systemd/system ] && command -v systemctl >/dev/null; then
	cat >/etc/systemd/system/kizashi-update.path <<-END
		[Unit]
		Description=Kizashi: update when an admin asks in the web app
		[Path]
		PathExists=$dir/update/request/update-now
		Unit=kizashi-update.service
		[Install]
		WantedBy=multi-user.target
	END
	cat >/etc/systemd/system/kizashi-update.service <<-END
		[Unit]
		Description=Kizashi: back up and update to the newest version (asked in the web app)
		[Service]
		Type=oneshot
		ExecStart=/usr/local/bin/kizashi web-update
		TimeoutStartSec=1h
	END
	systemctl daemon-reload
	if systemctl enable --now kizashi-update.path >/dev/null 2>&1; then
		echo 1 >"$dir/update/progress/updater"
	else
		rm -f "$dir/update/progress/updater"
		say "Note: could not start the updater (kizashi-update.path); update with sudo kizashi update"
	fi
fi

if [ $new = 1 ]; then
	umask 077
	cat >"$dir/.env" <<-END
		GOTRTG_DB_PASSWORD=$(openssl rand -hex 24)
		GOTRTG_DB_APP_PASSWORD=$(openssl rand -hex 24)
		GOTRTG_MASTER_KEY=$(openssl rand -base64 32)

		# HTTPS (Caddy) on ports 80 and 443
		COMPOSE_FILE=docker-compose.yml:docker-compose.prod.yml
		GOTRTG_DOMAIN=$domain
		GOTRTG_PUBLIC_URL=https://$domain
	END
	umask 022
fi

say "Starting Kizashi"
cd "$dir"
docker compose up -d --no-build --remove-orphans --quiet-pull || {
	docker compose ps
	die "Kizashi did not start; run this again, or see: cd $dir && docker compose logs"
}
docker compose up -d --no-build --force-recreate --no-deps backup >/dev/null 2>&1
i=0
until curl -fsS http://127.0.0.1:8080/healthz >/dev/null 2>&1; do
	i=$((i + 1))
	[ $i -lt 90 ] || {
		docker compose ps
		die "Kizashi did not start; see: cd $dir && docker compose logs core"
	}
	sleep 2
done
printf '%s\n' "$version" >"$dir/.version"
# Keep the three newest versions (to go back, see the download page).
docker images gotrtg --format '{{.Tag}}' | grep '^v' | sort -V | head -n -3 | while read -r t; do
	docker rmi -f "gotrtg:$t" >/dev/null 2>&1 || true
done

url=$(grep '^GOTRTG_PUBLIC_URL=' .env | cut -d= -f2-)
if [ $new = 1 ]; then
	code=$(docker compose logs core 2>/dev/null | grep -o 'setup_code=[A-Z0-9-]*' | tail -1 | cut -d= -f2)
	say ""
	say "Kizashi $version is running."
	say "  1. Open ${url:-https://$domain} (the certificate can take a minute)."
	say "  2. Enter the setup code ${code:-(see: docker compose logs core | grep setup_code)} and create your admin account."
	say "  3. Keep a copy of $dir/.env somewhere safe: its master key is needed to restore a backup."
	say "Your 30-day trial (up to 50 devices) starts now. Enter a license key under Settings → License."
	say "Later, update with: sudo kizashi update (sudo kizashi lists the other commands)."
else
	say "Kizashi is updated to $version: ${url:-}"
fi
}

main "$@"
