#!/bin/bash
# build-persistent-devbox.sh
# Persistent Fedora Minimal-based devbox with SSH, Git, and GitOps secrets (immutable config files)

set -euo pipefail

IMG_NAME="analytics-backend-workspace"
DEV_USER=devuser
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 && pacman -Scc --noconfirm && \
  groupadd secproc && useradd -ms /bin/zsh -G secproc $DEV_USER && \
  mkdir -p $SECURE && chmod -R 500 $SECURE && \
  mkdir /app && chmod 700 /app && chown $DEV_USER:$DEV_USER /app
"
# copy start script
buildah copy "$ctr" start.sh $DEV_HOME/start.sh
# copy zshrc, neovim and tmux setup
buildah copy "$ctr" zshrc $DEV_HOME/.zshrc
buildah copy "$ctr" config $DEV_HOME/.config

# copy ssh setup
buildah copy "$ctr" ssh $SECURE/ssh

# zsh and tmux config (immutable)
buildah run "$ctr" -- chown -R $DEV_USER:$DEV_USER $DEV_HOME
buildah run --user $DEV_USER "$ctr" -- nvim --headless "+Lazy! sync" +qa
buildah run --user $DEV_USER "$ctr" -- nvim --headless "+Lazy! sync" +qa
buildah run --user $DEV_USER "$ctr" -- nvim --headless "+Lazy! sync" +qa

# 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 '["/home/devuser/start.sh"]' \
  "$ctr"

buildah commit "$ctr" $IMG_NAME

echo "✅ $IMG_NAME built."
