#!/usr/bin/python

from subprocess import check_output,check_call, CalledProcessError, Popen, PIPE
import tempfile
import json
import re
import hashlib
import os
import sys
import platform
from string import upper

num_re = re.compile('^[0-9]+$')

# There should be a library for this
def human_to_bytes(human):
    if num_re.match(human):
        return human
    factors = { 'K' : 1024 , 'M' : 1048576, 'G' : 1073741824, 'T' : 1099511627776 }
    modifier=human[-1]
    if modifier in factors:
        return int(human[:-1]) * factors[modifier]
    if modifier == '%':
        total_ram = human_to_bytes(get_memtotal())

        if IS_32BIT_SYSTEM and total_ram > SYS_MEM_LIMIT:
            total_ram = SYS_MEM_LIMIT

        factor = int(human[:-1]) * 0.01
        pctram = total_ram * factor
        return int(pctram - (pctram % PAGE_SIZE))
    raise ValueError("Can only convert K,M,G, or T")


# Going for the biggest page size to avoid wasted bytes. InnoDB page size is
# 16MB
PAGE_SIZE = 16*1024*1024
try:
    IS_32BIT_SYSTEM = sys.maxsize < 2**32
except OverflowError:
    IS_32BIT_SYSTEM = True

if platform.machine() in ['armv7l']:
    SYS_MEM_LIMIT = human_to_bytes('2700M') # experimentally determined
else:
    SYS_MEM_LIMIT = human_to_bytes('4G')

if IS_32BIT_SYSTEM:
    check_call(['juju-log','-l','INFO','32bit system restrictions in play'])

configs=json.loads(check_output(['config-get','--format=json']))

def get_memtotal():
    with open('/proc/meminfo') as meminfo_file:
        meminfo = {}
        for line in meminfo_file:
            (key, mem) = line.split(':', 2)
            if key == 'MemTotal':
                (mtot, modifier) = mem.strip().split(' ')
                return '%s%s' % (mtot, upper(modifier[0]))


# There is preliminary code for mariadb, but switching
# from mariadb -> mysql fails badly, so it is disabled for now.
valid_flavors = ['distro','percona']
if configs['flavor'] not in valid_flavors:
    check_call(['juju-log','-l',
            'ERROR',
            'Invalid flavor, must be one of %s' % ','.join(valid_flavors)])
    sys.exit(1)

remove_pkgs=[]
if configs['flavor'] == 'distro':
    apt_sources = []
    package = 'mysql-server'
elif configs['flavor'] == 'percona':
    apt_sources = ['repo.percona.com/apt']
    package = 'percona-server-server'
    remove_pkgs = ['mysql-client-core-5.5','mysql-server-core-5.5']
elif configs['flavor'] == 'mariadb':
    apt_sources = ['ftp.osuosl.org/pub/mariadb/repo/5.5/ubuntu']
    package = 'mariadb-server'

series = check_output(['lsb_release','-cs'])

for source in apt_sources:
    server = source.split('/')[0]
    if os.path.exists('keys/%s' % server):
        check_call(['apt-key','add','keys/%s' % server])
    else:
        check_call(['juju-log','-l','ERROR',
                'No key for %s' % (server)])
        sys.exit(1)
    check_call(['add-apt-repository','-y','deb http://%s %s main' % (source, series)])
    check_call(['apt-get','update'])

with open('/var/lib/mysql/mysql.passwd','r') as rpw:
    root_pass = rpw.read()

dconf = Popen(['debconf-set-selections'], stdin=PIPE)
dconf.stdin.write("%s %s/root_password password %s\n" % (package, package, root_pass))
dconf.stdin.write("%s %s/root_password_again password %s\n" % (package, package, root_pass))
dconf.communicate()
dconf.wait()

if len(remove_pkgs):
    check_call(['apt-get','-y','remove'] + remove_pkgs)
check_call(['apt-get','-y','install','-qq',package])

# smart-calc stuff in the configs
dataset_bytes = human_to_bytes(configs['dataset-size'])

check_call(['juju-log','-l','INFO','dataset size in bytes: %d' % dataset_bytes])

if configs['query-cache-size'] == -1 and configs['query-cache-type'] in ['ON','DEMAND']:
    qcache_bytes = (dataset_bytes * 0.20)
    qcache_bytes = int(qcache_bytes - (qcache_bytes % PAGE_SIZE))
    configs['query-cache-size'] = qcache_bytes
    dataset_bytes -= qcache_bytes

# 5.5 allows the words, but not 5.1
if configs['query-cache-type'] == 'ON':
    configs['query-cache-type']=1
elif configs['query-cache-type'] == 'DEMAND':
    configs['query-cache-type']=2
else:
    configs['query-cache-type']=0

preferred_engines=configs['preferred-storage-engine'].split(',')
chunk_size = int(dataset_bytes / len(preferred_engines))
configs['innodb-flush-log-at-trx-commit']=1
configs['sync-binlog']=1
if 'InnoDB' in preferred_engines:
    configs['innodb-buffer-pool-size'] = chunk_size
    if configs['tuning-level'] == 'fast':
        configs['innodb-flush-log-at-trx-commit']=2
else:
    configs['innodb-buffer-pool-size'] = 0

configs['default-storage-engine'] = preferred_engines[0]

if 'MyISAM' in preferred_engines:
    configs['key-buffer'] = chunk_size
else:
    # Need a bit for auto lookups always
    configs['key-buffer'] = human_to_bytes('8M')

if configs['tuning-level'] == 'fast':
    configs['sync-binlog']=0

if configs['max-connections'] == -1:
    configs['max-connections'] = '# max_connections = ?'
else:
    configs['max-connections'] = 'max_connections = %s' % configs['max-connections']

template="""
######################################
#
#
#
# This file generated by the juju MySQL charm!
#
# Local changes will not be preserved!
#
#
#
######################################
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
# 
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html

# This will be passed to all mysql clients
# It has been reported that passwords should be enclosed with ticks/quotes
# escpecially if they contain "#" chars...
# Remember to edit /etc/mysql/debian.cnf when changing the socket location.
[client]
port		= 3306
socket		= /var/run/mysqld/mysqld.sock

# Here is entries for some specific programs
# The following values assume you have at least 32M ram

# This was formally known as [safe_mysqld]. Both versions are currently parsed.
[mysqld_safe]
socket		= /var/run/mysqld/mysqld.sock
nice		= 0

[mysqld]
#
# * Basic Settings
#

#
# * IMPORTANT
#   If you make changes to these settings and your system uses apparmor, you may
#   also need to also adjust /etc/apparmor.d/usr.sbin.mysqld.
#

user		= mysql
socket		= /var/run/mysqld/mysqld.sock
port		= 3306
basedir		= /usr
datadir		= /var/lib/mysql
tmpdir		= /tmp
skip-external-locking
#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address		= 0.0.0.0
#
# * Fine Tuning
#
key_buffer		= %(key-buffer)s
max_allowed_packet	= 16M
# This replaces the startup script and checks MyISAM tables if needed
# the first time they are touched
myisam-recover         = BACKUP
%(max-connections)s
#table_cache            = 64
#thread_concurrency     = 10
#
# * Query Cache Configuration
#
query_cache_limit = 1M
query_cache_size = %(query-cache-size)s
query_cache_type = %(query-cache-type)s
#
# * Logging and Replication
#
# Both location gets rotated by the cronjob.
# Be aware that this log type is a performance killer.
# As of 5.1 you can enable the log at runtime!
#general_log_file        = /var/log/mysql/mysql.log
#general_log             = 1

log_error                = /var/log/mysql/error.log

# Here you can see queries with especially long duration
#log_slow_queries	= /var/log/mysql/mysql-slow.log
#long_query_time = 2
#log-queries-not-using-indexes
#
# The following can be used as easy to replay backup logs or for replication.
# note: if you are setting up a replication slave, see README.Debian about
#       other settings you may need to change.
#server-id		= 1
#log_bin			= /var/log/mysql/mysql-bin.log
expire_logs_days	= 10
max_binlog_size         = 100M
#binlog_do_db		= include_database_name
#binlog_ignore_db	= include_database_name
#
# * InnoDB
#
# InnoDB is enabled by default with a 10MB datafile in /var/lib/mysql/.
# Read the manual for more InnoDB related options. There are many!
#
innodb_buffer_pool_size = %(innodb-buffer-pool-size)s
innodb_flush_log_at_trx_commit = %(innodb-flush-log-at-trx-commit)s
sync_binlog = %(sync-binlog)s
default_storage_engine = %(default-storage-engine)s
skip-name-resolve
# * Security Features
#
# Read the manual, too, if you want chroot!
# chroot = /var/lib/mysql/
#
# For generating SSL certificates I recommend the OpenSSL GUI "tinyca".
#
# ssl-ca=/etc/mysql/cacert.pem
# ssl-cert=/etc/mysql/server-cert.pem
# ssl-key=/etc/mysql/server-key.pem



[mysqldump]
quick
quote-names
max_allowed_packet	= 16M

[mysql]
#no-auto-rehash	# faster start of mysql but no tab completition

[isamchk]
key_buffer		= 16M

#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/
"""

i_am_a_slave = os.path.isfile('/var/lib/juju/i.am.a.slave')
unit_id = os.environ['JUJU_UNIT_NAME'].split('/')[1]

if not i_am_a_slave and configs['tuning-level'] == 'fast':
    binlog_cnf = ''
else:
    # On slaves, this gets overwritten
    binlog_template = """
[mysqld]
server_id = %s
log_bin = /var/log/mysql/mysql-bin.log
binlog_format = %s
"""

    binlog_cnf = binlog_template % (unit_id,
        configs.get('binlog-format','MIXED'))

mycnf=template % configs

targets = {'/etc/mysql/conf.d/binlog.cnf': binlog_cnf,
           '/etc/mysql/my.cnf': mycnf,
           }

need_restart = False
for target,content in targets.iteritems():
    tdir = os.path.dirname(target) 
    if len(content) == 0 and os.path.exists(target):
        os.unlink(target)
        need_restart = True
        continue
    with tempfile.NamedTemporaryFile(mode='w',dir=tdir,delete=False) as t:
        t.write(content)
        t.flush()
        tmd5 = hashlib.md5()
        tmd5.update(content)
        if os.path.exists(target):
            with open(target,'r') as old:
                md5=hashlib.md5()
                md5.update(old.read())
                oldhash = md5.digest()
                if oldhash != tmd5.digest():
                    os.rename(target,'%s.%s' % (target, md5.hexdigest()))
                    need_restart = True
        else:
            need_restart = True
        os.rename(t.name, target)

if need_restart:
    try:
        check_call(['service','mysql','stop'])
    except CalledProcessError:
        pass
    check_call(['service','mysql','start'])
