#!/usr/bin/env sh

SANDBOXES_DIR=$HOME/sandbox
TEMPLATES_DIR=$XDG_DATA_HOME/devenv/templates

list_templates() {
    echo "The available templates are:"
    ls $TEMPLATES_DIR
}

check_template () {
    TEMPLATE=$1
    if [ -z "$TEMPLATE" ]; then
        echo "No template given"
        list_templates
        return 1
    elif [ ! -e "$TEMPLATES_DIR/$TEMPLATE" ]; then
        echo "The given template '$TEMPLATE' doesn't exist!"
        list_templates
        return 1
    fi
}

devenv_install() {
    TEMPLATE=$1
    install -m 644 $TEMPLATES_DIR/$TEMPLATE/* ./
    echo "use flake . --impure" > .envrc
    direnv allow
}

devenv_init() {
    TEMPLATE=$1
    if ! check_template $TEMPLATE ; then
        return 1
    fi
    devenv_install $TEMPLATE
}

devenv_sandbox() {
    DIRECTORY=$1
    if [ -z "$DIRECTORY" ]; then
        show_help_sandbox
        return 1
    fi
    SANDBOX_DIR="$SANDBOXES_DIR/$DIRECTORY"
    TEMPLATE=$2
    if [ -z "$TEMPLATE" ]; then
        TEMPLATE=$DIRECTORY
    fi
    if ! check_template $TEMPLATE; then
        return 1
    fi
    if [ ! -e $SANDBOX_DIR ]; then
        echo "Creating sandbox at $SANDBOX_DIR with template $TEMPLATE"
        mkdir -p $SANDBOX_DIR
        cd $SANDBOX_DIR
        devenv_init $TEMPLATE
    else
        cd $SANDBOX_DIR
    fi
}

show_help_sandbox() {
    echo "Usage: devenv sandbox <directory> [<template>]"
    echo ""
    echo "  directory: The sandbox directory to go to."
    echo "  template: If the directory doesn't exist, the template to use for that sandbox"
    echo "            Defaults to directory if not given."
    echo ""
}

show_help() {
    echo "Usage: devenv <action>"
    echo "Available actions:"
    echo ""
    echo "  init: Initialize a dev env in the current directory"
    echo "  sandbox: Go to a sandbox directory using a template"
    echo ""
}

case "$1" in
    init)
        shift
        devenv_init $@
        ;;
    sandbox)
        shift
        devenv_sandbox $@
        ;;
    *)
        show_help
        ;;
esac
