From 81ba336b4bbd7e9d93717e3dac7f36a7eb95f74d Mon Sep 17 00:00:00 2001
From: martin <martin@martin-ThinkPad-T410.(none)>
Date: Wed, 18 May 2011 15:35:27 -0400
Subject: [PATCH] cc-2280: install script overwrites existing db

---
 install/airtime-db-install.php     | 21 +++++++++++++++++++--
 install/include/AirtimeInstall.php | 10 ++++++++--
 2 files changed, 27 insertions(+), 4 deletions(-)

diff --git a/install/airtime-db-install.php b/install/airtime-db-install.php
index 83f8d7ee0..66174e61a 100644
--- a/install/airtime-db-install.php
+++ b/install/airtime-db-install.php
@@ -11,13 +11,30 @@ echo PHP_EOL."*** Database Installation ***".PHP_EOL;
 
 AirtimeInstall::CreateDatabaseUser();
 
-AirtimeInstall::CreateDatabase();
+$databaseExisted = AirtimeInstall::CreateDatabase();
 
 AirtimeInstall::DbConnect(true);
 
 AirtimeInstall::InstallPostgresScriptingLanguage();
 
-AirtimeInstall::CreateDatabaseTables();
+if ($databaseExisted){
+    //Database already exists. Ask the user how they want to
+    //proceed. Warn them that creating the database tables again
+    //will cause them to lose their old ones.
+    
+    $userAnswer = "x";
+    while (!in_array($userAnswer, array("y", "Y", "n", "N", ""))) {
+        echo PHP_EOL."Database already exists. Do you want to delete all tables and recreate? (y/N)";
+        $userAnswer = trim(fgets(STDIN));
+    }
+    if (in_array($userAnswer, array("y", "Y"))) {
+        AirtimeInstall::CreateDatabaseTables();
+    }
+} else {
+    //Database was just created, meaning the tables do not
+    //exist. Let's create them.
+    AirtimeInstall::CreateDatabaseTables();
+}
 
 AirtimeInstall::SetAirtimeVersion(AIRTIME_VERSION);
 
diff --git a/install/include/AirtimeInstall.php b/install/include/AirtimeInstall.php
index 492250758..5cd0662c4 100644
--- a/install/include/AirtimeInstall.php
+++ b/install/include/AirtimeInstall.php
@@ -142,6 +142,7 @@ class AirtimeInstall
         }
     }
 
+    
     public static function CreateDatabase()
     {
         global $CC_CONFIG;
@@ -150,8 +151,9 @@ class AirtimeInstall
 
         $database = $CC_CONFIG['dsn']['database'];
         $username = $CC_CONFIG['dsn']['username'];
-        $command = "echo \"CREATE DATABASE $database OWNER $username\" | su postgres -c psql  2>/dev/null";
-
+        #$command = "echo \"CREATE DATABASE $database OWNER $username\" | su postgres -c psql  2>/dev/null";
+        $command = "su postgres -c \"createdb $database --owner $username\"";
+        
         @exec($command, $output, $results);
         if ($results == 0) {
             echo "* Database '{$CC_CONFIG['dsn']['database']}' created.".PHP_EOL;
@@ -164,6 +166,10 @@ class AirtimeInstall
                 echo "* Database '{$CC_CONFIG['dsn']['database']}' already exists.".PHP_EOL;
             }
         }
+        
+        $databaseExisted = ($results != 0);
+        
+        return $databaseExisted;
     }
 
     public static function InstallPostgresScriptingLanguage()