/*    
 *     createdb -- create a postgres database
 */
#include <stdio.h>
#include <sys/types.h>
#include <sys/file.h>

#ifndef sprite
#include <sys/signal.h>
#endif /* !sprite */

#include "tmp/c.h"
#undef palloc
#undef pfree

#include "tmp/daemon.h"
#include "strings.h"
#include "tmp/libpq-fe.h"
#include "storage/fd.h"
#include "installinfo.h"

RcsId("$Header: RCS/createdb.c,v 1.1 91/03/07 01:46:39 kemnitz Exp $");

extern char     *getenv();

extern char     *PQhost;     /* machine on which the backend is running */
extern char     *PQport;     /* comm. port with the postgres backend. */

extern char *optarg;
extern int optind,opterr;

main(argc,argv)
     int argc;
     char **argv;
{
    char *dbname;
    char *pstring;
    char *dir;
    char buf[100];
    int  errflag = 0;
    char c;
    char *p, *p1;
    int  nstriping;
    int  i;
    int  handle_striping = 0, len;

    /* ----------------
     *    process command line options
     * ----------------
     */
    while ((c = getopt(argc, argv, "p:h:")) != EOF) {
    switch(c) {
        case 'h':
            PQhost = optarg;
            break;        
        case 'p':
            PQport = optarg;
            break;
        case '?' :
            errflag++;
        }
    }

    if (errflag) {
        fprintf(stderr, "usage: %s [-p port] [-h host] dbname\n", *argv);
        exit (1);
    }

    /* ----------------
     *    get the name of the database to use
     * ----------------
     */
    if ((dbname = argv[optind]) == NULL) {
    /* find default database */
    /* defaults database name to username. */
    if ((dbname = getenv("DATABASE")) == NULL)  
        dbname = getenv("USER");
    }

    /* open a connection to the backend */
    PQsetdb("template1");

    /* remove the tuple from pg_database */
    sprintf(buf, "createdb %s", dbname);
    pstring = PQexec(&buf[0]);     

    if (*pstring == 'E') {
        fprintf(stdout, "%s\ncreatedb failed", ++pstring);
        exit(1);
    }

    /* shut down communications */
    PQfinish();

    exit(0);
}
