# Default release is 'current'
config.release = 'current'

def staging():
    """Staging server settings"""
    config.settings = 'staging'
    config.path = '/home/ryan/sites/staging.ryanwilliams'
    config.fab_hosts = ['staging.ryanwilliams.org']
    config.fab_user = 'ryan'


def production():
    """Production server settings"""
    config.settings = 'production'
    config.path = '/home/ryan/sites/ryanwilliams'
    config.fab_hosts = ['ryanwilliams.org']
    config.fab_user = 'ryan'

def setup():
    """
    Setup a fresh virtualenv and install everything we need so it's ready to
    deploy to
    """
    run('mkdir -p $(path); cd $(path); virtualenv .; mkdir releases; mkdir shared;')
    run('cd $(path)/bin; ln -s ../project/django.fcgi')
    clone_repo()
    checkout_latest()
    install_requirements()

def deploy():
    """Deploy the latest version of the site to the server and restart lighttpd"""
    checkout_latest()
    symlink_current_release()
    migrate()
    restart_lighttpd()




def clone_repo():
    """Do initial clone of the git repo"""
    run('cd $(path); git clone /home/git/repositories/ryanwilliams.git repository')

def checkout_latest():
    """Pull the latest code into the git repo and copy to a timestamped release directory"""
    import time
    config.release = time.strftime('%Y%m%d%H%M%S')
    run("cd $(path)/repository; git pull origin master")
    run('cp -R $(path)/repository $(path)/releases/$(release); rm -rf $(path)/releases/$(release)/.git*')

def install_requirements():
    """Install the required packages using pip"""
    run('cd $(path); pip install -E . -r ./releases/$(release)/requirements.txt')

def symlink_current_release():
    """Symlink our current release, uploads and settings file"""
    run('cd $(path); rm project; ln -s releases/current project; rm releases/current; ln -s $(release) releases/current')
    run('cd $(path)/releases/current/; ln -s settings_$(settings).py settings.py', fail='ignore')
    run('cd $(path)/releases/current/media/; ln -s ../../../shared/uploads/ .', fail='ignore')

def migrate():
    """Run our migrations"""
    run('cd $(path)/releases/current;  ../../bin/python manage.py syncdb --noinput --migrate')

def restart_lighttpd():
    """Restart the web server"""
    sudo('/etc/init.d/lighttpd restart')

