#!/bin/sh

DBNAME=$(/sbin/e-smith/db configuration getprop freepbx DbName)
backuppath='/home/e-smith/files/freepbx'

# check if backup module is local, enabled and running
# if not solve this...
if [[ ! `/sbin/e-smith/fwconsole ma list|/bin/grep backup`  ]] ;then
       /sbin/e-smith/fwconsole ma download backup -R standard -R extended >/dev/null 2>&1
fi
#force install
/sbin/e-smith/fwconsole ma install backup -R standard -R extended  >/dev/null 2>&1
# force enable
/sbin/e-smith/fwconsole ma enable backup  >/dev/null 2>&1
/sbin/e-smith/fwconsole r >/dev/null

# check our freepbx backup folder is there and accessible
if [[ ! -d $backuppath ]] ; then
        /bin/mkdir -p $backuppath
fi

version=$(/usr/bin/xmllint --xpath 'string(/module/version)' /opt/freepbx/admin/modules/backup/module.xml|cut -d. -f1)
#if version >=15
if [[ $version -ge 15 ]]
then
  ############
  # FILE STORE
  ############
  # check local space is defined, if not do it kvstore_FreePBX_modules_Filestore
  filestore=$(echo 'SELECT `id` FROM `kvstore_FreePBX_modules_Filestore`  WHERE `key` LIKE "path" and `val` LIKE "/home/e-smith/files/freepbx/"'| mariadb -u root  freepbxdb -s)
  if [ -z $filestore ] ; then
    filestore=$(/usr/bin/uuidgen)
    echo "creating new filestore id $filestore"
  else
   echo "filestore $filestore will be used"
  fi
    # we need existing  servers value to update it 
    servers=$(echo 'SELECT `val` FROM `kvstore_FreePBX_modules_Filestore`  WHERE `key` LIKE "servers" and `id` LIKE "noid"'| mariadb -u root  freepbxdb -s)
    servers=$(echo $servers| jq '.  |= . + {"'$filestore'" : { "id": "'$filestore'","name": "Local Storage","desc": "Storage location for backups", "driver": "Local" }}')
    mariadb -e "use $DBNAME; INSERT INTO \`kvstore_FreePBX_modules_Filestore\` (\`key\`, \`val\`, \`type\`, \`id\`) VALUES
     ('servers', '$servers', 'json-arr', 'noid')
     ON DUPLICATE KEY UPDATE val=VALUES(val);"
    mariadb -e "use $DBNAME; INSERT INTO \`kvstore_FreePBX_modules_Filestore\` (\`key\`, \`val\`, \`type\`, \`id\`) VALUES
     ('name', 'Local Storage', NULL, '$filestore'),
     ('desc', 'Storage location for backups', NULL, '$filestore'),
     ('path', '/home/e-smith/files/freepbx/', NULL, '$filestore'),
     ('immortal', 'true', NULL, '$filestore'),
     ('driver', 'Local', NULL, '$filestore')
     ON DUPLICATE KEY UPDATE val=VALUES(val);"

  ###########
  # BACKUP
  ###########
  # check Default-backup exists, if not set it, else update it
  backupid=$(echo 'SELECT `id` FROM `kvstore_FreePBX_modules_Backup` WHERE `key` LIKE "backup_name" and `val` LIKE "Default-backup"'| mariadb -u root  freepbxdb -s)
  if [ -z $backupid ] ; then
    backupid=$(/usr/bin/uuidgen)
    echo "creating new backup id $backupid"

    mariadb -e "use $DBNAME; CREATE TABLE IF NOT EXISTS \`kvstore_FreePBX_modules_Backup\` (
  \`key\` char(255) NOT NULL,
  \`val\` varchar(4096) DEFAULT NULL,
  \`type\` char(16) DEFAULT NULL,
  \`id\` char(255) DEFAULT NULL,
  UNIQUE KEY \`uniqueindex\` (\`key\`(190),\`id\`(190)),
  KEY \`keyindex\` (\`key\`(190)),
  KEY \`idindex\` (\`id\`(190))
) ENGINE=InnoDB DEFAULT CHARSET=utf8;"
    
    ##TODO SELECT * FROM `kvblobstore` WHERE `uuid` LIKE 'a9fe727b-fc4c-40c4-ad45-bcabd075302a' 
    ### TODO : list modules enabled and populate
    blobstore=$(/usr/bin/uuidgen)
    mariadb -e "use $DBNAME;INSERT INTO kvstore_FreePBX_modules_Backup (\`key\`, \`val\`, \`type\`, \`id\`) VALUES 
    ('backup_items', '$blobstore', 'blob', '$backupid')
    ON DUPLICATE KEY UPDATE val=VALUES(val);"
    # create an empty blob store, it seems to not be a problem to actually run the backup
    mariadb -e "use $DBNAME;INSERT INTO kvblobstore (\`uuid\`, \`type\`, \`content\`) VALUES 
    ('$blobstore', NULL, '');" || exit 1
    # we do this only if the other did not failed to avoid hitting one existing uuid
    mariadb -e "use $DBNAME;INSERT INTO kvstore_FreePBX_modules_Backup (\`key\`, \`val\`, \`type\`, \`id\`) VALUES 
    ('backup_items', '$blobstore', 'blob', '$backupid')
    ON DUPLICATE KEY UPDATE val=VALUES(val);"

  else
    echo "Updating backup $backupid"
  fi

    mariadb -e "use $DBNAME;INSERT INTO kvstore_FreePBX_modules_Backup (\`key\`, \`val\`, \`type\`, \`id\`) VALUES
('backup_name', 'Default-backup', NULL, '$backupid'),
('backup_description', 'Default SME PBX backup; automatically installed', NULL, '$backupid'),
('backup_email', 'admin', NULL, '$backupid'),
('created_by', 'SME Server Event', NULL, '$backupid'),
('desc', 'Default SME PBX backup; automatically installed', NULL, '$backupid'),
('warmspare_remoteip', '', NULL, '$backupid'),
('warmspare_user', '', NULL, '$backupid'),
('maintruns', '2', NULL, '$backupid'),
('backup_emailtype', 'failure', NULL, '$backupid'),
('backup_schedule', '31 5 * * 0', NULL, '$backupid'),
('schedule_enabled', 'yes', NULL, '$backupid'),
('backup_storage', '[\\\"Local_$filestore\\\"]', 'json-arr', '$backupid'),
('backup_items', 'a9fe727b-fc4c-40c4-ad45-bcabd075302a', 'blob', '$backupid'),
('maintage', 'Unlimited', NULL, '$backupid'),
('backup_emailinline', '', NULL, '$backupid'),
('backup_addbjname', 'yes', NULL, '$backupid'),
('warmspareenabled', 'on', NULL, '$backupid'),
('warmspare_remotenat', 'on', NULL, '$backupid'),
('warmspare_cert', 'on', NULL, '$backupid'),
('warmspare_remotebind', 'on', NULL, '$backupid'),
('warmspare_remotedns', 'on', NULL, '$backupid'),
('warmspare_remoteapply', 'on', NULL, '$backupid'),
('publickey', '', NULL, '$backupid'),
('warmsparewayofrestore', 'API', NULL, '$backupid'),
('warmspare_remoteapi_filestoreid', '', NULL, '$backupid'),
('warmspare_remoteapi_accesstoken', '', NULL, '$backupid'),
('warmspare_remoteapi_accesstokenurl', '', NULL, '$backupid'),
('warmspare_remoteapi_accesstoken_expire', '', NULL, '$backupid'),
('warmspare_remoteapi_clientid', '', NULL, '$backupid'),
('warmspare_remoteapi_secret', '', NULL, '$backupid'),
('warmspare_remoteapi_gql', '', NULL, '$backupid'),
('warmspare_excludetrunks', 'on', NULL, '$backupid'),
('warmspare_remotessh_filestoreid', '', NULL, '$backupid'),
('custom_files', '[{\"type\":\"dir\",\"path\":\"__ASTETCDIR__\",\"exclude\":[]}]', NULL, '$backupid'),
('prebu_hook', '', NULL, '$backupid'),
('postbu_hook', '', NULL, '$backupid'),
('prere_hook', '', NULL, '$backupid'),
('postre_hook', '', NULL, '$backupid'),
('core_disabletrunks', '', NULL, '$backupid'),
('$backupid', '{\\\"id\\\":\\\"$backupid\\\",\\\"name\\\":\\\"Default-backup\\\",\\\"description\\\":\\\"Default SME PBX backup; automatically installed\\\"}', 'json-arr', 'backupList'),
('bu_1', '{\\\"id\\\":\\\"1\\\",\\\"name\\\":\\\"Default backup\\\",\\\"description\\\":\\\"Default SME PBX backup; automatically installed\\\",\\\"immortal\\\":\\\"true\\\",\\\"data\\\":{\\\"created_by\\\":\\\"install.php\\\",\\\"desc\\\":\\\"Default SME PBX backup; automatically installed\\\",\\\"cron_schedule\\\":\\\"weekly\\\",\\\"storage_servers\\\":[\\\"1\\\"],\\\"bu_server\\\":\\\"0\\\",\\\"delete_amount\\\":\\\"2\\\",\\\"delete_time_type\\\":\\\"days\\\",\\\"cron_random\\\":\\\"on\\\",\\\"cron_month\\\":\\\"\\\",\\\"cron_minute\\\":\\\"0\\\",\\\"cron_hour\\\":\\\"0\\\",\\\"cron_dow\\\":\\\"0\\\",\\\"cron_dom\\\":\\\"\\\",\\\"delete_time\\\":\\\"0\\\",\\\"email\\\":\\\"admin\\\",\\\"emailfailonly\\\":\\\"1\\\"},\\\"email\\\":\\\"admin\\\",\\\"uuid\\\":\\\"$backupid\\\",\\\"items\\\":[{\\\"backup_id\\\":\\\"1\\\",\\\"type\\\":\\\"mysql\\\",\\\"path\\\":\\\"server-2\\\",\\\"exclude\\\":[]},{\\\"backup_id\\\":\\\"1\\\",\\\"type\\\":\\\"astdb\\\",\\\"path\\\":\\\"astdb\\\",\\\"exclude\\\":[]},{\\\"backup_id\\\":\\\"1\\\",\\\"type\\\":\\\"dir\\\",\\\"path\\\":\\\"\\/etc\\/dahdi\\\",\\\"exclude\\\":[]},{\\\"backup_id\\\":\\\"1\\\",\\\"type\\\":\\\"dir\\\",\\\"path\\\":\\\"__ASTSPOOLDIR__\\/voicemail\\\",\\\"exclude\\\":[]},{\\\"backup_id\\\":\\\"1\\\",\\\"type\\\":\\\"mysql\\\",\\\"path\\\":\\\"server-3\\\",\\\"exclude\\\":[]},{\\\"backup_id\\\":\\\"1\\\",\\\"type\\\":\\\"dir\\\",\\\"path\\\":\\\"__ASTETCDIR__\\\",\\\"exclude\\\":[]},{\\\"backup_id\\\":\\\"1\\\",\\\"type\\\":\\\"dir\\\",\\\"path\\\":\\\"__AMPWEBROOT__\\\",\\\"exclude\\\":[]},{\\\"backup_id\\\":\\\"1\\\",\\\"type\\\":\\\"dir\\\",\\\"path\\\":\\\"__AMPBIN__\\\",\\\"exclude\\\":[]},{\\\"backup_id\\\":\\\"1\\\",\\\"type\\\":\\\"dir\\\",\\\"path\\\":\\\"\\/tftpboot\\\",\\\"exclude\\\":[]}]}', 'json-arr', 'migratedbackups'),
('arimanager', '1', NULL, 'modules_$backupid'),
('backup', '1', NULL, 'modules_$backupid'),
('blacklist', '1', NULL, 'modules_$backupid'),
('callrecording', '1', NULL, 'modules_$backupid'),
('cdr', '1', NULL, 'modules_$backupid'),
('cel', '1', NULL, 'modules_$backupid'),
('certman', '1', NULL, 'modules_$backupid'),
('cidlookup', '1', NULL, 'modules_$backupid'),
('conferences', '1', NULL, 'modules_$backupid'),
('core', '1', NULL, 'modules_$backupid'),
('customappsreg', '1', NULL, 'modules_$backupid'),
('dashboard', '1', NULL, 'modules_$backupid'),
('fax', '1', NULL, 'modules_$backupid'),
('filestore', '1', NULL, 'modules_$backupid'),
('findmefollow', '1', NULL, 'modules_$backupid'),
('framework', '1', NULL, 'modules_$backupid'),
('infoservices', '1', NULL, 'modules_$backupid'),
('ivr', '1', NULL, 'modules_$backupid'),
('languages', '1', NULL, 'modules_$backupid'),
('logfiles', '1', NULL, 'modules_$backupid'),
('manager', '1', NULL, 'modules_$backupid'),
('music', '1', NULL, 'modules_$backupid'),
('phonebook', '1', NULL, 'modules_$backupid'),
('pm2', '1', NULL, 'modules_$backupid'),
('recordings', '1', NULL, 'modules_$backupid'),
('ringgroups', '1', NULL, 'modules_$backupid'),
('sipsettings', '1', NULL, 'modules_$backupid'),
('soundlang', '1', NULL, 'modules_$backupid'),
('ucp', '1', NULL, 'modules_$backupid'),
('userman', '1', NULL, 'modules_$backupid'),
('voicemail', '1', NULL, 'modules_$backupid') 
ON DUPLICATE KEY UPDATE val=VALUES(val);"

# TODO update 
#mariadb -e "use $DBNAME;INSERT INTO kvstore_FreePBX_modules_Backup (\`key\`, \`val\`, \`type\`, \`id\`) VALUES 
#('backup_items', 'a9fe727b-fc4c-40c4-ad45-bcabd075302a', 'blob', '$backupid')
#ON DUPLICATE KEY UPDATE val=VALUES(val);"

fi

# make sure all perms are ok for backup
/sbin/e-smith/fwconsole chown > /dev/null 2>&1

