#!/usr/pkg/bin/python2.7
# -*-python-*-
#
# Copyright (C) 1999-2023 The ViewCVS Group. All Rights Reserved.
#
# By using this file, you agree to the terms and conditions set forth in
# the LICENSE.html file which can be found at the top level of the ViewVC
# distribution or at http://viewvc.org/license-1.html.
#
# For more information, visit http://viewvc.org/
#
# -----------------------------------------------------------------------
#
# administrative program for CVSdb; creates a clean database in
# MySQL 3.22 or later
#
# -----------------------------------------------------------------------
#
# INSTALL-TIME CONFIGURATION
#
# These values will be set during the installation process. During
# development, they will remain None.
#

LIBRARY_DIR = r"/usr/pkg/share/viewvc/lib"
CONF_PATHNAME = r"/usr/pkg/etc/viewvc/viewvc.conf"

# Adjust sys.path to include our library directory
import sys
import os

if LIBRARY_DIR:
  sys.path.insert(0, LIBRARY_DIR)
else:
  sys.path.insert(0, os.path.abspath(os.path.join(sys.argv[0], "../../lib")))

import getopt

if sys.hexversion >= 0x3030000:
  import subprocess
  subprocess.has_timeout = True
else:
  try:
    import subprocess32 as subprocess
    subprocess.has_timeout = True
  except ImportError:
    import subprocess
    subprocess.has_timeout = False

if sys.version_info[0] >= 3:
    def raw_input(prompt=''):
        return input(prompt)

## ------------------------------------------------------------------------
## Stuff common to all schemas
##
DATABASE_SCRIPT_COMMON="""\
DROP DATABASE IF EXISTS <dbname>;
CREATE DATABASE <dbname>;

USE <dbname>;
"""

## ------------------------------------------------------------------------
## Version 0:  The original, Bonsai-compatible schema.
##
DATABASE_SCRIPT_VERSION_0="""\
DROP TABLE IF EXISTS branches;
CREATE TABLE branches (
  id mediumint(9) NOT NULL auto_increment,
  branch varchar(64) binary DEFAULT '' NOT NULL,
  PRIMARY KEY (id),
  UNIQUE branch (branch)
) ENGINE=MyISAM;

DROP TABLE IF EXISTS checkins;
CREATE TABLE checkins (
  type enum('Change','Add','Remove'),
  ci_when datetime DEFAULT '1000-01-01 00:00:00' NOT NULL,
  whoid mediumint(9) DEFAULT '0' NOT NULL,
  repositoryid mediumint(9) DEFAULT '0' NOT NULL,
  dirid mediumint(9) DEFAULT '0' NOT NULL,
  fileid mediumint(9) DEFAULT '0' NOT NULL,
  revision varchar(32) binary DEFAULT '' NOT NULL,
  stickytag varchar(255) binary DEFAULT '' NOT NULL,
  branchid mediumint(9) DEFAULT '0' NOT NULL,
  addedlines int(11) DEFAULT '0' NOT NULL,
  removedlines int(11) DEFAULT '0' NOT NULL,
  descid mediumint(9),
  UNIQUE repositoryid (repositoryid,dirid,fileid,revision),
  KEY ci_when (ci_when),
  KEY whoid (whoid),
  KEY repositoryid_2 (repositoryid),
  KEY dirid (dirid),
  KEY fileid (fileid),
  KEY branchid (branchid)
) ENGINE=MyISAM;

DROP TABLE IF EXISTS descs;
CREATE TABLE descs (
  id mediumint(9) NOT NULL auto_increment,
  description text,
  hash bigint(20) DEFAULT '0' NOT NULL,
  PRIMARY KEY (id),
  KEY hash (hash)
) ENGINE=MyISAM;

DROP TABLE IF EXISTS dirs;
CREATE TABLE dirs (
  id mediumint(9) NOT NULL auto_increment,
  dir varchar(255) binary DEFAULT '' NOT NULL,
  PRIMARY KEY (id),
  UNIQUE dir (dir)
) ENGINE=MyISAM;

DROP TABLE IF EXISTS files;
CREATE TABLE files (
  id mediumint(9) NOT NULL auto_increment,
  file varchar(255) binary DEFAULT '' NOT NULL,
  PRIMARY KEY (id),
  UNIQUE file (file)
) ENGINE=MyISAM;

DROP TABLE IF EXISTS people;
CREATE TABLE people (
  id mediumint(9) NOT NULL auto_increment,
  who varchar(128) binary DEFAULT '' NOT NULL,
  PRIMARY KEY (id),
  UNIQUE who (who)
) ENGINE=MyISAM;

DROP TABLE IF EXISTS repositories;
CREATE TABLE repositories (
  id mediumint(9) NOT NULL auto_increment,
  repository varchar(64) binary DEFAULT '' NOT NULL,
  PRIMARY KEY (id),
  UNIQUE repository (repository)
) ENGINE=MyISAM;

DROP TABLE IF EXISTS tags;
CREATE TABLE tags (
  repositoryid mediumint(9) DEFAULT '0' NOT NULL,
  branchid mediumint(9) DEFAULT '0' NOT NULL,
  dirid mediumint(9) DEFAULT '0' NOT NULL,
  fileid mediumint(9) DEFAULT '0' NOT NULL,
  revision varchar(32) binary DEFAULT '' NOT NULL,
  UNIQUE repositoryid (repositoryid,dirid,fileid,branchid,revision),
  KEY repositoryid_2 (repositoryid),
  KEY dirid (dirid),
  KEY fileid (fileid),
  KEY branchid (branchid)
) ENGINE=MyISAM;
"""

## ------------------------------------------------------------------------
## Version 1:  Adds the 'metadata' table.  Adds 'descid' index to
##             'checkins' table, and renames that table to 'commits'.
##
DATABASE_SCRIPT_VERSION_1="""\
DROP TABLE IF EXISTS branches;
CREATE TABLE branches (
  id mediumint(9) NOT NULL auto_increment,
  branch varchar(64) binary DEFAULT '' NOT NULL,
  PRIMARY KEY (id),
  UNIQUE branch (branch)
) ENGINE=MyISAM;

DROP TABLE IF EXISTS commits;
CREATE TABLE commits (
  type enum('Change','Add','Remove'),
  ci_when datetime DEFAULT '1000-01-01 00:00:00' NOT NULL,
  whoid mediumint(9) DEFAULT '0' NOT NULL,
  repositoryid mediumint(9) DEFAULT '0' NOT NULL,
  dirid mediumint(9) DEFAULT '0' NOT NULL,
  fileid mediumint(9) DEFAULT '0' NOT NULL,
  revision varchar(32) binary DEFAULT '' NOT NULL,
  stickytag varchar(255) binary DEFAULT '' NOT NULL,
  branchid mediumint(9) DEFAULT '0' NOT NULL,
  addedlines int(11) DEFAULT '0' NOT NULL,
  removedlines int(11) DEFAULT '0' NOT NULL,
  descid mediumint(9),
  UNIQUE repositoryid (repositoryid,dirid,fileid,revision),
  KEY ci_when (ci_when),
  KEY whoid (whoid),
  KEY repositoryid_2 (repositoryid),
  KEY dirid (dirid),
  KEY fileid (fileid),
  KEY branchid (branchid),
  KEY descid (descid)
) ENGINE=MyISAM;

DROP TABLE IF EXISTS descs;
CREATE TABLE descs (
  id mediumint(9) NOT NULL auto_increment,
  description text,
  hash bigint(20) DEFAULT '0' NOT NULL,
  PRIMARY KEY (id),
  KEY hash (hash)
) ENGINE=MyISAM;

DROP TABLE IF EXISTS dirs;
CREATE TABLE dirs (
  id mediumint(9) NOT NULL auto_increment,
  dir varchar(255) binary DEFAULT '' NOT NULL,
  PRIMARY KEY (id),
  UNIQUE dir (dir)
) ENGINE=MyISAM;

DROP TABLE IF EXISTS files;
CREATE TABLE files (
  id mediumint(9) NOT NULL auto_increment,
  file varchar(255) binary DEFAULT '' NOT NULL,
  PRIMARY KEY (id),
  UNIQUE file (file)
) ENGINE=MyISAM;

DROP TABLE IF EXISTS people;
CREATE TABLE people (
  id mediumint(9) NOT NULL auto_increment,
  who varchar(128) binary DEFAULT '' NOT NULL,
  PRIMARY KEY (id),
  UNIQUE who (who)
) ENGINE=MyISAM;

DROP TABLE IF EXISTS repositories;
CREATE TABLE repositories (
  id mediumint(9) NOT NULL auto_increment,
  repository varchar(64) binary DEFAULT '' NOT NULL,
  PRIMARY KEY (id),
  UNIQUE repository (repository)
) ENGINE=MyISAM;

DROP TABLE IF EXISTS tags;
CREATE TABLE tags (
  repositoryid mediumint(9) DEFAULT '0' NOT NULL,
  branchid mediumint(9) DEFAULT '0' NOT NULL,
  dirid mediumint(9) DEFAULT '0' NOT NULL,
  fileid mediumint(9) DEFAULT '0' NOT NULL,
  revision varchar(32) binary DEFAULT '' NOT NULL,
  UNIQUE repositoryid (repositoryid,dirid,fileid,branchid,revision),
  KEY repositoryid_2 (repositoryid),
  KEY dirid (dirid),
  KEY fileid (fileid),
  KEY branchid (branchid)
) ENGINE=MyISAM;

DROP TABLE IF EXISTS metadata;
CREATE TABLE metadata (
  name varchar(255) binary DEFAULT '' NOT NULL,
  value text,
  PRIMARY KEY (name),
  UNIQUE name (name)
) ENGINE=MyISAM;
INSERT INTO metadata (name, value) VALUES ('version', '1');
"""

BONSAI_COMPAT="""
WARNING:  Creating Bonsai-compatible legacy database version.  Some ViewVC
features may not be available, or may not perform especially well.

"""

## ------------------------------------------------------------------------

def usage_and_exit(errmsg=None):
  stream = errmsg is None and sys.stdout or sys.stderr
  stream.write("""\
Usage: %s [OPTIONS]

This script creates the database and tables in MySQL used by the
ViewVC checkin database.  In order to operate correctly, it needs to
know the following:  your database server hostname, database user,
database user password, and database name.  (You will be prompted for
any of this information that you do not provide via command-line
options.)  This script will use the 'mysql' program to create the
database for you.  You will then need to set the appropriate
parameters in the [cvsdb] section of your viewvc.conf file.

NOTE: If a hostname or port is supplied at the command line or during
interactive prompting, this script will pass '--protocol=TCP' to
'mysql'.

Options:

  --dbname=ARG        Use ARG as the ViewVC database name to create.
                      [Default: ViewVC]

  --help              Show this usage message.

  --hostname=ARG      Use ARG as the hostname for the MySQL connection.

  --port=ARG          Use ARG as the port for the MySQL connection.

  --password=ARG      Use ARG as the password for the MySQL connection.

  --timeout=ARG       Use ARG as the timeout in sec for waiting MySQL
                      to create database if timeout feature is available.
                      [Default: 300]

  --username=ARG      Use ARG as the username for the MySQL connection.

  --version=ARG       Create the database using the schema employed by
                      version ARG of ViewVC.  Valid values are:
                      [ "1.0" ]

""" % (os.path.basename(sys.argv[0])))
  if errmsg is not None:
    stream.write("[ERROR] %s.\n" % (errmsg))
    sys.exit(1)
  sys.exit(0)


if __name__ == "__main__":
  try:
    # Parse the command-line options, if any.
    dbname = version = hostname = port = username = password = None
    timeout = 300
    opts, args = getopt.getopt(sys.argv[1:], '', [ 'dbname=',
                                                   'help',
                                                   'hostname=',
                                                   'port=',
                                                   'password=',
                                                   'username=',
                                                   'version=',
                                                   'timeout=',
                                                   ])
    if len(args) > 0:
      usage_and_exit("Unexpected command-line parameters")
    for name, value in opts:
      if name == '--help':
        usage_and_exit(0)
      elif name == '--dbname':
        dbname = value
      elif name == '--hostname':
        hostname = value
      elif name == '--port':
        port = value
      elif name == '--username':
        username = value
      elif name == '--password':
        password = value
      elif name == '--version':
        if value in ["1.0"]:
          version = value
        else:
          usage_and_exit("Invalid version specified")
      elif subprocess.has_timeout and name == '--timeout':
        timeout = int(value)

    # Prompt for information not provided via command-line options.
    if hostname is None:
      hostname = raw_input("MySQL Hostname (leave blank for default): ")
    if port is None:
      port = raw_input("MySQL Port (leave blank for default): ")
    if username is None:
      username = raw_input("MySQL User: ")
    if password is None:
      password = raw_input("MySQL Password: ")
    if dbname is None:
      dbname = raw_input("ViewVC Database Name [default: ViewVC]: ") or "ViewVC"

    # Create the database.
    dscript = DATABASE_SCRIPT_COMMON.replace("<dbname>", dbname)
    if version == "1.0":
      print(BONSAI_COMPAT)
      dscript = dscript + DATABASE_SCRIPT_VERSION_0
    else:
      dscript = dscript + DATABASE_SCRIPT_VERSION_1

    # Calculate command arguments.
    cmd_args = [("--user=%s" % username), ("--password=%s" % password)]
    if hostname or port:
      cmd_args.append("--protocol=TCP")
    if hostname:
      cmd_args.append("--host=%s" % hostname)
    if port:
      cmd_args.append("--port=%s" % port)

    cmd = ["mysql"]
    mysql = subprocess.Popen(cmd + cmd_args, bufsize=-1, stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
                             universal_newlines=True,
                             close_fds=(sys.platform != "win32"))
    if (subprocess.has_timeout):
      try:
        stdout_data = mysql.communicate(input=dscript, timeout=timeout)[0]
        status = mysql.returncode
      except subprocess.TimeoutExpired:
        mysql.kill()
        stdout_data = mysql.communicate()[0]
        stdout_data += '\n[ERROR] Timeout expired while calling mysql process'
        status = -1
    else:
      stdout_data = mysql.communicate(input=dscript)[0]
      status = mysql.returncode
    print(stdout_data)
    if status:
      print("[ERROR] The database did not create sucessfully.")
      sys.exit(1)

    print("Database created successfully.  Don't forget to configure the ")
    print("[cvsdb] section of your viewvc.conf file.")
  except KeyboardInterrupt:
    pass
  sys.exit(0)

