#!/usr/bin/env bash

create-dotenv() {
    if [[ -z "$1" ]]; then
        echo "\$1/env is empty."
        return 1
    fi
    if [[ -z "$2" ]]; then
        echo "\$2/template is empty."
        return 1
    fi

    local global_flag=false
    if [[ "$3" == "-g" || "$3" == "--global" ]]; then
        global_flag=true
    fi

    local env_name="$1"
    local template="$2"
    local env_filename="${env_name}.env"
    local template_file="$HOME/taskfile.build/templates/${template}.env.template"
    local TASK_DOTENV_DIR="${TASK_DOTENV_DIR:-$HOME/.config/taskfile.build}"

    if [[ ! -f "$template_file" ]]; then
        echo "Template not found: $template_file"
        return 1
    fi

    local env_filepath
    if [[ "$global_flag" == true ]]; then
        init-dotenv-dir
        env_filepath="$TASK_DOTENV_DIR/$env_filename"
    else
        env_filepath="$PWD/$env_filename"
    fi

    if [[ "$env_filename" == *secrets.env ]]; then
        if [[ ! -f ".sops.yaml" ]]; then
            echo "Error: .sops.yaml not found. Run init-dotenv-sops first."
            return 1
        fi
    fi

    if [[ -f "$env_filepath" ]]; then
        echo "Env file already exists: $env_filepath"
        return 1
    fi

    echo "Init .env file: $env_filepath"
    cp "$template_file" "$env_filepath"

    if [[ "$env_filename" == *secrets.env ]]; then
        if ! sops --encrypt --in-place "$env_filepath"; then
            echo "Encryption failed; removing $env_filepath"
            rm -f "$env_filepath"
            return 1
        fi
        echo "Encrypted $env_filepath with sops."
    fi

    echo "Edit with: task edit-dotenv $env_name"
}
crd() {
    create-dotenv "$@"
}