// SPDX-License-Identifier: GPL-2.0-only
/*
 *  ppm/src/cmd/init.c
 *
 *  Copyright (C) 2026 Project Tick
 */

#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#include "../cli.h"
#include "../util/log.h"

static const char TEMPLATE[] =
    "# ppm.toml — package manifest\n"
    "# Documentation: https://git.projecttick.org/project-tick\n"
    "\n"
    "[package]\n"
    "name    = \"%s\"\n"
    "version = \"0.1.0\"\n"
    "summary = \"\"\n"
    "license = \"GPL-2.0-only\"\n"
    "\n"
    "[source]\n"
    "# url and hash become required when you publish to the registry.\n"
    "# url  = \"https://example.org/%s-0.1.0.tar.zst\"\n"
    "# hash = \"sha512:...\"\n"
    "\n"
    "[dependencies]\n"
    "# hello = \"^1.0\"\n";

int ppm_cmd_init(int argc, char **argv) {
    const char *name = (argc > 1) ? argv[1] : "my-package";

    if (access("ppm.toml", F_OK) == 0) {
        ppm_error("ppm.toml already exists in the current directory");
        return 1;
    }

    FILE *f = fopen("ppm.toml", "wxe");
    if (!f) {
        ppm_error("could not create ppm.toml: %s", strerror(errno));
        return 1;
    }
    fprintf(f, TEMPLATE, name, name);
    fclose(f);

    ppm_info("wrote ppm.toml for package '%s'", name);
    return 0;
}
