# Bastillefile: headscale-admin
#
# This template sets up the Headscale Admin UI in a Bastille Jail.
# It uses Caddy to serve the static frontend files.
#
# This Baastillefile uses the specific version v0.24.9 and relies on the
# original Caddyfile from the repository. The built files are copied
# into an `/app/admin` directory to be served by Caddy.

# Ensure the jail has network access and pkg is updated
CMD pkg update && pkg upgrade -y
CMD pkg install -y nano git node npm caddy

# Set up the shell and home directory for the build process
ENV HOME /root
ENV SHELL /bin/csh

# --- HEADSCALE ADMIN UI SETUP ---
# Clone the Headscale Admin UI repository from GitHub
CMD git clone --depth 1 https://github.com/juanfont/headscale-admin.git /root/headscale-admin
CMD cd /root/headscale-admin

# Check out the specific working version to avoid future issues
CMD git checkout tags/v0.24.9

# Install Node.js dependencies
CMD /usr/local/bin/npm install

# Build the frontend for production.
# This command generates the static HTML, CSS, and JavaScript files in the `build` directory.
CMD /usr/local/bin/npm run build

# --- CADDY WEB SERVER CONFIGURATION ---
# Create the necessary directories
CMD mkdir -p /app/admin
CMD mkdir -p /usr/local/etc/caddy/
CMD mkdir -p /var/log/caddy/

# Move the original Caddyfile to the correct location
CMD mv /root/headscale-admin/Caddyfile /usr/local/etc/caddy/Caddyfile

# Copy the built frontend files into the `/app/admin` directory.
# Caddy's Caddyfile is configured to serve from `/app`, so the files
# will be available under the `/admin` path.
CMD cp -r build/* /app/admin

# Correct permissions for Caddy to write logs
CMD chown -R www:www /var/log/caddy
CMD chown -R www:www /app

# Enable and start the Caddy service inside the jail
SYSRC caddy_enable="YES"
SERVICE caddy start