import platform
import shutil
from subprocess import Popen, PIPE
import subprocess
import sys
import os
sys.path.append('/usr/lib/airtime/')
from api_clients import api_client
from configobj import ConfigObj

import logging

if os.geteuid() != 0:
    print "Please run this as root."
    sys.exit(1)

"""
    This function returns the codename of the host OS by querying lsb_release.
    If lsb_release does not exist, or an exception occurs the codename returned
    is 'unknown'
"""
def get_os_codename():
    try:
        p = Popen("which lsb_release > /dev/null", shell=True)
        sts = os.waitpid(p.pid, 0)[1]
        
        if (sts == 0):
            #lsb_release is available on this system. Let's get the os codename
            p = Popen("lsb_release -sc", shell=True, stdout=PIPE)
            codename = p.communicate()[0].strip('\r\n')
 
            p = Popen("lsb_release -sd", shell=True, stdout=PIPE)
            fullname = p.communicate()[0].strip('\r\n')
            
            return (codename, fullname)
    except Exception, e:
        pass

    return ("unknown", "unknown")

def generate_liquidsoap_config(ss):
    data = ss['msg']
    fh = open('/etc/airtime/liquidsoap.cfg', 'w')
    fh.write("################################################\n")
    fh.write("# THIS FILE IS AUTO GENERATED. DO NOT CHANGE!! #\n")
    fh.write("################################################\n")
    for d in data:
        buffer = d[u'keyname'] + " = "
        if(d[u'type'] == 'string'):
            temp = d[u'value']
            buffer += '"%s"' % temp
        else:
            temp = d[u'value']
            if(temp == ""):
                temp = "0"
            buffer += temp
        buffer += "\n"
        fh.write(api_client.encode_to(buffer))
    fh.write('log_file = "/var/log/airtime/pypo-liquidsoap/<script>.log"\n')
    fh.close()
    
PATH_INI_FILE = '/etc/airtime/pypo.cfg'
PATH_LIQUIDSOAP_BIN = '/usr/lib/airtime/pypo/bin/liquidsoap_bin'

#any debian/ubuntu codename in this et will automatically use the natty liquidsoap binary
arch_map = dict({"32bit":"i386", "64bit":"amd64"})

# load config file
try:
    config = ConfigObj(PATH_INI_FILE)
except Exception, e:
    print 'Error loading config file: ', e
    sys.exit(1)
    
try:    
    #select appropriate liquidsoap file for given system os/architecture
    architecture = platform.architecture()[0]
    arch = arch_map[architecture]
        
    print "* Detecting OS: ...",
    (codename, fullname) = get_os_codename()
    print " Found %s (%s) on %s architecture" % (fullname, codename, arch) 
    
    print " * Installing Liquidsoap binary"
    
    p = Popen("which liquidsoap", shell=True, stdout=PIPE)
    liq_path = p.communicate()[0].strip()
    
    if p.returncode == 0:
        try:
            os.unlink(liq_path)
        except Exception:
            #liq_path DNE, which is OK.
            pass
            
        
        os.symlink(liq_path, "/usr/bin/airtime-liquidsoap")
    else:
        print " * Liquidsoap binary not found!"
        sys.exit(1)
    
    #initialize init.d scripts
    subprocess.call("update-rc.d airtime-playout defaults >/dev/null 2>&1", shell=True)

    #clear out an previous pypo cache
    print "* Clearing previous pypo cache"  
    subprocess.call("rm -rf /var/tmp/airtime/pypo/cache/scheduler/* >/dev/null 2>&1", shell=True)
    
    if "airtime_service_start" in os.environ and os.environ["airtime_service_start"] == "t":
        print "* Waiting for pypo processes to start..."    
        subprocess.call("invoke-rc.d airtime-playout start-no-monit  > /dev/null 2>&1", shell=True)
    
except Exception, e:
    print e

@@ -611,25 +611,17 @@
 , 0)%5B1%5D%0A
-        
 %0A
+
         
@@ -837,18 +837,17 @@
 '%5Cr%5Cn')%0A
- 
 %0A
+
         
@@ -960,29 +960,17 @@
 '%5Cr%5Cn')%0A
-            
 %0A
+
         
@@ -1833,21 +1833,17 @@
 close()%0A
-    
 %0A
+
 PATH_INI
@@ -2228,21 +2228,13 @@
 (1)%0A
-    
 %0Atry:
-    
 %0A   
@@ -2383,25 +2383,17 @@
 ecture%5D%0A
-        
 %0A
+
     prin
@@ -2536,22 +2536,17 @@
 e, arch)
- %0A    
+%0A
 %0A    pri
@@ -2582,21 +2582,17 @@
 binary%22%0A
-    
 %0A
+
     p = 
@@ -2684,24 +2684,69 @@
 strip()%0A    
+symlink_path = %22/usr/bin/airtime-liquidsoap%22%0A
 %0A    if p.re
@@ -2791,27 +2791,31 @@
   os.unlink(
-liq
+symlink
 _path)%0A     
@@ -2896,29 +2896,9 @@
 ass%0A
-            %0A        
+%0A
 %0A   
@@ -2927,37 +2927,20 @@
 th, 
-%22/usr/bin/airtime-liquidsoap%22
+symlink_path
 )%0A  
@@ -3015,21 +3015,17 @@
 exit(1)%0A
-    
 %0A
+
     #ini
@@ -3216,18 +3216,16 @@
 o cache%22
-  
 %0A    sub
@@ -3315,21 +3315,17 @@
 l=True)%0A
-    
 %0A
+
     if %22
@@ -3465,20 +3465,16 @@
 tart...%22
-    
 %0A       
@@ -3566,20 +3566,16 @@
 l=True)%0A
-    
 %0Aexcept 

fix installer breaking liquidsoap package install