#!/bin/bash

set -euo pipefail

IMG_NAME="analytics-backend-workspace"
DEV_USER=devuser
DEV_UID=1001
DEV_GID=1001
SECURE=/opt/secure
DEV_HOME=/home/$DEV_USER

ctr=$(buildah from archlinux)

buildah run "$ctr" -- bash -c "\
  pacman -Sy --noconfirm && pacman -S --noconfirm --needed base-devel neovim git zsh tmux \
  nodejs python podman fzf fd ripgrep jdk-openjdk zsh-completions zsh-syntax-highlighting \
  lazygit zsh-autosuggestions luarocks python-pynvim npm bash-completion tree-sitter-cli \
  lua51 openssh && pacman -Scc --noconfirm && groupadd secproc && groupadd -g $DEV_GID $DEV_USER && \
  useradd -ms /bin/zsh -G secproc -u $DEV_UID -g $DEV_GID $DEV_USER && mkdir -m 511 -p $SECURE
"

# copy start script, zshrc, neovim, tmux setup and ssh setup
buildah copy --chown $DEV_USER:$DEV_USER "$ctr" ./home/. $DEV_HOME
buildah copy "$ctr" 00-allow-git.conf /etc/ssh/ssh_config.d/

# configure lazyvim
buildah run --user $DEV_USER "$ctr" -- bash -c "\
  nvim --headless \"+Lazy! sync\" +qa && sleep 1 && \
  nvim --headless \"+Lazy! sync\" +qa && sleep 1 && \
  nvim --headless \"+Lazy! sync\" +qa && \
  mkdir -p $DEV_HOME/.ssh && ssh-keyscan -p 2222 10.88.0.1 >> ~/.ssh/known_hosts && \
  ssh-keyscan -p 22 github.com >> ~/.ssh/known_hosts
"

# lock the files
buildah run "$ctr" -- bash -c "\
  chmod 750 $DEV_HOME/start.sh \
  $DEV_HOME/.config/lazygit/config.yml \
  $DEV_HOME/.config/nvim/lua/config/lazy.lua \
  $DEV_HOME/.config/nvim/lazyvim.json \
  $DEV_HOME/.config/nvim/lazy-lock.json \
  $DEV_HOME/.config/nvim/init.lua \
  $DEV_HOME/.config/nvim/README.md \
  $DEV_HOME/.config/nvim/LICENSE \
  $DEV_HOME/.config/tmux/tmux.conf \
  $DEV_HOME/.config/tmux/tmux.conf.local \
  $DEV_HOME/.config/zsh/fzf-git.sh && \
  chown root:secproc $DEV_HOME/start.sh \
  $DEV_HOME/.config/lazygit/config.yml \
  $DEV_HOME/.config/nvim/lua/config/lazy.lua \
  $DEV_HOME/.config/nvim/lazyvim.json \
  $DEV_HOME/.config/nvim/lazy-lock.json \
  $DEV_HOME/.config/nvim/init.lua \
  $DEV_HOME/.config/nvim/README.md \
  $DEV_HOME/.config/nvim/LICENSE \
  $DEV_HOME/.config/tmux/tmux.conf \
  $DEV_HOME/.config/tmux/tmux.conf.local \
  $DEV_HOME/.config/zsh/fzf-git.sh && \
  chmod -R 750 $DEV_HOME/.config/zsh/ohmyzsh && \
  chown -R root:secproc $DEV_HOME/.config/zsh/ohmyzsh
"

buildah config \
  --user $DEV_USER \
  --workingdir /app \
  --env CONTAINER_HOST=unix:///run/podman/podman.sock \
  --cmd "[\"$DEV_HOME/start.sh\"]" \
  "$ctr"

buildah commit "$ctr" $IMG_NAME

echo "✅ $IMG_NAME built."
