----- use 5 '-' character for this script comment

----- EMS 2.14_01, add table 'sysProperty' and add record
----- EMS 2.14_01, modify table 'clientAction', add primary key
----- EMS 2.14_01, modify procedure 'clientActionInsert', rename to 'insertClientAction'
----- EMS 2.14_01, modify procedure 'register', rename to 'insertClientLog'   

----- EMS 2.14_02, modify table 'sysProperty', add record
----- EMS 2.14_02, modify procedure 'admin_agentreadlist', rename to 'admin_agentList'
----- EMS 2.14_02, modify procedure 'admin_agentgetitem', rename to 'getAgent'

----- EMS 2.15_02, modify table 'clientAction', check if table is existed when adding primary key 

----- EMS 2.15_03, delete procedure 'check_Worker'

----- EMS 2.15_04, modify table 'broker', add column 'enable'
----- EMS 2.15_04, modify table 'broker', add primary key
----- EMS 2.15_04, modify table 'agentsdriver', set column 'broker_id' to not null
----- EMS 2.15_04, modify table 'agentsdriver', add primary key
----- EMS 2.15_04, modify table 'agentsdriver', add foreign key  
----- EMS 2.15_04, modify table 'adlinks', remove column 'id'  
-----                                      set column 'agentsdriver_id' to not null
-----                                      set column 'agent_id' to not null
-----                                      add primary key column 'id', 'agent_id', 'agentsdriver_id'
-----                                      add foreign key column 'agentsdriver_id'  
-----                                      add foreign key column 'agent_id'   
----- EMS 2.15_04, add procedure 'addAgentsDriver'
----- EMS 2.15_04, add procedure 'addBroker'
----- EMS 2.15_04, add procedure 'deleteBroker'
----- EMS 2.15_04, add procedure 'setActiveBroker' 
----- EMS 2.15_04, add procedure 'getAgentsDriverAgents' 
----- EMS 2.15_04, add procedure 'deleteAdlink'
----- EMS 2.15_04, add procedure 'deleteAdlinks'
----- EMS 2.15_04, add procedure 'deleteBrokers'
----- EMS 2.15_04, delete procedure 'admin_brokergetitem' 
----- EMS 2.15_04, delete procedure 'admin_brokerdelete' 
----- EMS 2.15_04, delete procedure 'admin_drivergetitem'
----- EMS 2.15_04, delete procedure 'admin_getagents_out_driver'
----- EMS 2.15_04, modify procedure 'aliasInsert', rename to 'addAlias'
----- EMS 2.15_04, modify procedure 'admin_getagents_in_driver', rename to 'getPollingAgents'
----- EMS 2.15_04, modify procedure 'admin_brokerupdate', rename to 'editBroker'
----- EMS 2.15_04, modify procedure 'admin_driverupdate', rename to 'editAgentsDriver'  
----- EMS 2.15_04, modify procedure 'admin_agentInsert', rename to 'addAgent'
----- EMS 2.15_04, modify procedure 'admin_agentUpdate', rename to 'editAgent'
----- EMS 2.15_04, modify procedure 'nodeDelete', rename to 'deleteNode'
----- EMS 2.15_04, modify procedure 'admin_agentDelete', rename to 'deleteAgent'
----- EMS 2.15_04, modify procedure 'admin_addDriverAgents', rename to 'addAdlink'

----- EMS 2.16_03, add procedure 'getClientLogs'
----- EMS 2.16_03, add procedure 'getAgentByName'
----- EMS 2.16_03, add procedure 'getClientActions'
----- EMS 2.16_03, add procedure 'getFirstAgentDeviceType'
----- EMS 2.16_03, modify procedure 'getAgent', rename to 'getAgentById'
----- EMS 2.16_03, modify procedure 'admin_agentList', rename to 'getAgents'
----- EMS 2.16_03, modify procedure 'admin_clientList', rename to 'getClients'
----- EMS 2.16_03, modify procedure 'admin_clientInsert', rename to 'addClient'
----- EMS 2.16_03, modify procedure 'admin_clientUpdate', rename to 'editClient'
----- EMS 2.16_03, modify procedure 'admin_clientDelete', rename to 'deleteClient'
----- EMS 2.16_03, modify procedure 'insertClientLog', rename to 'addClientLog'
----- EMS 2.16_03, modify procedure 'insertClientAction', rename to 'addClientAction'
----- EMS 2.16_03, delete procedure 'admin_clientGet'

----- EMS 2.20_01, modify table 'nodes', add record for new model FRM220A
----- EMS 2.20_01, modify table 'node_types', add record for new model FRM220A
----- EMS 2.20_01, modify table 'treelinks', add record for new model FRM220A

----- EMS 2.20_02, modify procedure 'addAlias' for FRM220A

----- EMS 2.30_01, add 'table alarmlog'
----- EMS 2.30_01, add procedure 'addAlarmlog'
----- EMS 2.30_01, add procedure 'editAlarmLog'  
----- EMS 2.30_01, add procedure 'getAlarmLogs'
----- EMS 2.30_01, modify procedure 'insertPMList', rename to 'addPMList'
----- EMS 2.30_01, modify procedure 'insertTrapList', rename to 'addTrapList'
----- EMS 2.30_01, modify procedure 'addClientLog'
----- EMS 2.30_01, modify procedure 'addClientAction'
----- EMS 2.30_01, modify procedure 'getClientLogs' 
----- EMS 2.30_01, modify procedure 'getClientActions'    

----- EMS 2.31_01, modify table 'nodes', add record for new model FRM220A-1000EAS/X
----- EMS 2.31_01, modify table 'nodes', add record for model FRM220-10/100AS-2 
----- EMS 2.31_01, modify table 'node_types', add record for new model FRM220A-1000EAS/X
----- EMS 2.31_01, modify table 'treelinks', add record for new model FRM220A-1000EAS/X
----- EMS 2.31_01, modify table 'treelinks', add record for model FRM220-10/100AS-2
----- EMS 2.31_01, modify table 'treelinks', delete record model Series_Standalone
----- EMS 2.31_01, modify table 'treelinks', delete record model FRM220100AS2
----- EMS 2.31_01, modify procedure 'addAlias' for FRM220A-1000EAS/X

----- EMS 2.35_07, modify table 'nodes', add record for new model FMUX04E
----- EMS 2.35_07, modify table 'node_types', add record for new model FMUX04E
----- EMS 2.35_07, modify table 'treelinks', add record for new model FMUX04E
----- EMS 2.35_07, modify procedure 'addAlias' for FMUX04E

----- EMS 2.36_02, modify table 'nodes', add record for new model ERM-MUX/Plus
----- EMS 2.36_02, modify table 'node_types', add record for new model ERM-MUX/Plus
----- EMS 2.36_02, modify table 'treelinks', add record for new model ERM-MUX/Plus
----- EMS 2.36_02, modify procedure 'addAlias' for ERM-MUX/Plus

----- EMS 2.41_02, modify table 'agentsdriver', rename column 'pollingperiod' to 'poll_interval'    
----- EMS 2.41_02, modify table 'agentsdriver', rename column 'pollinginterval' to 'poll_timeout'  
----- EMS 2.41_02, edit procedure 'addAgentsDriver' 
----- EMS 2.41_02, edit procedure 'editAgentsDriver' 
----- EMS 2.41_02, edit procedure 'addBroker'

----- EMS 2.44_07, modify table 'trapList', rename column 'timestamp_system' to 'time'
-----                                       rename column 'trap_id' to 'specific_type'
-----                                       rename column 'timestamp_device' to 'timestamp'
-----                                       rename column 'body' to 'message'
-----                                       rename column 'timestamp_client' to 'time_ack'
-----                                       change column 'remark' type
-----                                       add column 'client_id'
-----                                       remove column 'op_name' 
-----                                       rename primary key 'PK_traplist' to 'PK_traplog'
-----                                       rename foreign key 'FK_traplist_agent' to 'FK_traplog_agent'
-----                                       rename column 'ack' constraint default to 'DF_trapLog_ack'
-----                                       rename column 'clear' constraint default to 'DF_trapLog_clear'
-----                                       rename table 'trapList' to 'trapLog' 
----- EMS 2.44_07, rename procedure 'addTrapList' to 'addTrapLog'
----- EMS 2.44_07, rename procedure 'getTrapList' to 'getTrapLogs'
----- EMS 2.44_07, add procedure 'editTrapLog' 

----- EMS 2.45_01, modify table 'agentsdriver', add column 'thread'
----- EMS 2.45_01, modify table 'agentsdriver', rename column 'poll_interval' to 'interval'
----- EMS 2.45_01, modify table 'agentsdriver', rename column 'poll_timeout' to 'timeout'
----- EMS 2.45_01, modify table 'agentsdriver', set column 'interval' to not null
----- EMS 2.45_01, modify table 'agentsdriver', set column 'timeout' to not null
----- EMS 2.45_01, modify procedure 'addAgentsDriver'
----- EMS 2.45_01, modify procedure 'editAgentsDriver'
----- EMS 2.45_01, modify procedure 'addBroker'

----- EMS 2.45_04, rename procedure 'treeList' to 'getUserTrees'

----- EMS 2.45_05, modify table 'pmList', rename column 'timestamp_system' to 'time'
-----                                       rename column 'timestamp_device' to 'timestamp'
-----                                       rename primary key 'PK_threshold' to 'PK_pmLog'
-----                                       rename foreign key 'FK_threshold_agent' to 'FK_pmLog_agent'
-----                                       rename table 'pmList' to 'pmLog' 
----- EMS 2.45_05, rename procedure 'addPMList' to 'addPmLog' 
----- EMS 2.45_05, add procedure 'getPmLogs' 

----- EMS 2.45_06, modify table 'sysProperty', add radius authentication paramaters

----- EMS 2.51_10, modify table 'sysProperty', rename and add trap paramaters

----- EMS 2.51_13, modify table 'sysProperty', add syslog paramaters

----- EMS 2.52_01, add table 'inventoryList'
----- EMS 2.52_01, add procedure 'addInventoryList'
----- EMS 2.52_01, add procedure 'getInventoryList'
----- EMS 2.52_01, add procedure 'editInventoryList'
----- EMS 2.52_01, add procedure 'deleteInventoryList'
----- EMS 2.52_01, modify procedure 'deleteAgent', when agent deleted in admin panel, also delete slot(s) of this agent in table inventoryList

----- EMS 2.54_01, remove the script for add table 'inventoryList'
----- EMS 2.54_01, remove the script for add procedure 'addInventoryList'
----- EMS 2.54_01, modify procedure 'getInventoryList'
----- EMS 2.54_01, modify procedure 'editInventoryList'
----- EMS 2.54_01, modify procedure 'deleteInventoryList'
----- EMS 2.54_01, add table 'inventoryListByServer', copy rows of 'inventoryList', then delete 'inventoryList'.

----- EMS 2.54_02, modify table 'nodes', add record for new model FRM220B
----- EMS 2.54_02, modify table 'node_types', add record for new model FRM220B
----- EMS 2.54_02, modify table 'treelinks', add record for new model FRM220B
----- EMS 2.54_02, modify procedure 'addAlias' for FRM220B

----- EMS 2.56_02, modify procedure 'deleteAgent', update script for delete inventory

----- EMS 2.57_01, modify table 'nodes', add record for new Series Industrial
----- EMS 2.57_01, modify table 'nodes', add record for new model IMC-1000M
----- EMS 2.57_01, modify table 'node_types', add record for new model IMC-1000M
----- EMS 2.57_01, modify table 'treelinks', add record for new Series Industrial
----- EMS 2.57_01, modify table 'treelinks', add record for new model IMC-1000M
----- EMS 2.57_01, modify procedure 'addAlias' for IMC-1000M

----- EMS 2.58_01, modify table 'nodes', add record for new model FRM220A-1000EAS/X-1
----- EMS 2.58_01, modify table 'node_types', add record for new model FRM220A-1000EAS/X-1
----- EMS 2.58_01, modify table 'treelinks', add record for new model FRM220A-1000EAS/X-1
----- EMS 2.58_01, modify procedure 'addAlias' for FRM220A-1000EAS/X-1

----- EMS 2.60_01, modify table 'nodes', add record for new model PHB200
----- EMS 2.60_01, modify table 'node_types', add record for new model PHB200
----- EMS 2.60_01, modify table 'treelinks', add record for new model PHB200

----- EMS 2.61_01, modify table 'nodes', add record for new model IGS803
----- EMS 2.61_01, modify table 'node_types', add record for new model IGS803
----- EMS 2.61_01, modify table 'treelinks', add record for new model IGS803
----- EMS 2.61_01, modify table 'inventoryListByServer', change type length 32 to 128. Date: 2014-0317

----- EMS 2.62_01, modify table 'nodes', add record for new model CHT-FRM220-1000EAS
----- EMS 2.62_01, modify table 'node_types', add record for new model CHT-FRM220-1000EAS
----- EMS 2.62_01, modify table 'treelinks', add record for new model CHT-FRM220-1000EAS
----- EMS 2.62_01, modify procedure 'addAlias' for CHT-FRM220-1000EAS

----- EMS 2.62_03, modify table 'nodes', add record for new model MSW202
----- EMS 2.62_03, modify table 'node_types', add record for new model MSW202
----- EMS 2.62_03, modify table 'treelinks', add record for new model MSW202

----- EMS 2.62_03, modify table 'nodes', add record for new model IGS402
----- EMS 2.62_03, modify table 'node_types', add record for new model IGS402
----- EMS 2.62_03, modify table 'treelinks', add record for new model IGS402

----- EMS 2.62_03, modify table 'nodes', add record for new model CHT-FRM220
----- EMS 2.62_03, modify table 'node_types', add record for new model CHT-FRM220
----- EMS 2.62_03, modify table 'treelinks', add record for new model CHT-FRM220
----- EMS 2.62_03, modify procedure 'addAlias' for CHT-FRM220
----- EMS 2.62_03, modify table 'inventoryListByServer', not to change column type varchar length if already varchar 128. Date: 2014-0325

----- EMS 2.63_01, modify table 'nodes', rename model CHT-FRM220-1000EAS to FRM220-1000EAS
----- EMS 2.63_01, modify table 'node_types', rename model CHT-FRM220-1000EAS to FRM220-1000EAS
----- EMS 2.63_01, modify procedure 'addAlias' rename CHT-FRM220-1000EAS to FRM220-1000EAS
----- EMS 2.63_01, modify table 'nodes', remove model CHT-FRM220 id 49
----- EMS 2.63_01, modify table 'node_types', remove model CHT-FRM220 id 49
----- EMS 2.63_01, modify procedure 'addAlias' remove CHT-FRM220
----- EMS 2.63_01, modify procedure 'getAgents'
----- EMS 2.63_01, modify procedure 'editAlarmLog', rename to 'editAlarmLogAck' 
----- EMS 2.63_01, add procedure 'editAlarmLogEndTime'
----- EMS 2.63_01, add table 'alarmType' and create new data
----- EMS 2.63_01, add table 'alarm' and create new data for IGS803, IGS402, MSW202
----- EMS 2.63_01, add procedure 'getAlarms'
----- EMS 2.63_01, add procedure 'editAlarm'

----- EMS 2.64_01, redefine table 'alarm', drop and create table 'alarm'
----- EMS 2.64_01, delete table 'node_types'
----- EMS 2.64_01, modify table 'alarmType', change column 'id' type from int to smallint
----- EMS 2.64_01, modify table 'alarmType', rename type 4 to 'Fault On'
----- EMS 2.64_01, modify table 'alarmType', add new type 8,9,10,11
----- EMS 2.64_01, modify procedure 'addAgent'
----- EMS 2.64_01, modify procedure 'addAlias', identify device by device id
----- EMS 2.64_01, modify procedure 'getAlarms'
----- EMS 2.64_01, modify procedure 'editAlarm'
----- EMS 2.64_01, add procedure 'addAlarm'
----- EMS 2.64_01, add procedure 'deleteAlarm'
----- EMS 2.64_01, add procedure 'deleteAlarm2'
----- EMS 2.64_01, add procedure 'editAlarm'

----- EMS 2.66_01, modify table 'sysProperty', add upgrade paramaters
----- EMS 2.66_01, modify procedure 'editAgent'
----- EMS 2.66_01, modify table 'nodes', add record for new model IMC-100M
----- EMS 2.66_01, modify table 'node_types', add record for new model IMC-100M
----- EMS 2.66_01, modify table 'treelinks', add record for new model IMC-100M
----- EMS 2.66_01, modify procedure 'addAlias' for IMC-100M

----- EMS 2.67_01, modify table 'agent', add column 'version', 'repetition'
----- EMS 2.67_01, modify procedure 'addAgent', add new column 'version', 'repetition'
----- EMS 2.67_01, modify procedure 'editAgent', add new column 'version', 'repetition'
----- EMS 2.67_01, modify procedure 'getAgents', add new column 'version', 'repetition'
----- EMS 2.67_01, modify procedure 'getAgentById', add new column 'version', 'repetition'
----- EMS 2.67_01, modify procedure 'getAgentByName', add new column 'version', 'repetition'
----- EMS 2.67_01, modify procedure 'getAgentsDriverAgents', add new column 'version', 'repetition'

----- EMS 2.68_01, add function 'ipValue'
----- EMS 2.68_01, modify procedure 'getAgents', edit order by column ip_address
----- EMS 2.68_01, modify procedure 'getPollingAgents', edit order by column ip_address
----- EMS 2.68_01, delete procedure 'getPollingAgent'

----- EMS 2.68_01, modify table 'alarmType', add new type 12,13,14,15,16,17,18,19
----- EMS 2.68_01, modify procedure 'addAlarm', add column param for DD alarm threshold
----- EMS 2.68_01, modify procedure 'editAlarm', add column param for DD alarm threshold
----- EMS 2.68_01, if not exists table 'alarm', create table, add one more column param for DD alarm threshold
----- EMS 2.68_01, if exists table 'alarm', alter table, add one more column param for DD alarm threshold
----- EMS 2.68_01, add procedure 'globalEditAlarm'

----- EMS 2.68_01, modify table 'nodes', add record for new model MX210
----- EMS 2.68_01, modify table 'treelinks', add record for new model MX210

----- EMS 2.69_01, remove column remark, add column remark1, remark2, remark3. Date: 2014-0714
----- EMS 2.69_01, add column alias. Date: 2014-0714

----- EMS 2.70_01, modify table 'nodes', add record for new model IGS812
----- EMS 2.70_01, modify table 'treelinks', add record for new model IGS812
----- EMS 2.70_01, modify table 'nodes', add record for new model IGS1604
----- EMS 2.70_01, modify table 'treelinks', add record for new model IGS1604

----- EMS 2.71_01, modify table 'sysProperty', remove upgrade parameters upgradeDeviceType
----- EMS 2.71_01, modify table 'alarmType', add type 'Fiber FEF On'

----- EMS 2.72_01, if not exists table 'alarm', create table, add new column 'model_id'
----- EMS 2.72_01, if exists table 'alarm' and not exists column 'model_id', alter table, add new column 'model_id'
----- EMS 2.72_01, if table 'alarm' has 'model_name' not null, set value for 'model_id', set 'model_name' null
----- EMS 2.72_01, modify procedure 'addAlarm', no parameter for model_name,  add one parameter for 'model_id'
----- EMS 2.72_01, modify procedure 'editAlarm', no paramater for 'model_name'
----- EMS 2.72_01, modify procedure 'globalEditAlarm', no parameter for 'model_name', add one parameter for 'model_id'
----- EMS 2.72_01, add new table 'alarmTemplate' and create new templates for CHT/Zelax/CNT models
----- EMS 2.72_01, add procedure 'getTemplateAlarms'
----- EMS 2.72_01, add procedure 'editTemplateAlarm'

----- EMS 2.72_01, modify table 'nodes', add record for new model IGS404
----- EMS 2.72_01, modify table 'treelinks', add record for new model IGS404

----- EMS 2.73_01, modify table 'nodes', add record for new model FMUX160
----- EMS 2.73_01, modify table 'treelinks', add record for new model FMUX160
----- EMS 2.73_01, modify procedure 'addAlias' for new model FMUX160

----- EMS 2.73_01, modify table 'nodes', add record for new model FMUX80
----- EMS 2.73_01, modify table 'treelinks', add record for new model FMUX80
----- EMS 2.73_01, modify procedure 'addAlias' for new model FMUX80

----- EMS 2.73_01, modify table 'nodes', add record for new model FMUX1600
----- EMS 2.73_01, modify table 'treelinks', add record for new model FMUX1600
----- EMS 2.73_01, modify procedure 'addAlias' for new model FMUX1600

----- EMS 2.73_01, modify table 'nodes', add record for new model FMUX800
----- EMS 2.73_01, modify table 'treelinks', add record for new model FMUX800
----- EMS 2.73_01, modify procedure 'addAlias' for new model FMUX800

----- EMS 2.73_01, modify table 'alarmType', add new type 21~25 
----- EMS 2.73_01, add new alarm template FMUX160, FMUX80, FMUX1600, FMUX800

----- EMS 2.74_01, add table 'pmParameterLog' and index
----- EMS 2.74_01, modify table 'agent', add column 'pm_enable'
----- EMS 2.74_01, modify table 'sysProperty', add performance paramaters
----- EMS 2.74_01, add procedure 'addPmParameterLog'
----- EMS 2.74_01, add procedure 'getPmParameterLog'
----- EMS 2.74_01, add procedure 'deletePmParameterLog'
----- EMS 2.74_01, add procedure 'editAgentPmEnable'
----- EMS 2.74_01, modify procedure 'addAgent', add new column pm_enable
----- EMS 2.74_01, modify procedure 'getAgentById', add new column pm_enable
----- EMS 2.74_01, modify procedure 'getAgentByName', add new column pm_enable
----- EMS 2.74_01, modify procedure 'getAgentsDriverAgents', add new column pm_enable
----- EMS 2.74_02, add procedure 'deletePmParameterLogbyTime'

----- EMS 2.75_01, modify table 'alarmType', rename type 21~24
----- EMS 2.75_01, modify table 'alarmType', add new type 26~42  
----- EMS 2.75_01, add new alarm template iMUX4T/S, iMUX5T/S, iMUX8T/S, iMUX16T/S
----- EMS 2.75_01, add new alarm template 1000T(S)
----- EMS 2.75_01, add new alarm template FTEC
----- EMS 2.75_01, add new alarm template FXOFXS
----- EMS 2.75_01, add new alarm template FXOFXS4

----- EMS 2.75_01, modify table 'nodes', add record for new model FRM220-100AS-1
----- EMS 2.75_01, modify table 'treelinks', add record for new model FRM220-100AS-1
----- EMS 2.75_01, modify table 'nodes', add record for new model FRM220-1000EAS/X-2F
----- EMS 2.75_01, modify table 'treelinks', add record for new model FRM220-1000EAS/X-2F
----- EMS 2.75_01, modify procedure 'addAlias' for FRM220-100AS-1
----- EMS 2.75_01, modify procedure 'addAlias' for FRM220-1000EAS/X-2F
----- EMS 2.75_01, add new alarm templates for Device FRM220A-1000EAS/X, FRM220A-1000EAS/X-1, FRM220-100AS-1, FRM220-1000EAS/X-2F
----- EMS 2.75_01, add new alarm template GFOM04

----- EMS 2.75_01, modify table 'nodes', add record for new model IPS-803
----- EMS 2.75_01, modify table 'treelinks', add record for new model IPS-803
----- EMS 2.75_01, add new alarm template IPS-803

----- EMS 2.76_01, add table 'image'
----- EMS 2.76_01, add table 'topologyDevice'
----- EMS 2.76_01, add table 'topologyDeviceLink'
----- EMS 2.76_01, add table 'topologyEquip'
----- EMS 2.76_01, add table 'topologyEquipLink'
----- EMS 2.76_01, add table 'topologyLocation'
----- EMS 2.76_01, modify table 'sysProperty', add topology paramaters
----- EMS 2.76_01, add procedure 'addImage'
----- EMS 2.76_01, add procedure 'addTopologyDevice'
----- EMS 2.76_01, add procedure 'addTopologyDeviceLink'
----- EMS 2.76_01, add procedure 'addTopologyEquip'
----- EMS 2.76_01, add procedure 'addTopologyEquipLink'
----- EMS 2.76_01, add procedure 'addTopologyLocation'
----- EMS 2.76_01, modify procedure 'treeInsert', rename to 'addTree'
----- EMS 2.76_01, modify procedure 'nodeInsert', rename to 'addTreeNode'
----- EMS 2.76_01, modify procedure 'nodeCopy', rename to 'addTreeNodeFromProduct'
----- EMS 2.76_01, add procedure 'deleteImage'
----- EMS 2.76_01, add procedure 'deleteTopologyDeviceLink'
----- EMS 2.76_01, add procedure 'deleteTopologyEquip'
----- EMS 2.76_01, add procedure 'deleteTopologyEquipLink'
----- EMS 2.76_01, modify procedure 'treeDelete', rename to 'deleteTree'
----- EMS 2.76_01, modify procedure 'deleteNode', rename to 'deleteTreeNode'
----- EMS 2.76_01, add procedure 'editTopologyDevice'
----- EMS 2.76_01, add procedure 'editTopologyEquip'
----- EMS 2.76_01, add procedure 'editTopologyLocation'
----- EMS 2.76_01, modify procedure 'nodeUpdate', rename to 'editTreeNode'
----- EMS 2.76_01, add procedure 'getImage'
----- EMS 2.76_01, add procedure 'getImageInfos'
----- EMS 2.76_01, add procedure 'getTopologyDeviceLinks'
----- EMS 2.76_01, add procedure 'getTopologyDevices'
----- EMS 2.76_01, add procedure 'getTopologyEquipLinks'
----- EMS 2.76_01, add procedure 'getTopologyEquips'
----- EMS 2.76_01, add procedure 'getTopologyLocation'
----- EMS 2.76_01, add procedure 'getTopologyLocations'
----- EMS 2.76_01, add procedure 'getTreeNode'
----- EMS 2.76_01, modify procedure 'deleteAgent', change procedure 'deleteNode' to 'deleteTreeNode'
----- EMS 2.76_01, modify procedure 'selectNodes', change column 'text' varchar 64 to 100
----- EMS 2.76_01, delete procedure 'treeLinkInsert'
----- EMS 2.76_01, modify table 'inventoryListByServer', set column 'status' value to 'online', 'offline'  
----- EMS 2.77_01, modify table 'alarmTemplate', change max ring number from 10 to 5
----- EMS 2.77_01, delete rows of table 'alarmTemplate' and 'alarm' where ring idx>5

----- EMS 2.78_01, modify table 'sysProperty', add upgrade scheduler paramaters

----- EMS 2.79_01, add new alarm template for NMC line card 1000EAS/X-2F and 100AS-1

----- EMS 2.81_01, no column 'acl' when insert into table 'nodes'
----- EMS 2.81_01, add function 'fn_getAllowedNodesByUserName'
----- EMS 2.81_01, add function 'fn_getRolesByUserName'
----- EMS 2.81_01, modify procedure 'deleteTreeNode', remove param '@idx', add param '@selectedNode_id'
----- EMS 2.81_01, modify procedure 'deleteAgent', procedure 'deleteTreeNode' remove param '@idx', add param '@selectedNode_id'
----- EMS 2.81_01, modify procedure 'getUserTrees', add role access check
----- EMS 2.81_01, modify procedure 'selectNodes', add param '@userName' for role access check
----- EMS 2.81_01, modify procedure 'selectNodeLinks', add param '@userName' for role access check
----- EMS 2.81_01, modify procedure 'selectNodeLinks', adjust tree structure before return
----- EMS 2.81_01, modify table 'privilege', rename table to 'userRole'
----- EMS 2.81_01, modify table 'userRole', add column 'function'
----- EMS 2.81_01, add table 'roleAccess'
----- EMS 2.81_01, add table 'clientRole'
----- EMS 2.81_01, modify table 'client', remove column 'acl' after INSERT into new table 'clientRole'
----- EMS 2.81_01, modify procedure 'getClients'
----- EMS 2.81_01, modify procedure 'addClient', remove param acl
----- EMS 2.81_01, modify procedure 'editClient', , remove param acl
----- EMS 2.81_01, add procedure 'getUserRoles'
----- EMS 2.81_01, add procedure 'addUserRole'
----- EMS 2.81_01, add procedure 'editUserRole'
----- EMS 2.81_01, add procedure 'deleteUserRole'
----- EMS 2.81_01, add procedure 'editRoleAccess'
----- EMS 2.81_01, modify procedure 'getTreeNodes', add param 'userName' for role access check
----- EMS 2.81_01, modify procedure 'getTreeLinks', add param 'userName' and check role access
----- EMS 2.81_01, modify procedure 'getTreeLinks', adjust tree structure before return
----- EMS 2.81_01, modify procedure 'loadUserTree', check role access
----- EMS 2.81_01, remove procedure 'treeIsModify'
----- EMS 2.81_01, modify procedure 'admin_agentNodeInsert', remove acl
----- EMS 2.81_01, modify procedure 'admin_agentNodeInsert', new device node default allowed for role administrator/operator/user
----- EMS 2.81_01, modify procedure 'addTreeNode', remove acl
----- EMS 2.81_01, modify procedure 'addTreeNode', new location node default allowed for creator roles and system roles administrator/operator/user
----- EMS 2.81_01, modify procedure 'addTreeNodeFromProduct', default allowed for creator roles
----- EMS 2.81_01, modify procedure 'addTree', remove acl
----- EMS 2.81_01, modify procedure 'addTree', new tree default allowed for creator roles and system roles administrator/operator/user

----- EMS 2.82_01, add new alarm template for NMC line card 16G-3R
----- EMS 2.82_01, if table 'nodes' exists column 'acl', change to NULL

----- EMS 2.83_01, modify procedure 'getUserRoles', move 'Radius Id' from the first column to the last.

----- EMS 2.84_01, modify procedure 'addTreeNodeFromProduct', check if creator roles can access child nodes

----- EMS 2.85_01, modify table 'trees', set type as public if not Product Tree
----- EMS 2.85_01, add procedure 'getTreeCreator'

----- EMS 2.86_01, modify table 'nodes', add record for new model IGS-804
----- EMS 2.86_01, modify table 'treelinks', add record for new model IGS-804
----- EMS 2.86_01, add new alarm template IGS-804

----- EMS 2.88_01, modify procedure 'getInventoryList', temp table column 'type' length should be 128
----- EMS 2.88_01, modify procedure 'addUserRole', add param 'nodeIds'
----- EMS 2.88_01, modify procedure 'editUserRole', add param 'nodeIds', 'isNodeChanged'
----- EMS 2.88_01, modify procedure 'selectNodes', fix bug that loss Product Tree nodes
----- EMS 2.88_01, modify procedure 'selectNodeLinks', fix bug that in the same level index doesn't reset when different parent
----- EMS 2.88_01, modify procedure 'addTreeNode', add one more 'WHERE AND' conditon for creator roles
----- EMS 2.88_01, modify procedure 'addTreeNodeFromProduct', add one more 'WHERE AND' condition for creator roles
----- EMS 2.88_01, modify procedure 'getUserRoles', default roles Administrator/Operator/User fixed at top
----- EMS 2.88_01, modify table 'userRole', add column 'radius_id'
----- EMS 2.88_01, modify procedure 'getUserRoles', add new column 'radius_id'
----- EMS 2.88_01, modify procedure 'addUserRole', add new column 'radius_id'
----- EMS 2.88_01, modify procedure 'editUserRole', add new column 'radius_id'
----- EMS 2.88_01, modify procedure 'deleteUserRole', param is radius_id
----- EMS 2.88_01, add table 'clientACL'

----- EMS 2.88_01, modify table 'client', change 'description' length 50 to 200. UI length 32, DB needs 192.
----- EMS 2.88_01, modify table 'client', change 'division' length 32 to 100. UI length 16, DB needs 96.
----- EMS 2.88_01, modify table 'client', change 'phone' length 32 to 100. UI length 16, DB needs 96.
----- EMS 2.88_01, modify table 'client', change 'address' length 50 to 200. UI length 32, DB needs 192.
----- EMS 2.88_01, modify procedure 'getClients', change column length, 'descripation' and 'address'.
----- EMS 2.88_01, modify procedure 'addClient', change colunm length, 'phone', 'division', 'address', and 'description'.
----- EMS 2.88_01, modify procedure 'editClient', change colunm length, 'phone', 'division', 'address', and 'description'.
----- EMS 2.88_01, modify table 'userRole', change 'description' length 50 to 200. UI length 32, DB needs 192.
----- EMS 2.88_01, modify procedure 'getUserRoles', change 'description' length 100 to 200. UI length 32, DB needs 192.
----- EMS 2.88_01, modify procedure 'addUserRole', change 'description' length 50 to 200. UI length 32, DB needs 192.
----- EMS 2.88_01, modify procedure 'editUserRole', change 'description' length 50 to 200. UI length 32, DB needs 192.

----- EMS 2.88_01, add table 'clientActionClassify'
----- EMS 2.88_01, add table 'clientActionCode'
----- EMS 2.88_01, add table 'clientActionContentCode'
----- EMS 2.88_01, add table 'clientActionLog'
----- EMS 2.88_01, remove table 'clientAction', 'clientlog', 'clientlogact'
----- EMS 2.88_01, remove procedure 'addClientLog'
----- EMS 2.88_01, remove procedure 'getClientLogs' 
----- EMS 2.88_02, remove check primary key of table 'clientAction'
----- EMS 2.88_01, remove procedure 'addClientAction'
----- EMS 2.88_01, remove procedure 'getClientActions'
----- EMS 2.88_01, add procedure 'getClientActionLog' 
----- EMS 2.88_01, add procedure 'addClientActionLog'
----- EMS 2.88_01, remove procedure 'admin_clientlog_clear'
----- EMS 2.88_01, remove procedure 'admin_clientaction_clear'

----- EMS 2.88_01, modify procedure 'deleteAgent', delete client action log of this agent
----- EMS 2.88_01, modify procedure 'deleteTreeNode', add write to clientActionLog
----- EMS 2.88_01, modify procedure 'deleteTree', add write to clientActionLog
----- EMS 2.88_01, modify procedure 'addTopologyEquip', add write to clientActionLog

----- EMS 2.88_01, add function 'fn_isHasIllegalChar'
----- EMS 2.88_01, add function 'fn_rmvIllegalChar'
----- EMS 2.88_01, to avoid clientActionLog content parse error, repalce (space,comma,colon,brackets,quote) with '_'
----- EMS 2.88_01, modify table 'alias' column 'name', repalce (space,comma,colon,brackets,quote) with '_' 
----- EMS 2.88_01, modify table 'nodes' column 'name', id>1000, repalce (space,comma,colon,brackets,quote) with '_' 
----- EMS 2.88_01, modify table 'topologyEquip' column 'name', repalce (space,comma,colon,brackets,quote) with '_' 
----- EMS 2.88_01, modify table 'topologyEquipLink' column 'name2', repalce (space,comma,colon,brackets,quote) with '_' 

----- EMS 2.88_01, modify table 'sysProperty', add syslog parameters 'Login', 'Logout', 'Configure Param'
----- EMS 2.88_01, modify table 'sysProperty', add disk usage parameter
----- EMS 2.88_01, modify table 'sysProperty', add user idle parameter 

----- EMS 2.88_01, add table 'pmParamErrCode'
----- EMS 2.88_01, add table 'pmParamDataType'
----- EMS 2.88_01, modify table 'pmParameterLog', add column 'type' and 'errCode', tinyint one byte, 0~255
----- EMS 2.88_01, modify procedure 'addPmParameterLog', add 'errCode' and 'dataType'
----- EMS 2.88_01, modify procedure 'getPmParameterLog', add 'errCode' and 'dataType'
----- EMS 2.88_01, add procedure 'editPmParameterLog'

----- EMS 2.88_01, add procedure 'getAgentIds'

----- EMS 2.88_01, modify table 'nodes', add record for new model FRM220R4
----- EMS 2.88_01, modify table 'treelinks', add record for new model FRM220R4
----- EMS 2.88_01, modify procedure 'addAlias' for FRM220R4

----- EMS 2.88_01, modify table 'alarmType', add new type 43~47
----- EMS 2.88_01, add new alarm template NMC-R4
----- EMS 2.88_01, add new alarm template for NMC-R4 line card 12G-3R
----- EMS 2.88_01, modify table 'alarmType', add new type 50,51,52
----- EMS 2.88_01, add new alarm template for NMC-R4 line card Protection
----- EMS 2.88_01, modify table 'alarmType', add new type 53,54,55

----- EMS 2.87_15, modify table 'inventoryListByServer', change 'alias' length 128 to 768. UI length 128, DB needs 768.

----- EMS 2.88_01, modify table 'alarmType', rename type 26 to 'Signal Loss'

----- EMS 2.89_03, modify procedure 'getTreeLinks', fix SQL 2014 order by issue
----- EMS 2.89_03, modify procedure 'getAlarmLogs', fix SQL 2014 order by issue
----- EMS 2.89_03, modify procedure 'getTrapLogs', fix SQL 2014 order by issue
----- EMS 2.89_03, modify procedure 'getInventoryList', fix SQL 2014 order by issue
----- EMS 2.87_15, modify procedure 'getInventoryList', change alias length 128 to 768. UI length 128, DB needs 768.
----- EMS 2.88_01, modify procedure 'getClientActionLog', fix SQL 2014 ordry by issue

----- EMS 2.90_01, modify table 'nodes', add record for new model MSW404
----- EMS 2.90_01, modify table 'nodes', add record for new model ICSG24S4X
----- EMS 2.90_01, modify table 'nodes', add record for new model ICSG24S2X
----- EMS 2.90_01, modify table 'nodes', add record for new model IGS-S2804TM
----- EMS 2.90_01, modify table 'nodes', add record for new model MSW4424A
----- EMS 2.90_01, modify table 'treelinks', add record for new model MSW404
----- EMS 2.90_01, modify table 'treelinks', add record for new model ICSG24S4X
----- EMS 2.90_01, modify table 'treelinks', add record for new model ICSG24S2X
----- EMS 2.90_01, modify table 'treelinks', add record for new model IGS-S2804TM
----- EMS 2.90_01, modify table 'treelinks', add record for new model MSW4424A
----- EMS 2.90_01, add new alarm template MSW404
----- EMS 2.90_01, add new alarm template MSW4424A
----- EMS 2.90_01, add new alarm template ICSG24S4X
----- EMS 2.90_01, add new alarm template ICSG24S2X
----- EMS 2.90_01, add new alarm template IGS-S2804TM
----- EMS 2.90_01, modify table 'alarmType', add new type 49
----- EMS 2.90_01, ICSG24S4X(93) has 14 ring
----- EMS 2.90_01, ICSG24S2X(94) has 13 ring
----- EMS 2.90_01, IGS-S2804TM(95) has 14 ring

----- EMS 2.90_01, add table 'timeSynchornizer'
----- EMS 2.90_01, modify table 'agent', add column 'syncTime'
----- EMS 2.90_01, modify table 'sysProperty', add ntpServerAddress paramaters
----- EMS 2.90_01, add procedure 'editAgentTimeSyncer'
----- EMS 2.90_01, add procedure 'getAgentTimeSyncer'
----- EMS 2.90_01, modify procedure 'addAgent', add column 'syncTime'

----- EMS 2.90_01, modify table 'nodes', change 'name' length 100 to 768. UI length 128, DB needs 768.
----- EMS 2.90_01, modify table 'alias', change 'name' length 200 to 768. UI length 128, DB needs 768.
----- EMS 2.90_01, modify table 'inventoryListByServer', change 'alias' length 128 to 768. UI length 128, DB needs 768.

----- EMS 2.90_01, modify procedure 'addAgent', change name length 100 to 768. UI length 128, DB needs 768.
----- EMS 2.90_01, modify procedure 'admin_agentNodeInsert', change agent_name length 100 to 768. UI length 128, DB needs 768.
----- EMS 2.90_01, modify procedure 'getPollingAgents', change name length 100 to 768. UI length 128, DB needs 768.
----- EMS 2.90_01, modify procedure 'editAgent', change name length 100 to 768. UI length 128, DB needs 768.
----- EMS 2.90_01, modify procedure 'getAgentByName', change agentName length 100 to 768. UI length 128, DB needs 768.
----- EMS 2.90_01, modify table 'inventoryListByServer', change alias length 128 to 768. UI length 128, DB needs 768.
----- EMS 2.90_01, modify procedure 'editTreeNode', change name length 100 to 768. UI length 128, DB needs 768.
----- EMS 2.90_01, modify procedure 'addTree', change name length 100 to 768. UI length 128, DB needs 768.
----- EMS 2.90_01, modify procedure 'addTreeNode', change name length 100 to 768. UI length 128, DB needs 768.

----- EMS 2.91_01, modify table 'nodes', add record for new model GSW3208M2
----- EMS 2.91_01, modify table 'treelinks', add record for new model GSW3208M2
----- EMS 2.91_01, add new alarm template GSW3208M2

----- EMS 2.92_01, modify table 'nodes', add record for new model GSW1005MS
----- EMS 2.92_01, modify table 'treelinks', add record for new model GSW1005MS
----- EMS 2.92_01, add new alarm template GSW1005MS
----- EMS 2.92_01, modify table 'alarmType', add type 56,57
----- EMS 2.92_01, modify table 'alarmType', rename type 11-17,19 to add 'Fiber' description
----- EMS 2.92_01, modify table 'alarmTemplate', add FRM220A template type 56,57

----- EMS 2.93_01, modify table 'clientACL', add empty ip/mac for users not in white list
----- EMS 2.93_01, modify procedure 'addClient', add default empty ACL ip/mac

----- EMS 2.94_01, modify table 'clientActionLog', change 'content' length 128 to 3840
----- EMS 2.94_01, modify procedure 'getClientActionLog', change content column length 128 to 3840 
----- EMS 2.94_01, modify procedure 'addClientActionLog', change content length 128 to 3840
----- EMS 2.94_01, modify table 'timeSynchornizer', add rows disable/ntp/ems

----- EMS 2.97_01, modify table 'userRole', fix radius id bug
----- EMS 2.97_01, modify table 'userRole', change 'name' and 'description' length to 768. UI length 128, DB needs 768.
----- EMS 2.97_01, modify procedure 'getUserRoles', change length of all columns to 768
----- EMS 2.97_01, modify procedure 'getUserRoles', replace user name list with total user number
----- EMS 2.97_01, modify procedure 'addUserRole', change length of all columns to 768
----- EMS 2.97_01, modify procedure 'editUserRole', change length of all columns to 768

----- EMS 2.97_01, modify table 'client', change length of all columns to 768
----- EMS 2.97_01, modify procedure 'getClients', change length of all columns to 768
----- EMS 2.97_01, modify procedure 'getClients', replace role name list with total role number

----- EMS 2.99_01, modify table 'alarmType', add type 58 to 64
----- EMS 2.99_01, add new alarm template NMC-R3 line card Eoe1/GS
----- EMS 2.99_01, add new alarm template for NMC-R3 line card OPS51
----- EMS 2.99_01, modify table 'nodes', add record for new model MSW4424C
----- EMS 2.99_01, modify table 'treelinks', add record for new model MSW4424C
----- EMS 2.99_01, add new alarm template MSW4424C
----- EMS 2.99_01, add new alarm template for NMC-R3 line card FMC1000MS

----- EMS 2.100_01, modify table 'sysProperty', add 'trapDeviceAlarm'
----- EMS 2.100_01, modify table 'alarmType', add type 65
----- EMS 2.100_01, modify table 'alarmTemplate', add NMC-R4 template type 65

----- EMS 2.100_01, modify procedure 'addTopologyEquip', fix write to clientActionLog content length bug
----- EMS 2.100_01, modify procedure 'getClientActionLog', fix actionId 410 bug, if2 becomes equip name, length not enough

----- EMS 2.101, modify table 'alarmType', add type 66
----- EMS 2.101, table 'alarmTemplate', add id 1055 FRM220-OAB15 template.

----- EMS 2.102, table 'nodes', add IGS-1608SM-8PH
----- EMS 2.102, table 'nodes', add IFS-1608GSM-8PH
----- EMS 2.102, table 'nodes', add IGS-1608SM-SE
----- EMS 2.102, table 'treelinks', add IGS-1608SM-8PH
----- EMS 2.102, table 'treelinks', add IFS-1608GSM-8PH
----- EMS 2.102, table 'treelinks', add IGS-1608SM-SE
----- EMS 2.102, table 'alarmTemplate', add IGS-1608SM-8PH
----- EMS 2.102, table 'alarmTemplate', add IFS-1608GSM-8PH
----- EMS 2.102, table 'alarmTemplate', add IGS-1608SM-SE
----- EMS 2.102, table 'nodes', update name for IFS/IGS-812SM

----- EMS 2.200, modify procedure 'selectNodes', change column 'text' varchar 100 to 768
----- EMS 2.200, modify procedure 'deleteTree', change @treeNodeName varchar 100 to varchar 768
----- EMS 2.200, delete procedure 'getPollingAgent', change type error 'getPollingAgents' to 'getPollingAgent'
----- EMS 2.200, change procedure 'loadUserTree' to 'getUserTree'

----- Definition Area
----- Definition: Table Structure
----- Definition: Function
----- Definition: Stored Procedure
----- Definition: Table Structure
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------

----- EMS 2.14_01, add table 'sysProperty' and add record
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[sysProperty]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
	CREATE TABLE [dbo].[sysProperty](
		[name]  [varchar](50)  NOT NULL,
		[value] [varchar](128) NOT NULL,
		CONSTRAINT [PK_sysProperty] PRIMARY KEY CLUSTERED 
		(
			[name] ASC
		) ON [PRIMARY]
	) ON [PRIMARY]
		
	INSERT INTO [sysProperty] ([name], [value]) VALUES ('backupAuto',        '0')   
	INSERT INTO [sysProperty] ([name], [value]) VALUES ('backupRule',        '1')
	INSERT INTO [sysProperty] ([name], [value]) VALUES ('backupStartTime',   '')    
	INSERT INTO [sysProperty] ([name], [value]) VALUES ('backupEndTime',     '')     
	INSERT INTO [sysProperty] ([name], [value]) VALUES ('backupRestoreTime', '')
	INSERT INTO [sysProperty] ([name], [value]) VALUES ('historyPeriodRecord', '3')     
	INSERT INTO [sysProperty] ([name], [value]) VALUES ('historyPeriodFile',   '3')     
	INSERT INTO [sysProperty] ([name], [value]) VALUES ('historyAutoFile',     '0') 
END
GO


----- EMS 2.14_02, modify table 'sysProperty', add record
----- EMS 2.45_06, modify table 'sysProperty', add add radius authentication paramaters
----- EMS 2.51_10, modify table 'sysProperty', rename and add trap paramaters
----- EMS 2.51_13, modify table 'sysProperty', add syslog paramaters
----- EMS 2.66_01, modify table 'sysProperty', add upgrade paramaters
----- EMS 2.71_01, modify table 'sysProperty', remove upgrade parameters upgradeDeviceType
----- EMS 2.74_01, modify table 'sysProperty', add performance paramaters
----- EMS 2.76_01, modify table 'sysProperty', add topology paramaters
----- EMS 2.78_01, modify table 'sysProperty', add upgrade scheduler paramaters
----- EMS 2.88_01, modify table 'sysProperty', remove syslog parameters, UserLog and ActionLog
----- EMS 2.88_01, modify table 'sysProperty', add syslog parameters 'Login', 'Logout', 'Configure Param'
----- EMS 2.88_01, modify table 'sysProperty', add disk usage parameter
----- EMS 2.88_01, modify table 'sysProperty', add user idle parameter
----- EMS 2.90_01, modify table 'sysProperty', add ntpServerAddress paramaters
----- EMS 2.100_01, modify table 'sysProperty', add 'trapDeviceAlarm'
 
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[sysProperty]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='pmInterval')	
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('pmInterval',    '15') 
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='pmThread')	
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('pmThread',      '2')         
	
	IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='radiusEnable')	
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('radiusEnable',  '0')     
        
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='radiusAddress')    		    
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('radiusAddress', '10.1.1.1')  		
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='radiusPort')    	
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('radiusPort',    '1812')  		
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='radiusSecret')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('radiusSecret',  'secret')
        
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='syslogEnable')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('syslogEnable',   '0')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='syslogAddress')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('syslogAddress',  '10.1.1.1')

    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='syslogPort')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('syslogPort',     '514')

	DECLARE @oldUserEnable varchar(4),@oldUserFac varchar(4),@oldUserSev varchar(4),
			@oldActEnable varchar(4),@oldActFac varchar(4),@oldActSev varchar(4) 
	SET @oldUserEnable = '0' 
	SET @oldUserFac    = '4' 
	SET @oldUserSev    = '5' 
	SET @oldActEnable  = '0' 
	SET @oldActFac     = '10' 
	SET @oldActSev     = '5' 

	IF EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='syslogUserLog') 
	BEGIN
		SET @oldUserEnable = (SELECT value FROM sysProperty WHERE name='syslogUserLog') 
		SET @oldUserFac    = (SELECT value FROM sysProperty WHERE name='syslogFacUser')
		SET @oldUserSev    = (SELECT value FROM sysProperty WHERE name='syslogSevUser')
		SET @oldActEnable  = (SELECT value FROM sysProperty WHERE name='syslogActionLog') 
		SET @oldActFac     = (SELECT value FROM sysProperty WHERE name='syslogFacAction')
		SET @oldActSev     = (SELECT value FROM sysProperty WHERE name='syslogSevAction')
		
		DELETE FROM sysProperty WHERE name='syslogUserLog' 
		DELETE FROM sysProperty WHERE name='syslogFacUser' 
		DELETE FROM sysProperty WHERE name='syslogSevUser' 
		DELETE FROM sysProperty WHERE name='syslogActionLog' 
		DELETE FROM sysProperty WHERE name='syslogFacAction' 
		DELETE FROM sysProperty WHERE name='syslogSevAction' 
	END
	
	-- enable or not
	IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='syslogLogin')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('syslogLogin', @oldUserEnable)
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='syslogLogout')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('syslogLogout', @oldUserEnable)

    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='syslogConfigParam')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('syslogConfigParam', @oldActEnable)

	-- facility
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='syslogFacLogin')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('syslogFacLogin', @oldUserFac)
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='syslogFacLogout')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('syslogFacLogout', @oldUserFac)
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='syslogFacConfigParam')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('syslogFacConfigParam', @oldActFac)  
    
	-- severity
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='syslogSevLogin')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('syslogSevLogin', @oldUserSev)
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='syslogSevLogout')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('syslogSevLogout', @oldUserSev)
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='syslogSevConfigParam')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('syslogSevConfigParam', @oldActSev)  
    
    
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='topologyLock')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('topologyLock', '0') 
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='topologyName')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('topologyName', '1') 
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='trapEnable')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('trapEnable',     '0')  
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='trapDeviceDisconnect')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('trapDeviceDisconnect', '0')	

    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='trapDeviceAlarm')
	    INSERT INTO [sysProperty] ([name], [value]) VALUES ('trapDeviceAlarm', '0')
        
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='trapDeviceName')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('trapDeviceName', '0')        

    IF EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='trapForwardAddress')	
        UPDATE [dbo].[sysProperty] SET [name]='trapReceiverIP' WHERE [name]='trapForwardAddress' 
    ELSE              		
	    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='trapReceiverIP')	   
		    INSERT INTO [sysProperty] ([name], [value]) VALUES ('trapReceiverIP', '10.1.1.1')

    IF EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='trapForwardPort')	
        UPDATE [dbo].[sysProperty] SET [name]='trapPort' WHERE [name]='trapForwardPort'	
    ELSE
	    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='trapPort')	  	    
		    INSERT INTO [sysProperty] ([name], [value]) VALUES ('trapPort',       '162')         
        
    IF EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='trapForwardCommunity')	
        UPDATE [dbo].[sysProperty] SET [name]='trapCommunity' WHERE [name]='trapForwardCommunity'	
    ELSE
	    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='trapCommunity')	  
		    INSERT INTO [sysProperty] ([name], [value]) VALUES ('trapCommunity',  'public')          

    IF EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='trapForwardEnable' AND [value]='1')
        UPDATE [dbo].[sysProperty] SET [value]='1' WHERE [name]='trapEnable'     
    
    IF EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='trapForwardEnable')
        UPDATE [dbo].[sysProperty] SET [name]='trapForwarding' WHERE [name]='trapForwardEnable'   
    ELSE
	    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='trapForwarding')
		    INSERT INTO [sysProperty] ([name], [value]) VALUES ('trapForwarding', '0')
		                
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='upgradeInterval')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('upgradeInterval',   '3')  
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='upgradeTftpAddress')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('upgradeTftpAddress', '10.1.1.1')          
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='upgradeTftpFile')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('upgradeTftpFile',   'firmware.img') 
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='upgradeSchedulerEnable')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('upgradeSchedulerEnable', '0')
        
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='upgradeSchedulerTime')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('upgradeSchedulerTime', '0') 

	IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='diskUsageWarn')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('diskUsageWarn', '80') 

    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='diskUsageStop')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('diskUsageStop', '99') 
        
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='diskUsageStopAutoRestart')   
		INSERT INTO [sysProperty] ([name], [value]) VALUES ('diskUsageStopAutoRestart', '0') 
		
	IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='userIdleLogoutMinutes')   
		INSERT INTO [sysProperty] ([name], [value]) VALUES ('userIdleLogoutMinutes', '30') 
		
	IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='userIdleLogoutEnable')   
		INSERT INTO [sysProperty] ([name], [value]) VALUES ('userIdleLogoutEnable', '1') 
    
    IF NOT EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='ntpServerAddress')   
        INSERT INTO [sysProperty] ([name], [value]) VALUES ('ntpServerAddress', '211.22.103.158') 
    
     
    IF EXISTS (SELECT * FROM [dbo].[sysProperty] WHERE [name]='upgradeDeviceType')   
        DELETE [sysProperty] WHERE name='upgradeDeviceType'
                  
END
GO


----- EMS 2.15_04, modify table 'broker', add column 'enable'
----- create column 'enable'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[broker]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
	IF NOT EXISTS(select * from sysobjects o, syscolumns c where o.id=c.id and o.name='broker' and c.name='enable' and c.xtype=(select t.xtype from systypes t where t.name='bit'))
		ALTER TABLE [dbo].[broker] ADD [enable] bit
GO
 
----- check if enable active broker, if not, means column 'enable' is a new column
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[broker]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )	
	IF EXISTS(select * from sysobjects o, syscolumns c where o.id=c.id and o.name='broker' and c.name='enable' and c.xtype=(select t.xtype from systypes t where t.name='bit'))	
		IF NOT EXISTS(SELECT * FROM broker WHERE enable=1)	
		BEGIN 
			UPDATE [dbo].[broker] SET enable=0

			DECLARE @broker_id int
			SELECT @broker_id=val FROM params WHERE id=1
			UPDATE [dbo].[broker] SET enable=1 WHERE id=@broker_id
		END
GO

----- alter column 'enable' to be not null
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[broker]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
	IF EXISTS(select * from sysobjects o, syscolumns c where o.id=c.id and o.name='broker' and c.name='enable' and c.xtype=(select t.xtype from systypes t where t.name='bit'))	
		IF NOT EXISTS(select * from sysobjects o, syscolumns c where o.id=c.id and o.name='broker' and c.name='enable' and c.xtype=(select t.xtype from systypes t where t.name='bit') and c.isnullable=0)	
			ALTER TABLE [dbo].[broker] ALTER COLUMN [enable] bit NOT NULL
GO 

----- EMS 2.15_04, modify table 'broker', add primary key
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[broker]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[PK_broker]') AND OBJECTPROPERTY(id, N'IsPrimaryKey')=1)
		ALTER TABLE [dbo].[broker] ADD CONSTRAINT [PK_broker] PRIMARY KEY CLUSTERED ( [id] ASC) 
GO


----- EMS 2.20_01, modify table 'nodes', add record for new model FRM220A
----- EMS 2.31_01, modify table 'nodes', add record for new model FRM220A-1000EAS/X
----- EMS 2.31_01, modify table 'nodes', add record for model FRM220-10/100AS-2 
----- EMS 2.35_07, modify table 'nodes', add record for new model FMUX04E
----- EMS 2.36_02, modify table 'nodes', add record for new model ERM-MUX/Plus
----- EMS 2.54_02, modify table 'nodes', add record for new model FRM220B
----- EMS 2.57_01, modify table 'nodes', add record for new Series Industrial
----- EMS 2.57_01, modify table 'nodes', add record for new model IMC-1000M
----- EMS 2.58_01, modify table 'nodes', add record for new model FRM220A-1000EAS/X-1
----- EMS 2.60_01, modify table 'nodes', add record for new model PHB200
----- EMS 2.61_01, modify table 'nodes', add record for new model IGS803
----- EMS 2.62_01, modify table 'nodes', add record for new model CHT-FRM220-1000EAS
----- EMS 2.62_03, modify table 'nodes', add record for new model MSW202
----- EMS 2.62_03, modify table 'nodes', add record for new model IGS402
----- EMS 2.62_03, modify table 'nodes', add record for new model CHT-FRM220
----- EMS 2.63_01, modify table 'nodes', rename model CHT-FRM220-1000EAS to FRM220-1000EAS
----- EMS 2.63_01, modify table 'nodes', remove model CHT-FRM220 id 49
----- EMS 2.66_01, modify table 'nodes', add record for new model IMC-100M
----- EMS 2.68_01, modify table 'nodes', add record for new model MX210
----- EMS 2.70_01, modify table 'nodes', add record for new model IGS812
----- EMS 2.70_01, modify table 'nodes', add record for new model IGS1604
----- EMS 2.72_01, modify table 'nodes', add record for new model IGS404
----- EMS 2.73_01, modify table 'nodes', add record for new model FMUX160
----- EMS 2.73_01, modify table 'nodes', add record for new model FMUX80
----- EMS 2.73_01, modify table 'nodes', add record for new model FMUX1600
----- EMS 2.73_01, modify table 'nodes', add record for new model FMUX800
----- EMS 2.75_01, modify table 'nodes', add record for new model FRM220-100AS-1
----- EMS 2.75_01, modify table 'nodes', add record for new model FRM220-1000EAS/X-2F
----- EMS 2.75_01, modify table 'nodes', add record for new model IPS-803
----- EMS 2.75_01, modify table 'nodes', add record for new model FRM220-100AS-1
----- EMS 2.75_01, modify table 'nodes', add record for new model FRM220-1000EAS/X-2F
----- EMS 2.81_01, no column 'acl' when insert into table 'nodes'
----- EMS 2.86_01, modify table 'nodes', add record for new model IGS-804
----- EMS 2.88_01, modify table 'nodes', add record for new model FRM220R4
----- EMS 2.90_01, modify table 'nodes', add record for new model MSW404
----- EMS 2.90_01, modify table 'nodes', add record for new model ICSG24S4X
----- EMS 2.90_01, modify table 'nodes', add record for new model ICSG24S2X
----- EMS 2.90_01, modify table 'nodes', add record for new model IGS-S2804TM
----- EMS 2.90_01, modify table 'nodes', add record for new model MSW4424A
----- EMS 2.91_01, modify table 'nodes', add record for new model GSW3208M2
----- EMS 2.92_01, modify table 'nodes', add record for new model GSW1005MS
----- EMS 2.99_01, modify table 'nodes', add record for new model MSW4424C
----- EMS 2.102, table 'nodes', add IGS-1608SM-8PH
----- EMS 2.102, table 'nodes', add IFS-1608GSM-8PH
----- EMS 2.102, table 'nodes', add IGS-1608SM-SE
----- EMS 2.102, table 'nodes', update name for IFS/IGS-812SM

----- EMS 2.82_01, if table 'nodes' exists column 'acl', change to NULL
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[nodes]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
	IF EXISTS (SELECT * FROM syscolumns WHERE name='acl' and id=OBJECT_ID('nodes'))
    BEGIN
        ALTER TABLE nodes ALTER COLUMN acl INTEGER NULL	
    END
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[nodes]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
	-- add model FRM220A
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='41')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (41, 'FRM220A', 1, 1)
	
	-- add model FRM220A-1000EAS/X
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='42')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (42, 'FRM220A-1000EAS/X', 1, 1)
		
    -- add model FRM220-10/100AS-2 to replace FRM220100AS2 model id 70 to new mode id 43 
    -- but dont delete the existing record 'FRM220100AS2' id 70, or the existing system could not work
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='43')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (43, 'FRM220-10/100AS-2', 1, 1)
	
	-- add model FRM220B
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='44')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (44, 'FRM220B', 1, 1)
	
	-- add model FRM220A-1000EAS/X-1
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='45')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (45, 'FRM220A-1000EAS/X-1', 1, 1)
	
	-- add model PHB200
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='46')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (46, 'PHB200', 1, 1)
	
	-- add model FRM220-1000EAS
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='47')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (47, 'FRM220-1000EAS', 1, 1)	
	
	-- rename model CHT-FRM220-1000EAS to FRM220-1000EAS
	IF EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='47' AND [name]='CHT-FRM220-1000EAS')
        UPDATE [nodes] SET [name]='FRM220-1000EAS' WHERE [id]='47'

	-- add model MSW202
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='48')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (48, 'MSW202', 1, 1)	
	
	-- remove model CHT-FRM220 id 49
    IF EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='49' AND [name]='CHT-FRM220')
    BEGIN
        -- remove nodes from model CHT-FRM220
        DELETE [nodes] WHERE [id]='49' AND [name]='CHT-FRM220'
       	
       	-- change nodes which type_id is CHT-FRM220 to FRM220
       	UPDATE [nodes] SET [type_id]='40' WHERE [type_id]='49'
       	
        -- remove treelinks for CHT-FRM220
    	DELETE [treelinks] WHERE [tree_id]='1' AND [child_id]='49'
        
        -- change treelink which parent_id/child_id is CHT-FRM220 to FRM220
    	UPDATE [treelinks] SET [parent_id]='40' WHERE [parent_id]='49' 
    	UPDATE [treelinks] SET [child_id]='40' WHERE [child_id]='49' 
    END	   
        
	-- add model MX210
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='49')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (49, 'MX210', 1, 1)	
	
	
	-- add model FMUX04E
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='33')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (33, 'FMUX04E', 1, 1)		
	
	-- add model FMUX160
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='34')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (34, 'FMUX160', 1, 1)		
	
	-- add model FMUX80
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='35')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (35, 'FMUX80', 1, 1)		
	
	-- add model FMUX1600
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='36')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (36, 'FMUX1600', 1, 1)		
	
	-- add model FMUX800
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='37')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (37, 'FMUX800', 1, 1)		
		
	-- add model ERM-MUX/Plus
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='25')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (25, 'ERM-MUX/Plus', 1, 1)
		
	-- add series Industrial
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='7')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (7, 'Series_Industrial', 1, 1)	
		
	-- add model IMC-1000M
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='71')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (71, 'IMC-1000M', 1, 1)
		
	-- add model IGS-803
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='72')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (72, 'IFS/IGS-803SM', 1, 1)	
	
	-- add model IGS-402
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='73')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (73, 'IFS/IGS-402SM', 1, 1)	
	
	-- add model IMC-100M
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='74')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (74, 'IMC-100M', 1, 1)
		
	-- add model IGS-812
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='75')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (75, 'IFS/IGS-812SM', 1, 1)	

    -- correct IFS/IGS-812SM wrong name 'IFS/IGS-803SM'  
	IF EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='75' AND [name]='IFS/IGS-803SM')
		UPDATE [nodes] SET [name]='IFS/IGS-812SM' WHERE [id]='75'			
		
	-- add model IGS-1604
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='76')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (76, 'IFS/IGS-1604SM', 1, 1)		
									
	-- add model IGS-404
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='77')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (77, 'IFS/IGS-404SM', 1, 1)
		
	-- add model IPS-803
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='78')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (78, 'IPS-803SM', 1, 1)
		
	-- add model IGS-804
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='79')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (79, 'IFS/IGS-804SM', 1, 1)			

	-- add model FRM220-100AS-1
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='80')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (80, 'FRM220-100AS-1', 1, 1)	
								
	-- add model FRM220-1000EAS/X-2F
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='81')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (81, 'FRM220-1000EAS/X-2F', 1, 1)

	-- add model MSW4424C
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='82')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (82, 'MSW4424C', 1, 1)
		
	-- add model FRM220R4
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='83')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (83, 'FRM220-R4', 1, 1)
		
	-- add model MSW404
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='84')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (84, 'MSW404', 1, 1)		
	
	-- add model MSW4424A
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='85')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (85, 'MSW4424A', 1, 1)			
		
	-- add model GSW3208M2
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='86')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (86, 'GSW3208M2', 1, 1)			
	
	-- add model GSW1005MS
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='87')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (87, 'GSW1005MS', 1, 1)			
			
	-- 90,91,92 reserved for ITP
	
	-- add model ICSG24S4X
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='93')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (93, 'ICS-G24S4X', 1, 1)
		
	-- add model ICSG24S2X
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='94')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (94, 'ICS-G24S2X', 1, 1)		
	
	-- add model IGS-S2804TM
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='95')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (95, 'IGS-S2804TM', 1, 1)	
	
	-- model IGS-1608SM-8PH
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='96')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (96, 'IGS-1608SM-8PH', 1, 1)	
		
	-- model IFS-1608GSM-8PH	
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='97')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (97, 'IFS-1608GSM-8PH', 1, 1)			
		
	-- model IGS-1608SM-SE	
	IF NOT EXISTS (SELECT * FROM [dbo].[nodes] WHERE [id]='98')
		INSERT INTO [nodes] ([id], [name], [type_id], [client_id]) VALUES (98, 'IGS-1608SM-SE', 1, 1)	
END
GO

----- EMS 2.64_01, delete table 'node_types'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[node_types]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
	IF EXISTS (SELECT * FROM sysobjects o, syscolumns c WHERE o.id=c.id AND o.name='node_types' AND c.name='is_hardware')
	    DROP TABLE node_types
GO


----- EMS 2.20_01, modify table 'treelinks', add record for new model FRM220A
----- EMS 2.31_01, modify table 'treelinks', add record for new model FRM220A-1000EAS/X
----- EMS 2.31_01, modify table 'treelinks', add record for model FRM220-10/100AS-2
----- EMS 2.31_01, modify table 'treelinks', delete record model Series_Standalone
----- EMS 2.31_01, modify table 'treelinks', delete record model FRM220100AS2
----- EMS 2.35_07, modify table 'treelinks', add record for new model FMUX04E
----- EMS 2.36_02, modify table 'treelinks', add record for new model ERM-MUX/Plus
----- EMS 2.54_02, modify table 'treelinks', add record for new model FRM220B
----- EMS 2.57_01, modify table 'treelinks', add record for new Series Industrial
----- EMS 2.57_01, modify table 'treelinks', add record for new model IMC-1000M
----- EMS 2.58_01, modify table 'treelinks', add record for new model FRM220A-1000EAS/X-1
----- EMS 2.60_01, modify table 'treelinks', add record for new model PHB200
----- EMS 2.61_01, modify table 'treelinks', add record for new model IGS803
----- EMS 2.62_01, modify table 'treelinks', add record for new model CHT-FRM220-1000EAS
----- EMS 2.62_03, modify table 'treelinks', add record for new model MSW202
----- EMS 2.62_03, modify table 'treelinks', add record for new model IGS402
----- EMS 2.62_03, modify table 'treelinks', add record for new model CHT-FRM220
----- EMS 2.63_01, modify table 'treelinks', remove model CHT-FRM220
----- EMS 2.66_01, modify table 'treelinks', add record for new model IMC-100M
----- EMS 2.68_01, modify table 'treelinks', add record for new model MX210
----- EMS 2.70_01, modify table 'treelinks', add record for new model IGS812
----- EMS 2.70_01, modify table 'treelinks', add record for new model IGS1604
----- EMS 2.72_01, modify table 'treelinks', add record for new model IGS404
----- EMS 2.73_01, modify table 'treelinks', add record for new model FMUX160
----- EMS 2.73_01, modify table 'treelinks', add record for new model FMUX80
----- EMS 2.73_01, modify table 'treelinks', add record for new model FMUX1600
----- EMS 2.73_01, modify table 'treelinks', add record for new model FMUX800
----- EMS 2.75_01, modify table 'treelinks', add record for new model IPS-803
----- EMS 2.75_01, modify table 'treelinks', add record for new model FRM220-100AS-1
----- EMS 2.75_01, modify table 'treelinks', add record for new model FRM220-1000EAS/X-2F
----- EMS 2.86_01, modify table 'treelinks', add record for new model IGS-804
----- EMS 2.88_01, modify table 'treelinks', add record for new model FRM220R4
----- EMS 2.90_01, modify table 'treelinks', add record for new model MSW404
----- EMS 2.90_01, modify table 'treelinks', add record for new model ICSG24S4X
----- EMS 2.90_01, modify table 'treelinks', add record for new model ICSG24S2X
----- EMS 2.90_01, modify table 'treelinks', add record for new model IGS-S2804TM
----- EMS 2.90_01, modify table 'treelinks', add record for new model MSW4424A
----- EMS 2.91_01, modify table 'treelinks', add record for new model GSW3208M2
----- EMS 2.92_01, modify table 'treelinks', add record for new model GSW1005MS
----- EMS 2.99_01, modify table 'treelinks', add record for new model MSW4424C
----- EMS 2.102, table 'treelinks', add IGS-1608SM-8PH
----- EMS 2.102, table 'treelinks', add IFS-1608GSM-8PH
----- EMS 2.102, table 'treelinks', add IGS-1608SM-SE

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[treelinks]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    -- add FRM220A
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='41')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 41, 1, 2)

    -- add FRM220A-1000EAS/X
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='42')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 42, 2, 2)		

    -- add model FRM220-10/100AS-2 to replace FRM220100AS2 model id 70 to new mode id 43 
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='43')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 43, 3, 2)	
	
	-- add FRM220B
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='44')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 44, 4, 2)
	
	-- add FRM220A-1000EAS/X-1
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='45')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 45, 5, 2)
	
	-- add PHB200
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='46')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 46, 6, 2)
		
	-- add FRM220-1000EAS
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='47')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 47, 7, 2)	
	
	-- add MSW202
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='48')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 48, 8, 2)	
	
	-- add MX210
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='49')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 49, 9, 2)	
	
    -- add FMUX04E
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='33')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 3, 33, 3, 2)	
	
	-- add FMUX160
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='34')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 3, 34, 4, 2)	
	
	-- add FMUX80
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='35')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 3, 35, 5, 2)	
	
	-- add FMUX1600
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='36')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 3, 36, 6, 2)	
	
	-- add FMUX800
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='37')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 3, 37, 7, 2)	
		
    -- add ERM-MUX/Plus
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='25')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 2, 25, 4, 2)
	
    -- delete model 'Series_Standalone' id 7		
	IF EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='7')
	    DELETE treelinks WHERE tree_id='1' AND child_id='7'
			
	-- delete model 'FRM220100AS2' id 70	
	IF EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='70')
	    DELETE treelinks WHERE tree_id='1' AND child_id='70'	   
	    
	-- add Series Industrial
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='7')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 1, 7, 5, 1)	    
	
	-- add IMC-1000M
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='71')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 7, 71, 0, 2)	
		
	-- add IGS-803
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='72')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 7, 72, 1, 2)		    
	
	-- add IGS-402
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='73')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 7, 73, 2, 2)
		
	-- add IMC-100M
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='74')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 7, 74, 3, 2)				    
	
	-- add IGS-812
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='75')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 7, 75, 4, 2)				    
	
	-- add IGS-1604
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='76')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 7, 76, 5, 2)				    
	
	-- add IGS-404
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='77')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 7, 77, 6, 2)
		
	-- add IPS-803
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='78')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 7, 78, 7, 2)	
		
	-- add IGS-804
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='79')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 7, 79, 8, 2)		

	-- add FRM220-100AS-1
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='80')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 80, 10, 2)
		    
	-- add FRM220-1000EAS/X-2F
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='81')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 81, 11, 2)

	-- add MSW4424C
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='82')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 82, 17, 2)
			
	-- add FRM220R4
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='83')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 83, 12, 2)
	
	-- add MSW404
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='84')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 84, 13, 2)
	
	-- add MSW4424A
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='85')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 85, 14, 2)
		
	-- add GSW3208M2
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='86')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 86, 15, 2)
	
	-- add GSW1005MS
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='87')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 4, 87, 16, 2)

	-- 90,91,92 reserved for ITP	
		
	-- add ICSG24S4X
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='93')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 7, 93, 9, 2)		
		
	-- add ICSG24S2X
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='94')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 7, 94, 10, 2)		
	
	-- add IGS-S2804TM
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='95')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 7, 95, 11, 2)
		
    -- IGS-1608SM-8PH
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='96')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 7, 96, 12, 2)
		
    -- IFS-1608GSM-8PH
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='97')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 7, 97, 13, 2)	

    -- IGS-1608SM-SE
	IF NOT EXISTS (SELECT * FROM [dbo].[treelinks] WHERE [tree_id]='1' AND [child_id]='98')
		INSERT INTO treelinks ([tree_id], [parent_id], [child_id], [idx], [lvl]) values(1, 7, 98, 14, 2)			
END
GO

----- EMS 2.30_01, add table 'alarmlog'
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[alarmLog]') AND type in (N'U'))
BEGIN
    CREATE TABLE [dbo].[alarmLog](
	    [id] [int] IDENTITY(1,1) NOT NULL,
	    [agent_id] [int] NOT NULL,
	    [time_begin] [datetime] NOT NULL,
	    [time_end] [datetime] NOT NULL,
	    [location] [varchar](100) NOT NULL,
	    [severity] [int] NOT NULL,
	    [message] [varchar](100) NOT NULL,
	    [ack] [tinyint] NOT NULL,
	    [client_id] [int] NULL,
	    [time_ack] [datetime] NOT NULL,
        CONSTRAINT [PK_alarmLog] PRIMARY KEY CLUSTERED 
        (
    	    [id] ASC
        )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
END
GO

IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_alarmLog_agent]') AND parent_object_id = OBJECT_ID(N'[dbo].[alarmLog]'))
    ALTER TABLE [dbo].[alarmLog]  WITH CHECK ADD  CONSTRAINT [FK_alarmLog_agent] FOREIGN KEY([agent_id])
    REFERENCES [dbo].[agent] ([id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
GO
ALTER TABLE [dbo].[alarmLog] CHECK CONSTRAINT [FK_alarmLog_agent]
GO

IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_alarmLog_client]') AND parent_object_id = OBJECT_ID(N'[dbo].[alarmLog]'))
    ALTER TABLE [dbo].[alarmLog]  WITH CHECK ADD  CONSTRAINT [FK_alarmLog_client] FOREIGN KEY([client_id])
    REFERENCES [dbo].[client] ([id])
    ON UPDATE CASCADE
    ON DELETE SET NULL
GO
ALTER TABLE [dbo].[alarmLog] CHECK CONSTRAINT [FK_alarmLog_client]
GO


----- EMS 2.14_01, modify table 'clientAction', add primary key
----- EMS 2.15_02, modify table 'clientAction', check if table is existed when adding primary key
----- EMS 2.88_02, remove check primary key of table 'clientAction'

----- EMS 2.15_04, modify table 'agentsdriver', set column 'broker_id' to not null
----- EMS 2.15_04, modify table 'agentsdriver', add primary key
----- EMS 2.15_04, modify table 'agentsdriver', add foreign key    
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[agentsdriver]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    -- set column 'broker_id' to be not null
    IF EXISTS (SELECT * FROM sysobjects o, syscolumns c WHERE o.id=c.id AND o.name='agentsdriver' AND c.name='broker_id' AND c.isnullable=1)
	    ALTER TABLE [dbo].[agentsdriver] ALTER COLUMN [broker_id] int NOT NULL;
	
	-- set PK
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[PK_agentsdriver]') AND OBJECTPROPERTY(id, N'IsPrimaryKey')=1)
		ALTER TABLE [dbo].[agentsdriver] ADD CONSTRAINT [PK_agentsdriver] PRIMARY KEY CLUSTERED ( [id] ASC) 
	
	-- set FK
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[FK_agentsdriver_broker]') AND OBJECTPROPERTY(id, N'IsForeignKey')=1)
	BEGIN	
		ALTER TABLE [dbo].[agentsdriver]  WITH CHECK ADD  CONSTRAINT [FK_agentsdriver_broker] FOREIGN KEY([broker_id])
		REFERENCES [dbo].[broker] ([id])
		ON UPDATE CASCADE
		ON DELETE CASCADE

		ALTER TABLE [dbo].[agentsdriver] CHECK CONSTRAINT [FK_agentsdriver_broker]	
	END
END	
GO	


----- EMS 2.41_02, modify table 'agentsdriver', rename column 'pollingperiod' to 'poll_interval' 
----- EMS 2.45_01, modify table 'agentsdriver', rename column 'poll_interval' to 'interval'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[agentsdriver]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
	IF EXISTS (SELECT * FROM sysobjects o, syscolumns c WHERE o.id=c.id AND o.name='agentsdriver' AND c.name='poll_interval')
	    EXEC sp_rename 'agentsdriver.poll_interval', 'interval', 'COLUMN'
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[agentsdriver]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
	IF EXISTS (SELECT * FROM sysobjects o, syscolumns c WHERE o.id=c.id AND o.name='agentsdriver' AND c.name='pollingperiod' AND c.xtype=(SELECT t.xtype FROM systypes t WHERE t.name='int') )
	    EXEC sp_rename 'agentsdriver.pollingperiod', 'interval', 'COLUMN'
GO
IF @@ROWCOUNT = 1		
	UPDATE agentsdriver SET interval=ISNULL(interval, 1000)/1000
GO
	

----- EMS 2.41_02, modify table 'agentsdriver', rename column 'pollinginterval' to 'poll_timeout' 	
----- EMS 2.45_01, modify table 'agentsdriver', rename column 'poll_timeout' to 'timeout'  
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[agentsdriver]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
    IF EXISTS(SELECT * FROM sysobjects o, syscolumns c WHERE o.id=c.id AND o.name='agentsdriver' AND c.name='poll_timeout')
	    EXEC sp_rename 'agentsdriver.poll_timeout', 'timeout', 'COLUMN'   	    
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[agentsdriver]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
	IF EXISTS (SELECT * FROM sysobjects o, syscolumns c WHERE o.id=c.id AND o.name='agentsdriver' AND c.name='pollinginterval' AND c.xtype=(SELECT t.xtype FROM systypes t WHERE t.name='int') )
	    EXEC sp_rename 'agentsdriver.pollinginterval', 'timeout', 'COLUMN' 
GO
IF @@ROWCOUNT = 1	
	UPDATE agentsdriver SET timeout=ISNULL(timeout, 1000)/1000	
GO


----- EMS 2.45_01, modify table 'agentsdriver', set column 'interval' to not null
----- EMS 2.45_01, modify table 'agentsdriver', set column 'timeout' to not null
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[agentsdriver]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    IF EXISTS (SELECT * FROM sysobjects o, syscolumns c WHERE o.id=c.id AND o.name='agentsdriver' AND c.name='interval' AND c.isnullable=1)
	    ALTER TABLE [dbo].[agentsdriver] ALTER COLUMN [interval] int NOT NULL;	     
    
    IF EXISTS (SELECT * FROM sysobjects o, syscolumns c WHERE o.id=c.id AND o.name='agentsdriver' AND c.name='timeout' AND c.isnullable=1)
	    ALTER TABLE [dbo].[agentsdriver] ALTER COLUMN [timeout] int NOT NULL;		    
END	    
GO


----- EMS 2.45_01, modify table 'agentsdriver', add column 'thread'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[agentsdriver]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
    IF NOT EXISTS(SELECT * FROM sysobjects o, syscolumns c WHERE o.id=c.id AND o.name='agentsdriver' AND c.name='thread')
	    ALTER TABLE [dbo].[agentsdriver] ADD [thread] int
GO
IF EXISTS (SELECT * FROM sysobjects o, syscolumns c WHERE o.id=c.id AND o.name='agentsdriver' AND c.name='thread' AND c.isnullable=1)
BEGIN		
    UPDATE agentsdriver SET thread=1 WHERE thread IS NULL	
		
	ALTER TABLE [dbo].[agentsdriver] ALTER COLUMN [thread] int NOT NULL   
END
GO


----- EMS 2.15_04, modify table 'adlinks', remove column 'id'  
-----                                      set column 'agentsdriver_id' to not null
-----                                      set column 'agent_id' to not null
-----                                      add primary key column 'id', 'agent_id', 'agentsdriver_id'
-----                                      add foreign key column 'agentsdriver_id'  
-----                                      add foreign key column 'agent_id'  
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[adlinks]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
	-- remove column
	IF EXISTS (select * from sysobjects o, syscolumns c where o.id=c.id and o.name='adlinks' and c.name='id')
		ALTER TABLE [dbo].[adlinks] DROP COLUMN [id];
	
	-- set column to be not null for FK/PK
	ALTER TABLE [dbo].[adlinks] ALTER COLUMN [agentsdriver_id] int NOT NULL;
	ALTER TABLE [dbo].[adlinks] ALTER COLUMN [agent_id] int NOT NULL;
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[adlinks]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
	-- set PK		
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[PK_adlinks]') AND OBJECTPROPERTY(id, N'IsPrimaryKey')=1)
		ALTER TABLE [dbo].[adlinks] ADD CONSTRAINT [PK_adlinks] PRIMARY KEY CLUSTERED ( [agent_id] ASC, [agentsdriver_id] ASC) 

	-- set FK
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[FK_adlinks_agentsdriver]') AND OBJECTPROPERTY(id, N'IsForeignKey')=1)
	BEGIN	
		ALTER TABLE [dbo].[adlinks]  WITH CHECK ADD CONSTRAINT [FK_adlinks_agentsdriver] FOREIGN KEY([agentsdriver_id])
		REFERENCES [dbo].[agentsdriver] ([id])
		ON UPDATE CASCADE
		ON DELETE CASCADE

		ALTER TABLE [dbo].[adlinks] CHECK CONSTRAINT [FK_adlinks_agentsdriver]	
	END			
	
	IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[FK_adlinks_agent]') AND OBJECTPROPERTY(id, N'IsForeignKey')=1)
	BEGIN	
		ALTER TABLE [dbo].[adlinks]  WITH CHECK ADD CONSTRAINT [FK_adlinks_agent] FOREIGN KEY([agent_id])
		REFERENCES [dbo].[agent] ([id])
		ON UPDATE CASCADE
		ON DELETE CASCADE

		ALTER TABLE [dbo].[adlinks] CHECK CONSTRAINT [FK_adlinks_agent]	
	END	
END	
GO


----- EMS 2.44_07, modify table 'trapList', rename column 'timestamp_system' to 'time'
-----                                       rename column 'trap_id' to 'specific_type'
-----                                       rename column 'timestamp_device' to 'timestamp'
-----                                       rename column 'body' to 'message'
-----                                       rename column 'timestamp_client' to 'time_ack'
-----                                       change column 'remark' type
-----                                       add column 'client_id'
-----                                       remove column 'op_name' 
-----                                       rename primary key 'PK_traplist' to 'PK_traplog'
-----                                       rename foreign key 'FK_traplist_agent' to 'FK_traplog_agent'
-----                                       rename column 'ack' constraint default to 'DF_trapLog_ack'
-----                                       rename column 'clear' constraint default to 'DF_trapLog_clear'
-----                                       rename table 'trapList' to 'trapLog' 
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[trapList]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    Declare @default_name varchar(50)
    
    -- rename column 'timestamp_system' to 'time' 
    IF EXISTS (SELECT * FROM syscolumns WHERE name='timestamp_system' and id=OBJECT_ID('trapList'))
        EXEC sp_rename 'trapList.timestamp_system', 'time', 'COLUMN'
    
    -- rename column 'trap_id' to 'specific_type' 
    IF EXISTS (SELECT * FROM syscolumns WHERE name='trap_id' and id=OBJECT_ID('trapList'))
        EXEC sp_rename 'trapList.trap_id', 'specific_type', 'COLUMN'

    -- rename column 'timestamp_device' to 'timestamp'
    IF EXISTS (SELECT * FROM syscolumns WHERE name='timestamp_device' and id=OBJECT_ID('trapList'))
        EXEC sp_rename 'trapList.timestamp_device', 'timestamp', 'COLUMN'

    -- rename column 'body' to 'message'
    IF EXISTS (SELECT * FROM syscolumns WHERE name='body' and id=OBJECT_ID('trapList'))
        EXEC sp_rename 'trapList.body', 'message', 'COLUMN'

    -- rename column 'timestamp_client' to 'time_ack'
    IF EXISTS (SELECT * FROM syscolumns WHERE name='timestamp_client' and id=OBJECT_ID('trapList'))
    BEGIN
        -- rename column 'timestamp_client' to 'time_ack'
        EXEC sp_rename 'trapList.timestamp_client', 'time_ack', 'COLUMN'
    
        -- remove column constraint default 
        SELECT @default_name=OBJECT_NAME(cdefault) FROM syscolumns WHERE name='time_ack' AND id=OBJECT_ID('traplist')
        IF @default_name IS NOT NULL
            EXEC ('ALTER TABLE trapList DROP CONSTRAINT ' +@default_name)

        -- define column type        
        ALTER TABLE trapList ALTER COLUMN time_ack datetime 
    END
    
    -- change column 'remark' type
    IF EXISTS (SELECT * FROM syscolumns WHERE name='remark' and id=OBJECT_ID('trapList'))
    BEGIN
        -- remove column constraint default 
        SELECT @default_name=OBJECT_NAME(cdefault) FROM syscolumns WHERE name='remark' AND id=OBJECT_ID('traplist')
        IF @default_name IS NOT NULL
            EXEC ('ALTER TABLE trapList DROP CONSTRAINT ' +@default_name)
        
        -- define column type to be null
        ALTER TABLE trapList ALTER COLUMN remark varchar(50)
    END
    
    
    -- add column 'client_id'
    IF NOT EXISTS (SELECT * FROM syscolumns WHERE name='client_id' and id=OBJECT_ID('trapList'))
    BEGIN
        -- add column 'client_id'
        ALTER TABLE trapList ADD client_id int
        
        -- add foreign key
        ALTER TABLE trapList ADD CONSTRAINT FK_trapLog_client 
            FOREIGN KEY ( client_id ) REFERENCES dbo.client ( id ) 
	        ON UPDATE CASCADE 
	        ON DELETE SET NULL 
    END
END           
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[trapList]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    Declare @default_name varchar(50)
    
    -- update column 'client_id' value
    IF EXISTS (SELECT * FROM syscolumns WHERE name='client_id' and id=OBJECT_ID('trapList')) 
        AND EXISTS (SELECT * FROM syscolumns WHERE name='op_name' and id=OBJECT_ID('trapList'))
        -- update column 'client_id' value according to column 'op_name'         
        UPDATE trapList SET client_id=(SELECT c.id FROM client c WHERE c.name=op_name) WHERE ack=1
            
    -- remove column 'op_name'            
    IF EXISTS (SELECT * FROM syscolumns WHERE name='op_name' and id=OBJECT_ID('trapList'))
        ALTER TABLE trapList DROP COLUMN op_name  
    
    -- rename primary key 'PK_trapList' to 'PK_trapLog'
    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[PK_trapList]') AND OBJECTPROPERTY(id, N'IsPrimaryKey')=1)
        EXEC sp_rename 'PK_trapList', 'PK_trapLog'
  
    -- rename foreign key 'FK_trapList_agent' to 'FK_trapLog_agent'
    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[FK_trapList_agent]') AND OBJECTPROPERTY(id, N'IsForeignKey')=1)
        EXEC sp_rename 'FK_trapList_agent', 'FK_trapLog_agent'  
    
    -- rename column 'ack' constraint default to 'DF_trapLog_ack'
    SELECT @default_name=OBJECT_NAME(cdefault) FROM syscolumns WHERE name='ack' AND id=OBJECT_ID('traplist')
        IF @default_name IS NOT NULL
            EXEC ('sp_rename '''+ @default_name +''', ''DF_trapLog_ack''')

    -- rename column 'clear' constraint default to 'DF_trapLog_clear'
    SELECT @default_name=OBJECT_NAME(cdefault) FROM syscolumns WHERE name='clear' AND id=OBJECT_ID('traplist')
        IF @default_name IS NOT NULL
            EXEC ('sp_rename '''+ @default_name +''', ''DF_trapLog_clear''')
    
    -- rename table 'trapList' to 'trapLog'
    EXEC sp_rename 'trapList', 'trapLog'        
END
GO


----- EMS 2.45_05, modify table 'pmList', rename column 'timestamp_system' to 'time'
-----                                     rename column 'timestamp_device' to 'timestamp'
-----                                     rename primary key 'PK_threshold' to 'PK_pmLog'
-----                                     rename foreign key 'FK_threshold_agent' to 'FK_pmLog_agent'
-----                                     rename table 'pmList' to 'pmLog' 
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[pmList]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    -- rename column 'timestamp_system' to 'time' 
    IF EXISTS (SELECT * FROM syscolumns WHERE name='timestamp_system' and id=OBJECT_ID('pmList'))
        EXEC sp_rename 'pmList.timestamp_system', 'time', 'COLUMN'
    
    -- rename column 'timestamp_device' to 'timestamp'
    IF EXISTS (SELECT * FROM syscolumns WHERE name='timestamp_device' and id=OBJECT_ID('pmList'))
        EXEC sp_rename 'pmList.timestamp_device', 'timestamp', 'COLUMN'

    -- rename primary key 'PK_threshold' to 'PK_pmLog'
    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[PK_threshold]') AND OBJECTPROPERTY(id, N'IsPrimaryKey')=1)
        EXEC sp_rename 'PK_threshold', 'PK_pmLog'
  
    -- rename foreign key 'FK_threshold_agent' to 'FK_pmLog_agent'
    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[FK_threshold_agent]') AND OBJECTPROPERTY(id, N'IsForeignKey')=1)
        EXEC sp_rename 'FK_threshold_agent', 'FK_pmLog_agent'  
    
    -- rename table 'pmList' to 'pmLog'
    EXEC sp_rename 'pmList', 'pmLog'        
END
GO

----- EMS 2.54_01, add table 'inventoryListByServer'
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO

----- EMS 2.90_01, modify table 'inventoryListByServer', change alias length 128 to 768. UI length 128, DB needs 768.
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[inventoryListByServer]'))
BEGIN	
	CREATE TABLE [dbo].[inventoryListByServer](
		[id] [int] IDENTITY(1,1) NOT NULL,
		[agent_id] [int] NOT NULL,
		[location] [varchar](64) NOT NULL,
		[type] [varchar](128) NOT NULL,
		[HW] [varchar](32) NOT NULL,
		[FW] [varchar](32) NOT NULL,
		[SN] [varchar](32) NOT NULL,
		[alias] [varchar](768) NULL,
		[status] [varchar](16) NOT NULL,
		[date] [datetime] NOT NULL,
		[userId] [varchar](512) NULL,
		[remark1] [varchar](512) NULL,
		[remark2] [varchar](512) NULL,
		[remark3] [varchar](512) NULL,
	 CONSTRAINT [PK_inventoryListByServer] PRIMARY KEY CLUSTERED 
	(
		[agent_id] ASC,
		[location] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
ELSE 
BEGIN
	----- EMS 2.61_01, modify table 'inventoryListByServer', change type length 32 to 128. Date: 2014-0317
	----- EMS 2.62_03, modify table 'inventoryListByServer', not to change column type varchar length if already varchar 128. Date: 2014-0325
	IF (select CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='inventoryListByServer' and COLUMN_NAME='type' ) < 128 	
	BEGIN 
		ALTER TABLE inventoryListByServer ALTER COLUMN type VARCHAR(128) 
	END
		
	----- EMS 2.69_01, remove column remark, add column remark1, remark2, remark3. Date: 2014-0714
	IF EXISTS (SELECT * FROM syscolumns WHERE name='remark' and id=OBJECT_ID('inventoryListByServer'))
    BEGIN    
        ALTER TABLE inventoryListByServer DROP COLUMN remark 
        ALTER TABLE inventoryListByServer ADD remark1 VARCHAR(512) 
        ALTER TABLE inventoryListByServer ADD remark2 VARCHAR(512) 
        ALTER TABLE inventoryListByServer ADD remark3 VARCHAR(512) 
    END
    
    ----- EMS 2.69_01, add column alias. Date: 2014-0714
    ----- EMS 2.90_01, modify table 'inventoryListByServer', change alias length 128 to 768. UI length 128, DB needs 768.
    IF NOT EXISTS (SELECT * FROM syscolumns WHERE name='alias' and id=OBJECT_ID('inventoryListByServer'))
    BEGIN    
        ALTER TABLE inventoryListByServer ADD alias VARCHAR(768) 
    END	

    ----- EMS 2.76_01, modify table 'inventoryListByServer', set column 'status' value to 'online', 'offline'  
    IF EXISTS(SELECT * FROM inventoryListByServer WHERE status IN('On Line', 'Off Line'))
    BEGIN
	    UPDATE inventoryListByServer SET status='Online' WHERE status='On Line'
	    UPDATE inventoryListByServer SET status='Offline' WHERE status='Off Line'
    END	
    	
END

SET ANSI_PADDING OFF
GO

DECLARE 
	@old_id     varchar(64),
	@old_date   datetime,
	@old_userId varchar(512),
	@old_remark varchar(512),
	@old_rownum int,
	@counter    int,
	@agtId      varchar(32),
	@typId      varchar(32),
	@location   varchar(64),
	@rack       varchar(64),
	@slot       varchar(64),
	@site       varchar(64),
	@tmp1       varchar(512),
	@tmp2       varchar(512),
	@tmp3       varchar(512),
	@rackNum    int,
	@slotNum    int

SET @old_rownum = 0

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[inventoryList]'))	
	SELECT @old_rownum = COUNT(*) FROM inventoryList

	
IF @old_rownum > 0
BEGIN
	SET @counter = 1
	
	WHILE(@counter <= @old_rownum)
	BEGIN
			SELECT @old_id=id, @old_date=date, @old_userId=userId, @old_remark=remark FROM (SELECT ROW_NUMBER() OVER(ORDER BY id ASC) AS row, * FROM inventorylist) sub WHERE row = @counter
			SET @agtId = SUBSTRING(@old_id, 1, CHARINDEX(' ',@old_id)-1)
			SELECT @typId = type_id FROM nodes WHERE id=@agtId
			SET @location = SUBSTRING(@old_id, CHARINDEX(' ',@old_id)+1, LEN(@old_id)-CHARINDEX(' ',@old_id))
			
			
			IF @typId = 40 OR @typId = 41
			BEGIN
				SET @rack = SUBSTRING(@location, 1, CHARINDEX(' ',@location)-1)
				SET @location = SUBSTRING(@location, CHARINDEX(' ',@location)+1, LEN(@location)-CHARINDEX(' ',@location))
				
				SET @rackNum = cast(SUBSTRING(@rack,3,2) AS INT)
				SET @rack = '[4:'+CAST(@rackNum AS varchar(8))+']'
				
				SET @site = SUBSTRING(@location, 1, CHARINDEX(' ',@location)-1)
				SET @location = SUBSTRING(@location, CHARINDEX(' ',@location)+1, LEN(@location)-CHARINDEX(' ',@location))
				
				IF @site = '1:00'
				BEGIN
					SET @site = '[1]'
					SET @slotNum = (cast(SUBSTRING(@location,3,2) AS INT))+1
					SET @slot = '[5:'+CAST(@slotNum AS varchar(8))+']'
				END
				ELSE IF @site = '2:01'
				BEGIN
					SET @slot = SUBSTRING(@location, 1, CHARINDEX(' ',@location)-1)
					SET @site = SUBSTRING(@location, CHARINDEX(' ',@location)+1, LEN(@location)-CHARINDEX(' ',@location))
					
					SET @slotNum = (cast(SUBSTRING(@slot,3,2) AS INT))+1
					SET @slot = '[5:'+CAST(@slotNum AS varchar(8))+']'
					SET @site = '['+SUBSTRING(@site,1,1)+']'
				END
				
				INSERT INTO inventoryListByServer (agent_id, location, type, HW, FW, SN, status, date, userId, remark1)
				VALUES(@agtId, @rack+@slot+@site, 'None', 'None', 'None', 'None', 'Offline', @old_date, @old_userId, @old_remark)
			END
			ELSE IF @typId = 42
			BEGIN
				IF @location = '1:00'
				BEGIN
					SET @location = '[1]'
				END
				ELSE IF @location = '2:01'
				BEGIN
					SET @location = '[6]'
				END
				ELSE IF @location = '2:02'
				BEGIN
					SET @location = '[7]'
				END
				
				INSERT INTO inventoryListByServer (agent_id, location, type, HW, FW, SN, status, date, userId, remark1)
				VALUES(@agtId, @location, 'None', 'None', 'None', 'None', 'Offline', @old_date, @old_userId, @old_remark)
			END
			
			
			SET @counter = @counter + 1
	END
END

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[inventoryList]'))	
	DROP TABLE inventoryList
GO


----- EMS 2.63_01, add table 'alarmType' and create new data
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[alarmType]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[alarmType](
    	[id] [int] NOT NULL,
    	[name] [varchar](50) NOT NULL,
     CONSTRAINT [PK_AlarmType] PRIMARY KEY CLUSTERED 
    (
    	[id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    
    INSERT INTO alarmType (id, name) VALUES (1, 'Power Off')
    INSERT INTO alarmType (id, name) VALUES (2, 'UTP Link Down')
    INSERT INTO alarmType (id, name) VALUES (3, 'Fiber Link Down')
    INSERT INTO alarmType (id, name) VALUES (4, 'RelayAlarm')
    INSERT INTO alarmType (id, name) VALUES (5, 'PoE Power Buget Exceed')
    INSERT INTO alarmType (id, name) VALUES (6, 'PoE PD overload')
    INSERT INTO alarmType (id, name) VALUES (7, 'Ring Fault')
END
GO


----- EMS 2.64_01, modify table 'alarmType', change column 'id' type from int to smallint
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[alarmType]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
    IF EXISTS (SELECT * FROM sysobjects o, syscolumns c WHERE o.id=c.id AND o.name='alarmType' AND c.name='id' AND c.xtype=(SELECT xtype FROM systypes WHERE name='int'))
    BEGIN
        -- delete alarm FK, PK 
        IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[alarm]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
    		IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[FK_Alarm_AlarmType]') AND OBJECTPROPERTY(id, N'IsForeignKey')=1 )
    		BEGIN
    			ALTER TABLE alarm DROP CONSTRAINT FK_Alarm_AlarmType
    			ALTER TABLE alarm DROP CONSTRAINT PK_Alarm
    			ALTER TABLE alarm ALTER COLUMN type smallint NOT NULL	
    		END
        
        -- update alarmType column id
        ALTER TABLE alarmType DROP CONSTRAINT PK_AlarmType
        ALTER TABLE alarmType ALTER COLUMN id smallint NOT NULL
        ALTER TABLE alarmType ADD CONSTRAINT PK_AlarmType PRIMARY KEY CLUSTERED ( [id] ASC) 
    
        -- recover alarm FK, PK
	    IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[alarm]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
		    IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[FK_Alarm_AlarmType]'))
		    BEGIN
				ALTER TABLE [dbo].[alarm] ADD  CONSTRAINT [PK_Alarm] PRIMARY KEY CLUSTERED ([device_type] ASC, [type] ASC, [idx] ASC)	    
			    ALTER TABLE [dbo].[alarm]  WITH CHECK ADD CONSTRAINT FK_Alarm_AlarmType FOREIGN KEY([type])
			    REFERENCES [dbo].[alarmType] ([id])
			    ON UPDATE CASCADE
			    ON DELETE CASCADE

			    ALTER TABLE [dbo].[alarm] CHECK CONSTRAINT [FK_Alarm_AlarmType]		
		    END    
	END    
GO

----- EMS 2.64_01, modify table 'alarmType', rename type 4 to 'Fault On'
----- EMS 2.64_01, modify table 'alarmType', add new type 8,9,10,11
----- EMS 2.68_01, modify table 'alarmType', add new type 12,13,14,15,16,17,18,19
----- EMS 2.71_01, modify table 'alarmType', add type 'Fiber FEF On'
----- EMS 2.73_01, modify table 'alarmType', add new type 21~25
----- EMS 2.75_01, modify table 'alarmType', rename type 21~24
----- EMS 2.75_01, modify table 'alarmType', add new type 26~42
----- EMS 2.88_01, modify table 'alarmType', add new type 43~47
----- EMS 2.88_01, modify table 'alarmType', add new type 50,51,52
----- EMS 2.88_01, modify table 'alarmType', add new type 53,54,55
----- EMS 2.88_01, modify table 'alarmType', rename type 26 to 'Signal Loss'
----- EMS 2.90_01, modify table 'alarmType', add new type 49
----- EMS 2.92_01, modify table 'alarmType', add type 56,57
----- EMS 2.92_01, modify table 'alarmType', rename type 11-17,19 to add 'Fiber' description
----- EMS 2.99_01, modify table 'alarmType', add type 58 to 64
----- EMS 2.100_01, modify table 'alarmType', add type 65
----- EMS 2.101, modify table 'alarmType', add type 66

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[alarmType]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    IF EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='4' AND [name]='RelayAlarm')
	    UPDATE alarmType SET name='Fault On' WHERE id=4 AND name='RelayAlarm'
	    
	IF EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='11' AND [name]='Loopback Test')
	    UPDATE alarmType SET name='Fiber Loopback Test' WHERE id=11 AND name='Loopback Test' 
	    
	IF EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='12' AND [name]='Rx Power Low')
	    UPDATE alarmType SET name='Fiber Rx Power Low' WHERE id=12 AND name='Rx Power Low' 	    

	IF EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='13' AND [name]='Rx Power Error')
	    UPDATE alarmType SET name='Fiber Rx Power Error' WHERE id=13 AND name='Rx Power Error' 
	    
	IF EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='14' AND [name]='Temperature Abnormal')
	    UPDATE alarmType SET name='Fiber Temperature Abnormal' WHERE id=14 AND name='Temperature Abnormal' 	    

	IF EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='15' AND [name]='Tx Fail')
	    UPDATE alarmType SET name='Fiber Tx Fail' WHERE id=15 AND name='Tx Fail' 	    

	IF EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='16' AND [name]='Tx BERT Test')
	    UPDATE alarmType SET name='Fiber Tx BERT Test' WHERE id=16 AND name='Tx BERT Test' 
	    
	IF EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='17' AND [name]='Rx BERT Test')
	    UPDATE alarmType SET name='Fiber Rx BERT Test' WHERE id=17 AND name='Rx BERT Test' 	  

	IF EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='19' AND [name]='Wave Length Abnormal')
	    UPDATE alarmType SET name='Fiber Wave Length Abnormal' WHERE id=19 AND name='Wave Length Abnormal' 	    
	    
	IF EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='21' AND [name]='E1 Channel Rx Loss')
	    UPDATE alarmType SET name='E1/T1 Rx Loss' WHERE id=21 AND name='E1 Channel Rx Loss'    
    
    IF EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='22' AND [name]='E1 Channel AIS On')
	    UPDATE alarmType SET name='E1/T1 AIS On' WHERE id=22 AND name='E1 Channel AIS On'    
    
    IF EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='23' AND [name]='E1 Channel Tx Fail')
	    UPDATE alarmType SET name='E1/T1 Tx Fail' WHERE id=23 AND name='E1 Channel Tx Fail'    
    
    IF EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='24' AND [name]='E1 Channel Loopback Test')
	    UPDATE alarmType SET name='E1/T1 Loopback Test' WHERE id=24 AND name='E1 Channel Loopback Test'
	    
	IF EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='26' AND [name]='Fiber Has No Optical Signal')
	    UPDATE alarmType SET name='Signal Loss' WHERE id=26 AND name='Fiber Has No Optical Signal'      
	        
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='8')
        INSERT INTO alarmType (id, name) VALUES (8, 'Fan Off')
        
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='9')    
        INSERT INTO alarmType (id, name) VALUES (9, 'Alarm On')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='10')  
        INSERT INTO alarmType (id, name) VALUES (10, 'Remote Power Off')
        
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='11')     
        INSERT INTO alarmType (id, name) VALUES (11, 'Fiber Loopback Test')
        
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='12')     
        INSERT INTO alarmType (id, name) VALUES (12, 'Fiber Rx Power Low')        
        
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='13')     
        INSERT INTO alarmType (id, name) VALUES (13, 'Fiber Rx Power Error')

    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='14')     
        INSERT INTO alarmType (id, name) VALUES (14, 'Fiber Temperature Abnormal')        

    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='15')     
        INSERT INTO alarmType (id, name) VALUES (15, 'Fiber Tx Fail')

    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='16')     
        INSERT INTO alarmType (id, name) VALUES (16, 'Fiber Tx BERT Test')

    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='17')     
        INSERT INTO alarmType (id, name) VALUES (17, 'Fiber Rx BERT Test')         
        
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='18')     
        INSERT INTO alarmType (id, name) VALUES (18, 'Card Error') 
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='19')     
        INSERT INTO alarmType (id, name) VALUES (19, 'Fiber Wave Length Abnormal')  
            
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='20')     
        INSERT INTO alarmType (id, name) VALUES (20, 'Fiber FEF On')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='21')   
        INSERT INTO alarmType (id, name) VALUES (21, 'E1/T1 Rx Loss')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='22')
        INSERT INTO alarmType (id, name) VALUES (22, 'E1/T1 AIS On')
        
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='23')  
        INSERT INTO alarmType (id, name) VALUES (23, 'E1/T1 Tx Fail') 
        
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='24')    
        INSERT INTO alarmType (id, name) VALUES (24, 'E1/T1 Loopback Test')  
        
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='25')     
        INSERT INTO alarmType (id, name) VALUES (25, 'Fiber Bit Error')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='26')     
        INSERT INTO alarmType (id, name) VALUES (26, 'Signal Loss')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='27')     
        INSERT INTO alarmType (id, name) VALUES (27, 'E1 Alarm On')
        
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='28')     
        INSERT INTO alarmType (id, name) VALUES (28, 'E1 AIS On')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='29')     
        INSERT INTO alarmType (id, name) VALUES (29, 'E1 RAI On')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='30')     
        INSERT INTO alarmType (id, name) VALUES (30, 'E1 LOMF On')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='31')     
        INSERT INTO alarmType (id, name) VALUES (31, 'E1 Defected')
        
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='32')     
        INSERT INTO alarmType (id, name) VALUES (32, 'E1 Signal Loss')    
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='33')     
        INSERT INTO alarmType (id, name) VALUES (33, 'E1 Sync Loss')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='34')     
        INSERT INTO alarmType (id, name) VALUES (34, 'E1 Loopback Test')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='35')     
        INSERT INTO alarmType (id, name) VALUES (35, 'E1 BERT Test')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='36')     
        INSERT INTO alarmType (id, name) VALUES (36, 'E1 BERT Test Has Error')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='37')     
        INSERT INTO alarmType (id, name) VALUES (37, 'T1 Signal Loss')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='38')     
        INSERT INTO alarmType (id, name) VALUES (38, 'T1 Sync Loss')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='39')     
        INSERT INTO alarmType (id, name) VALUES (39, 'T1 Alarm On')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='40')     
        INSERT INTO alarmType (id, name) VALUES (40, 'T1 AIS On')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='41')     
        INSERT INTO alarmType (id, name) VALUES (41, 'T1 Loopback Test')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='42')     
        INSERT INTO alarmType (id, name) VALUES (42, 'Front Panel Loopback Test')
        
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='43')     
        INSERT INTO alarmType (id, name) VALUES (43, 'Fiber CV Abnormal')    
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='44')     
        INSERT INTO alarmType (id, name) VALUES (44, 'Fiber ES Abnormal')    
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='45')     
        INSERT INTO alarmType (id, name) VALUES (45, 'Fiber SES Abnormal')    
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='46')     
        INSERT INTO alarmType (id, name) VALUES (46, 'Fiber UAS Abnormal')    
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='47')     
        INSERT INTO alarmType (id, name) VALUES (47, 'All Slots Link Down')    
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='49')     
        INSERT INTO alarmType (id, name) VALUES (49, 'Port Link Down')
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='50')     
        INSERT INTO alarmType (id, name) VALUES (50, 'Working path (primary channel) signal loss')    
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='51')     
        INSERT INTO alarmType (id, name) VALUES (51, 'Working path (secondary channel) signal loss')    
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='52')     
        INSERT INTO alarmType (id, name) VALUES (52, 'Both channels signal loss') 
        
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='53')     
        INSERT INTO alarmType (id, name) VALUES (53, 'Working path signal loss')    
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='54')     
        INSERT INTO alarmType (id, name) VALUES (54, 'Primary channel signal loss')    
    
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='55')     
        INSERT INTO alarmType (id, name) VALUES (55, 'Secondary channel signal loss')        

    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='56')     
        INSERT INTO alarmType (id, name) VALUES (56, 'CPU Temperature Abnormal')
        
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='57')     
        INSERT INTO alarmType (id, name) VALUES (57, 'Board Temperature Abnormal')

	IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='58')     
        INSERT INTO alarmType (id, name) VALUES (58, 'Loopback Test')

	IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='59')     
        INSERT INTO alarmType (id, name) VALUES (59, 'BERT Test')

	IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='60')     
        INSERT INTO alarmType (id, name) VALUES (60, 'BERT Test Has Error')

	IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='61')     
        INSERT INTO alarmType (id, name) VALUES (61, 'E1 CRC ON')

	IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='62')     
        INSERT INTO alarmType (id, name) VALUES (62, 'E1 BPV ON')

	IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='63')     
        INSERT INTO alarmType (id, name) VALUES (63, 'E1 LOS')

	IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='64')     
        INSERT INTO alarmType (id, name) VALUES (64, 'E1 LOF')

    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='65')     
        INSERT INTO alarmType (id, name) VALUES (65, 'Card Unplug')

    IF NOT EXISTS (SELECT * FROM [dbo].[alarmType] WHERE [id]='66')     
        INSERT INTO alarmType (id, name) VALUES (66, 'Pump Inactive')        
END   
GO


----- EMS 2.64_01, redefine table 'alarm', drop and create table 'alarm'
----- EMS 2.64_01, redefine table 'alarm', drop and create table 'alarm'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[alarm]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
	IF EXISTS (SELECT * FROM sysobjects o, syscolumns c WHERE o.id=c.id AND o.name='alarm' AND c.name='device_type')
	    DROP TABLE alarm
GO

----- EMS 2.68_01, if not exists table 'alarm', create table, add one more column param for DD alarm threshold
----- EMS 2.72_01, if not exists table 'alarm', create table, add new column 'model_id'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[alarm]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
CREATE TABLE [dbo].[alarm](
	[agent_id] [int] NOT NULL,
	[rack] [tinyint] NOT NULL,
	[slot] [tinyint] NOT NULL,
	[side] [tinyint] NOT NULL,
	[model_name] [varchar](50) NULL, -- USELESS, BUT SHOULD BE RESERVED, OR CAN NOT PASS SQL COMPILATION.
	[param] [varchar](10) NOT NULL,
	[type] [smallint] NOT NULL,
	[idx] [tinyint] NOT NULL,
	[severity] [tinyint] NOT NULL,
	[enable] [bit] NOT NULL,
	[model_id] [int] NOT NULL,
 CONSTRAINT [PK_alarm] PRIMARY KEY CLUSTERED 
(
	[agent_id] ASC,
	[rack] ASC,
	[slot] ASC,
	[side] ASC,
	[type] ASC,
	[idx] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

ALTER TABLE [dbo].[alarm]  WITH CHECK ADD  CONSTRAINT [FK_alarm_agent] FOREIGN KEY([agent_id])
REFERENCES [dbo].[agent] ([id])
ON UPDATE CASCADE
ON DELETE CASCADE

ALTER TABLE [dbo].[alarm] CHECK CONSTRAINT [FK_alarm_agent]

ALTER TABLE [dbo].[alarm]  WITH CHECK ADD  CONSTRAINT [FK_alarm_alarmType] FOREIGN KEY([type])
REFERENCES [dbo].[alarmType] ([id])
ON UPDATE CASCADE
ON DELETE CASCADE

ALTER TABLE [dbo].[alarm] CHECK CONSTRAINT [FK_alarm_alarmType]

END

ELSE
BEGIN
	----- EMS 2.68_01, if exists table 'alarm', alter table, add one more column param for DD alarm threshold
	IF NOT EXISTS(SELECT * FROM sys.columns WHERE [name] = N'param' AND [object_id] = OBJECT_ID(N'alarm'))
	BEGIN
		ALTER TABLE [dbo].[alarm] ADD param VARCHAR(10) 
	END

	----- EMS 2.72_01, if exists table 'alarm' and not exists column 'model_id', alter table, add new column 'model_id'
	IF NOT EXISTS(SELECT * FROM sys.columns WHERE [name] = N'model_id' AND [object_id] = OBJECT_ID(N'alarm'))
	BEGIN
		ALTER TABLE [dbo].[alarm] ADD model_id INT NOT NULL DEFAULT(0)			
	END	
END
GO

----- EMS 2.72_01, if table 'alarm' has 'model_name' not null, set value for 'model_id', set 'model_name' null

--------------------------------------------------------------------------------------------------------------------------
----- NOTE: NOT TO DROP COLUMN 'model_name', OR CAN NOT PASS SQL COMPILATION ! -------------------------------------------
--------------------------------------------------------------------------------------------------------------------------

IF EXISTS (SELECT is_nullable FROM sys.columns WHERE [object_id] = OBJECT_ID(N'alarm') AND [name] = N'model_name')
BEGIN
		UPDATE [dbo].[alarm] SET model_id = 72   WHERE (model_name='IFS/IGS-803SM'  OR model_name='Industrial-803')
		UPDATE [dbo].[alarm] SET model_id = 73   WHERE (model_name='IFS/IGS-402SM'  OR model_name='Industrial-402')
		UPDATE [dbo].[alarm] SET model_id = 75   WHERE (model_name='IFS/IGS-812SM'  OR model_name='Industrial-812')
		UPDATE [dbo].[alarm] SET model_id = 76   WHERE (model_name='IFS/IGS-1604SM' OR model_name='Industrial-1604')
		UPDATE [dbo].[alarm] SET model_id = 48   WHERE (model_name='MSW202'         OR model_name='EDD202')
		UPDATE [dbo].[alarm] SET model_id = 49   WHERE (model_name='MX210'          OR model_name='EDD210' OR model_name='ZOS-MUX-2G')
		UPDATE [dbo].[alarm] SET model_id = 47   WHERE (model_name='FRM220-1000EAS')
		UPDATE [dbo].[alarm] SET model_id = 41   WHERE (model_name='FRM220A')
		
		UPDATE [dbo].[alarm] SET model_id = 1001 WHERE (model_name='CARD_NMC')
		UPDATE [dbo].[alarm] SET model_id = 1002 WHERE (model_name='CARD_1000EASX')
		UPDATE [dbo].[alarm] SET model_id = 1003 WHERE (model_name='CARD_1000EAS')
		UPDATE [dbo].[alarm] SET model_id = 1004 WHERE (model_name='CARD_1000EAS_2F')
		UPDATE [dbo].[alarm] SET model_id = 1005 WHERE (model_name='CARD_1000EA_2F')
		UPDATE [dbo].[alarm] SET model_id = 1006 WHERE (model_name='CARD_1000EAS_1')
		UPDATE [dbo].[alarm] SET model_id = 1007 WHERE (model_name='CARD_1000EA_1')
		UPDATE [dbo].[alarm] SET model_id = 1008 WHERE (model_name='CARD_2R4G_2S')
		UPDATE [dbo].[alarm] SET model_id = 1009 WHERE (model_name='CARD_2R4G_3S')
		UPDATE [dbo].[alarm] SET model_id = 1010 WHERE (model_name='CARD_3R27G_2S')
		UPDATE [dbo].[alarm] SET model_id = 1011 WHERE (model_name='CARD_3R27G_3S')
		UPDATE [dbo].[alarm] SET model_id = 1012 WHERE (model_name='CARD_3R10G_SS')
		UPDATE [dbo].[alarm] SET model_id = 1013 WHERE (model_name='CARD_10G_SX')
		UPDATE [dbo].[alarm] SET model_id = 1014 WHERE (model_name='CARD_10G_XX')
		UPDATE [dbo].[alarm] SET model_id = 1015 WHERE (model_name='CARD_10G_SXX')
		UPDATE [dbo].[alarm] SET model_id = 1016 WHERE (model_name='CARD_1000DS')
		UPDATE [dbo].[alarm] SET model_id = 1017 WHERE (model_name='CARD_100M')
		UPDATE [dbo].[alarm] SET model_id = 1018 WHERE (model_name='CARD_100MS')
		UPDATE [dbo].[alarm] SET model_id = 1019 WHERE (model_name='CARD_1000M')
		UPDATE [dbo].[alarm] SET model_id = 1020 WHERE (model_name='CARD_1000MS')
		UPDATE [dbo].[alarm] SET model_id = 1021 WHERE (model_name='CARD_IMC_100M')
		UPDATE [dbo].[alarm] SET model_id = 1022 WHERE (model_name='CARD_IMC_100MS')
		UPDATE [dbo].[alarm] SET model_id = 1023 WHERE (model_name='CARD_IMC_1000M')
		UPDATE [dbo].[alarm] SET model_id = 1024 WHERE (model_name='CARD_IMC_1000MS')
		UPDATE [dbo].[alarm] SET model_id = 1025 WHERE (model_name='CARD_MSW202')
		UPDATE [dbo].[alarm] SET model_id = 1026 WHERE (model_name='CARD_MX210')
		UPDATE [dbo].[alarm] SET model_id = 1027 WHERE (model_name='CARD_1000EASX_1')
		UPDATE [dbo].[alarm] SET model_id = 1028 WHERE (model_name='CARD_100I')
		
		ALTER TABLE [dbo].[alarm] ALTER COLUMN model_name VARCHAR(50) NULL
		UPDATE [dbo].[alarm] SET model_name=NULL
END
GO	


----- EMS 2.67_01, modify table 'agent', add column 'version', 'repetition'
----- EMS 2.74_01, modify table 'agent', add column 'pm_enable'
----- EMS 2.90_01, modify table 'agent', add column 'syncTime'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[agent]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    IF NOT EXISTS (SELECT * FROM syscolumns WHERE name='version' and id=OBJECT_ID('agent'))
        ALTER TABLE [dbo].[agent] ADD [version] tinyint
    
    IF NOT EXISTS (SELECT * FROM syscolumns WHERE name='repetition' and id=OBJECT_ID('agent'))
        ALTER TABLE [dbo].[agent] ADD [repetition] tinyint    

    IF NOT EXISTS (SELECT * FROM syscolumns WHERE name='pm_enable' and id=OBJECT_ID('agent'))
        ALTER TABLE [dbo].[agent] ADD [pm_enable] bit
    
    IF NOT EXISTS (SELECT * FROM syscolumns WHERE name='syncTime' and id=OBJECT_ID('agent'))
        ALTER TABLE [dbo].[agent] ADD [syncTime] tinyint                 
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[agent]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    IF EXISTS (SELECT * FROM sysobjects o, syscolumns c WHERE o.id=c.id AND o.name='agent' AND c.name='version' AND c.isnullable=1)
	    UPDATE [dbo].[agent] SET [version]=1 WHERE [version] IS NULL 
        ALTER TABLE [dbo].[agent] ALTER COLUMN [version] tinyint NOT NULL
        
    IF EXISTS (SELECT * FROM sysobjects o, syscolumns c WHERE o.id=c.id AND o.name='agent' AND c.name='repetition' AND c.isnullable=1)
	    UPDATE [dbo].[agent] SET [repetition]=10 WHERE [repetition] IS NULL 
        ALTER TABLE [dbo].[agent] ALTER COLUMN [repetition] tinyint NOT NULL

    IF EXISTS (SELECT * FROM sysobjects o, syscolumns c WHERE o.id=c.id AND o.name='agent' AND c.name='pm_enable' AND c.isnullable=1)
	    UPDATE [dbo].[agent] SET [pm_enable]=0 WHERE [pm_enable] IS NULL 
        ALTER TABLE [dbo].[agent] ALTER COLUMN [pm_enable] bit NOT NULL
        
    IF EXISTS (SELECT * FROM sysobjects o, syscolumns c WHERE o.id=c.id AND o.name='agent' AND c.name='syncTime' AND c.isnullable=1)
	    UPDATE [dbo].[agent] SET [syncTime]=0 WHERE [syncTime] IS NULL 
        ALTER TABLE [dbo].[agent] ALTER COLUMN [syncTime] tinyint NOT NULL     
END
GO



----- EMS 2.74_01, add table 'pmParameterLog' and index
----- EMS 2.88_01, modify table 'pmParameterLog', add column 'type' and 'errCode', tinyint one byte, 0~255
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[pmParameterLog]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[pmParameterLog](
    	[agent_id] [int] NOT NULL,
    	[time] [datetime] NOT NULL,
    	[data] [varbinary](max) NOT NULL,
    	[type] [tinyint] NOT NULL, -- 0 to 255
    	[errCode] [tinyint] NOT NULL -- 0 to 255
    ) ON [PRIMARY]
    
    ALTER TABLE [dbo].[pmParameterLog]  WITH CHECK ADD  CONSTRAINT [FK_pmParameterLog_agent] FOREIGN KEY([agent_id])
    REFERENCES [dbo].[agent] ([id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
    
    ALTER TABLE [dbo].[pmParameterLog] CHECK CONSTRAINT [FK_pmParameterLog_agent]
    
    CREATE CLUSTERED INDEX [IX_pmParameterLog] ON [dbo].[pmParameterLog] 
    (
    	[agent_id] ASC,
    	[time] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
END
ELSE BEGIN
	IF NOT EXISTS (SELECT * FROM syscolumns WHERE name='type' and id=OBJECT_ID('pmParameterLog'))
		ALTER TABLE [dbo].[pmParameterLog] ADD [type] TINYINT NOT NULL DEFAULT '1' -- 001 for PMNormal, FAN,RMON,etc       
	
	IF NOT EXISTS (SELECT * FROM syscolumns WHERE name='errCode' and id=OBJECT_ID('pmParameterLog'))
		ALTER TABLE [dbo].[pmParameterLog] ADD [errCode] TINYINT NOT NULL DEFAULT '0' -- 0 for no error   
END
GO

----- EMS 2.88_01, add table 'pmParamErrCode'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[pmParamErrCode]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[pmParamErrCode](
		[id]   [tinyint] NOT NULL,
	    [name] [varchar](128) NOT NULL
    CONSTRAINT [PK_pmParamErrCode] PRIMARY KEY CLUSTERED 
    (
	    [id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY] 
END
GO

IF NOT EXISTS (SELECT * FROM [dbo].[pmParamErrCode] WHERE [name]='No Error')   
        INSERT INTO [pmParamErrCode] VALUES ('0', 'No Error')
IF NOT EXISTS (SELECT * FROM [dbo].[pmParamErrCode] WHERE [name]='Disconnected')   
        INSERT INTO [pmParamErrCode] VALUES ('1', 'Disconnected')
IF NOT EXISTS (SELECT * FROM [dbo].[pmParamErrCode] WHERE [name]='Timeout')   
        INSERT INTO [pmParamErrCode] VALUES ('2', 'Timeout')  
IF NOT EXISTS (SELECT * FROM [dbo].[pmParamErrCode] WHERE [name]='Over Time')   
        INSERT INTO [pmParamErrCode] VALUES ('3', 'Over Time')          
GO        
----- EMS 2.88_01, add table 'pmParamDataType'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[pmParamDataType]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[pmParamDataType](
		[id]   [tinyint] NOT NULL,
	    [name] [varchar](128) NOT NULL
    CONSTRAINT [PK_pmParamDataType] PRIMARY KEY CLUSTERED 
    (
	    [id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY] 
END
GO

IF NOT EXISTS (SELECT * FROM [dbo].[pmParamDataType] WHERE [name]='None') -- 000   
        INSERT INTO [pmParamDataType] VALUES ('0', 'None')
IF NOT EXISTS (SELECT * FROM [dbo].[pmParamDataType] WHERE [name]='PMNormal') -- 001   
        INSERT INTO [pmParamDataType] VALUES ('1', 'PMNormal')
IF NOT EXISTS (SELECT * FROM [dbo].[pmParamDataType] WHERE [name]='PM15Min') -- 010   
        INSERT INTO [pmParamDataType] VALUES ('2', 'PM15Min')
IF NOT EXISTS (SELECT * FROM [dbo].[pmParamDataType] WHERE [name]='PMNormal,PM15Min') -- 011  
        INSERT INTO [pmParamDataType] VALUES ('3', 'PMNormal,PM15Min')
IF NOT EXISTS (SELECT * FROM [dbo].[pmParamDataType] WHERE [name]='PM24Hr') -- 100  
        INSERT INTO [pmParamDataType] VALUES ('4', 'PM24Hr')
IF NOT EXISTS (SELECT * FROM [dbo].[pmParamDataType] WHERE [name]='PMNormal,PM24Hr') -- 101  
        INSERT INTO [pmParamDataType] VALUES ('5', 'PMNormal,PM24Hr')
IF NOT EXISTS (SELECT * FROM [dbo].[pmParamDataType] WHERE [name]='PM15Min,PM24Hr') -- 110  
        INSERT INTO [pmParamDataType] VALUES ('6', 'PM15Min,PM24Hr')
IF NOT EXISTS (SELECT * FROM [dbo].[pmParamDataType] WHERE [name]='PMNormal,PM15Min,PM24Hr') -- 111  
        INSERT INTO [pmParamDataType] VALUES ('7', 'PMNormal,PM15Min,PM24Hr')
GO 

----- EMS 2.76_01, add table 'image'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[image]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[image](
    	[name] [varchar](200) NOT NULL,
    	[size] [int] NOT NULL,
    	[date] [datetime] NOT NULL,
    	[data] [varbinary](max) NOT NULL,
     CONSTRAINT [PK_image] PRIMARY KEY CLUSTERED 
    (
    	[name] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
END
GO


----- EMS 2.76_01, add table 'topologyDevice'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[topologyDevice]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[topologyDevice](
    	[tree_id] [int] NOT NULL,
    	[node_id] [int] NOT NULL,
    	[location_x] [smallint] NOT NULL,
    	[location_y] [smallint] NOT NULL,
    	[width] [tinyint] NOT NULL,
    	[height] [tinyint] NOT NULL,
     CONSTRAINT [PK_topologyDevice] PRIMARY KEY CLUSTERED 
    (
    	[tree_id] ASC,
    	[node_id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    ALTER TABLE [dbo].[topologyDevice]  WITH CHECK ADD  CONSTRAINT [FK_topologyDevice_treelinks] FOREIGN KEY([tree_id], [node_id])
    REFERENCES [dbo].[treelinks] ([tree_id], [child_id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
    
    ALTER TABLE [dbo].[topologyDevice] CHECK CONSTRAINT [FK_topologyDevice_treelinks]
END
GO


----- EMS 2.76_01, add table 'topologyDeviceLink'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[topologyDeviceLink]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[topologyDeviceLink](
    	[tree_id] [int] NOT NULL,
    	[node_id1] [int] NOT NULL,
    	[interface1] [varchar](50) NOT NULL,
    	[node_id2] [int] NOT NULL,
    	[interface2] [varchar](50) NOT NULL,
     CONSTRAINT [PK_topologyDeviceLink] PRIMARY KEY CLUSTERED 
    (
    	[tree_id] ASC,
    	[node_id1] ASC,
    	[interface1] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY],
     CONSTRAINT [UK_topologyDeviceLink] UNIQUE NONCLUSTERED 
    (
    	[tree_id] ASC,
    	[node_id2] ASC,
    	[interface2] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    ALTER TABLE [dbo].[topologyDeviceLink]  WITH CHECK ADD  CONSTRAINT [FK_topologyDeviceLink_treelinks] FOREIGN KEY([tree_id], [node_id1])
    REFERENCES [dbo].[treelinks] ([tree_id], [child_id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
    
    ALTER TABLE [dbo].[topologyDeviceLink] CHECK CONSTRAINT [FK_topologyDeviceLink_treelinks]
END
GO


----- EMS 2.76_01, add table 'topologyEquip'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[topologyEquip]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[topologyEquip](
    	[tree_id] [int] NOT NULL,
    	[node_id] [int] NOT NULL,
    	[name] [varchar](200) NOT NULL,
    	[location_x] [int] NOT NULL,
    	[location_y] [int] NOT NULL,
    	[width] [int] NOT NULL,
    	[height] [int] NOT NULL,
     CONSTRAINT [PK_TopologyEquip] PRIMARY KEY CLUSTERED 
    (
    	[tree_id] ASC,
    	[node_id] ASC,
    	[name] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    ALTER TABLE [dbo].[topologyEquip]  WITH CHECK ADD  CONSTRAINT [FK_topologyEquip_treelinks] FOREIGN KEY([tree_id], [node_id])
    REFERENCES [dbo].[treelinks] ([tree_id], [child_id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
    
    ALTER TABLE [dbo].[topologyEquip] CHECK CONSTRAINT [FK_topologyEquip_treelinks]
END
GO


----- EMS 2.76_01, add table 'topologyEquipLink'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[topologyEquipLink]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[topologyEquipLink](
    	[tree_id] [int] NOT NULL,
    	[node_id1] [int] NOT NULL,
    	[interface1] [varchar](50) NOT NULL,
    	[node_id2] [int] NOT NULL,
    	[name2] [varchar](200) NOT NULL,
     CONSTRAINT [PK_topologyEquipLink] PRIMARY KEY CLUSTERED 
    (
    	[tree_id] ASC,
    	[node_id1] ASC,
    	[interface1] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    ALTER TABLE [dbo].[topologyEquipLink]  WITH CHECK ADD  CONSTRAINT [FK_topologyEquipLink_treelinks] FOREIGN KEY([tree_id], [node_id1])
    REFERENCES [dbo].[treelinks] ([tree_id], [child_id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
    
    ALTER TABLE [dbo].[topologyEquipLink] CHECK CONSTRAINT [FK_topologyEquipLink_treelinks]
END
GO


----- EMS 2.76_01, add table 'topologyLocation'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[topologyLocation]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[topologyLocation](
    	[tree_id] [int] NOT NULL,
    	[node_id] [int] NOT NULL,
    	[image_name] [varchar](200) NULL,
    	[scale] [smallint] NOT NULL,
    	[location_x] [smallint] NOT NULL,
    	[location_y] [smallint] NOT NULL,
    	[width] [tinyint] NOT NULL,
    	[height] [tinyint] NOT NULL,
     CONSTRAINT [PK_topologyLocation] PRIMARY KEY CLUSTERED 
    (
    	[tree_id] ASC,
    	[node_id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    ALTER TABLE [dbo].[topologyLocation]  WITH CHECK ADD  CONSTRAINT [FK_topologyLocation_image] FOREIGN KEY([image_name])
    REFERENCES [dbo].[image] ([name])
    ON UPDATE SET NULL
    ON DELETE SET NULL
    
    ALTER TABLE [dbo].[topologyLocation] CHECK CONSTRAINT [FK_topologyLocation_image]
    
    ALTER TABLE [dbo].[topologyLocation]  WITH CHECK ADD  CONSTRAINT [FK_topologyLocation_treelinks] FOREIGN KEY([tree_id], [node_id])
    REFERENCES [dbo].[treelinks] ([tree_id], [child_id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
    
    ALTER TABLE [dbo].[topologyLocation] CHECK CONSTRAINT [FK_topologyLocation_treelinks]
END
GO








----- Definition: Function
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------


----- EMS 2.68_01, add function 'ipValue'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[ipValue]') AND OBJECTPROPERTY(id, N'IsScalarFunction')=1 )
    DROP FUNCTION [dbo].[ipValue]
GO

CREATE FUNCTION [dbo].[ipValue]
(
	@ip varchar(16)
)

RETURNS bigint
AS
    
    BEGIN
    	-- ip string format must to be x.x.x.x
    	return CONVERT(int, PARSENAME(@ip, 4))*POWER(2.0, 32)
    		+ CONVERT(int, PARSENAME(@ip, 3))*POWER(2.0, 24)
    		+ CONVERT(int, PARSENAME(@ip, 2))*POWER(2.0, 16)
    		+ CONVERT(int, PARSENAME(@ip, 1))*POWER(2.0, 8)
    END
GO    

----- EMS 2.81_01, add function 'fn_getAllowedNodesByUserName'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[fn_getAllowedNodesByUserName]') AND OBJECTPROPERTY(id, N'IsTableFunction')=1 )
    DROP FUNCTION [dbo].[fn_getAllowedNodesByUserName]
GO

CREATE FUNCTION [dbo].[fn_getAllowedNodesByUserName](@userName varchar(64))
RETURNS @RS TABLE (id int)
AS
BEGIN
	INSERT INTO @RS 
	SELECT ra.node_id FROM client c, clientRole cr, roleAccess ra    
	WHERE c.name=@userName AND c.id=cr.client_id AND cr.role_id=ra.role_id 
	
	RETURN
END
GO

----- EMS 2.81_01, add function 'fn_getRolesByUserName'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[fn_getRolesByUserName]') AND OBJECTPROPERTY(id, N'IsTableFunction')=1 )
    DROP FUNCTION [dbo].[fn_getRolesByUserName]
GO

CREATE FUNCTION [dbo].[fn_getRolesByUserName](@userName varchar(64))
RETURNS @RS TABLE (id int)
AS
BEGIN
	INSERT INTO @RS 
	SELECT cr.role_id FROM client c, clientRole cr    
	WHERE c.name=@userName AND c.id=cr.client_id 
	
	RETURN
END
GO


----- EMS 2.88_01, add function 'fn_isHasIllegalChar'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[fn_isHasIllegalChar]') AND OBJECTPROPERTY(id, N'IsScalarFunction')=1 )
    DROP FUNCTION [dbo].[fn_isHasIllegalChar]
GO

CREATE FUNCTION [dbo].[fn_isHasIllegalChar](@name varchar(256))
RETURNS int
AS
BEGIN
	IF(CHARINDEX(' ', @name)>0 OR CHARINDEX(',', @name)>0 OR CHARINDEX(':', @name)>0 OR CHARINDEX('''', @name)>0
	 OR CHARINDEX('"', @name)>0 OR CHARINDEX('[', @name)>0 OR CHARINDEX(']', @name)>0)
		RETURN 1
	
	RETURN 0
END
GO

----- EMS 2.88_01, add function 'fn_rmvIllegalChar'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[fn_rmvIllegalChar]') AND OBJECTPROPERTY(id, N'IsScalarFunction')=1 )
    DROP FUNCTION [dbo].[fn_rmvIllegalChar]
GO

CREATE FUNCTION [dbo].[fn_rmvIllegalChar](@name varchar(256))
RETURNS varchar(256)
AS
BEGIN
	IF CHARINDEX(' ', @name)>0   SET @name = REPLACE(@name, ' ',  '_') 
	IF CHARINDEX(',', @name)>0   SET @name = REPLACE(@name, ',',  '_') 
	IF CHARINDEX(':', @name)>0   SET @name = REPLACE(@name, ':',  '_') 
	IF CHARINDEX('''',@name)>0   SET @name = REPLACE(@name, '''', '_') 
	IF CHARINDEX('"', @name)>0   SET @name = REPLACE(@name, '"',  '_') 
	IF CHARINDEX('[', @name)>0   SET @name = REPLACE(@name, '[',  '_') 
	IF CHARINDEX(']', @name)>0   SET @name = REPLACE(@name, ']',  '_') 
	
	RETURN @name
END
GO


----- Definition: Stored Procedure
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------


----- EMS 2.14_01, modify procedure 'clientActionInsert', rename to 'insertClientAction'
----- EMS 2.16_03, modify procedure 'insertClientAction', rename to 'addClientAction'
----- EMS 2.30_01, modify procedure 'addClientAction'
----- EMS 2.88_01, remove procedure 'addClientAction'  
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[clientActionInsert]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[clientActionInsert]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[insertClientAction]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[insertClientAction]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[addClientAction]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[addClientAction]
GO

----- EMS 2.14_01, modify procedure 'register', rename to 'insertClientLog'
----- EMS 2.16_03, modify procedure 'insertClientLog', rename to 'addClientLog'
----- EMS 2.30_01, modify procedure 'addClientLog'
----- EMS 2.88_01, remove procedure 'addClientLog'
----- EMS 2.88_01, add procedure 'addClientActionLog'
----- EMS 2.94_01, modify procedure 'addClientActionLog', change content length 128 to 3840
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[register]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[register]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[insertClientLog]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[insertClientLog]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[addClientLog]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[addClientLog]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[addClientActionLog]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[addClientActionLog]
GO

CREATE PROCEDURE [dbo].[addClientActionLog]
	@time       datetime,
	@username   varchar(100),	-- client name
	@classifyId int,
	@actionId   int,
	@content    varchar(3840)
AS
	DECLARE
		@i         int, 
		@client_id int
	
	-- select client id
	SELECT @client_id=id FROM client 
	WHERE name=@username
	
	-- check if user exist
	IF @client_id IS NULL AND @username<>'*' 	-- username * for special case
	GOTO ERR
	
	INSERT INTO clientActionLog ([time], [client_id], [classify_id], [action_id], [content]) 
		VALUES(@time, @client_id, @classifyId, @actionId, @content)
	
	IF @@error<>0 
		GOTO ERR

	-- select record for file storage in host pc		
	DECLARE @fromSql varchar(512)
	/*
	SET @fromSql='clientlog WHERE client_id='''+convert(varchar(512), @client_id)+''''
			+' AND timestamp='''+convert(varchar(512), @timestamp,120)+''''
			+' AND code='''+convert(varchar(512), @code)+''''
			+' AND client_ip='''+convert(varchar(512), @client_ip)+''''
	*/
	SET @fromSql='clientActionLog WHERE id='''+convert(varchar(100), (SELECT @@identity))+''''
	
	EXEC getClientActionLog '3', '', '', @fromSql, '', ''
	
	RETURN 0 	

ERR:
RETURN -1
GO

----- EMS 2.14_02, modify procedure 'admin_agentreadlist', rename to 'admin_agentList'
----- EMS 2.16_03, modify procedure 'admin_agentList', rename to 'getAgents'
----- EMS 2.63_01, modify procedure 'getAgents'
----- EMS 2.67_01, modify procedure 'getAgents', add new column 'version', 'repetition'
----- EMS 2.68_01, modify procedure 'getAgents', edit order by column ip_address
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_agentreadlist]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_agentreadlist]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_agentList]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_agentList]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getAgents]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getAgents]
GO

CREATE PROCEDURE [dbo].[getAgents]
	@orderCol varchar(100),
	@orderDir varchar(100)
AS
	IF @orderCol = 'ip_address'
		SET @orderCol='dbo.ipValue(ip_address)'


	EXEC('SELECT
			a.id, 
			n.name,
			a.ip_address,
			n.type_id,
			a.version,
			a.port, 
			a.port_trap,
			a.read_community, 
			a.write_community, 
			a.trap_community,
			a.repetition 
			FROM agent a, nodes n 
			WHERE a.id=n.id 
			ORDER BY '+@orderCol+' '+@orderDir
		)
GO		



----- EMS 2.14_02, modify procedure 'admin_agentgetitem', rename to 'getAgent'
----- EMS 2.16_03, modify procedure 'getAgent', rename to 'getAgentById'
----- EMS 2.67_01, modify procedure 'getAgentById', add new column 'version', 'repetition'
----- EMS 2.74_01, modify procedure 'getAgentById', add new column pm_enable
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_agentgetitem]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_agentgetitem]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getAgent]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getAgent]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getAgentById]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getAgentById]
GO

CREATE PROCEDURE [dbo].[getAgentById]
	@id	int
AS

	SELECT
		a.id, 
		n.name,
		n.type_id,
		a.ip_address,
		a.version,
		a.port, 
		a.port_trap,
		a.read_community, 
		a.write_community, 
		a.trap_community, 
		a.repetition,
		a.pm_enable
		FROM agent a, nodes n WHERE a.id=n.id AND a.id=@id
		
GO


----- EMS 2.15_03, delete procedure 'check_Worker'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[check_Worker]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[check_Worker]
GO


----- EMS 2.15_04, add procedure 'addAgentsDriver' 
----- EMS 2.41_02, edit procedure 'addAgentsDriver'
----- EMS 2.45_01, modify procedure 'addAgentsDriver' 
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[addAgentsDriver]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[addAgentsDriver]
GO

CREATE PROCEDURE [dbo].[addAgentsDriver]
    @broker_id       int,
	@driverName      varchar(100),
	@delayRead       int,
	@interval        int,
	@timeout         int,
	@type            int,
	@thread          int	

AS
    INSERT INTO agentsdriver (broker_id, name, delayread, interval, timeout, type, thread)
	    VALUES (@broker_id, @driverName, @delayRead, @interval, @timeout, @type, @thread)
GO


----- EMS 2.15_04, add procedure 'addBroker'
----- EMS 2.41_02, edit procedure 'addBroker'
----- EMS 2.45_01, modify procedure 'addBroker'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[addBroker]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[addBroker]
GO

CREATE PROCEDURE [dbo].[addBroker]                                                                                            
    @brokerName varchar(100),	-- could be unicode format %uxxxx for 1 char                                                  
    @ipAddress  varchar(32),                                                                                                  
    @scanPeriod int,                                                                                                          
    @port       int                                                                                                           
                                                                                                                              
AS                                                                                                                            
BEGIN TRAN                                                                                                                    
    INSERT INTO broker(name, ip_address, scanningperiod, port, enable)                                                        
	    VALUES(@brokerName, @ipAddress, @scanPeriod, @port, 0);                                                               
                                                                                                                              
    -- check if this broker's polling driver is none, add one.                                                                
    DECLARE @broker_id int                                                                                                    
                                                                                                                              
    SELECT @broker_id=id                                                                                                      
	    FROM broker                                                                                                           
	    WHERE name=@brokerName AND ip_address=@ipAddress AND scanningperiod=@scanPeriod AND port=@port AND enable=0           
                                                                                                                              
    IF NOT EXISTS (SELECT * FROM agentsdriver WHERE broker_id=@broker_id)                                                     
	    EXEC addAgentsDriver @broker_id, 'Polling-1', 0, 1, 3, 0, 1                                                           
COMMIT TRAN                                                                                                                   
GO


----- EMS 2.15_04, add procedure 'deleteBroker'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[deleteBroker]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[deleteBroker]
GO

CREATE PROCEDURE [dbo].[deleteBroker] 
	@broker_id int
AS
	-- id=1 default broker,  it cannot be deleted.
	IF (@broker_id=1) RETURN	
		
	DELETE FROM broker WHERE id=@broker_id
	
	-- if no active enable broker, set default broker to be active broker.
	IF NOT EXISTS (SELECT * FROM broker WHERE enable=1)		
		UPDATE broker SET enable=1 WHERE id=1;	
GO


----- EMS 2.15_04, add procedure 'deleteBrokers'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[deleteBrokers]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[deleteBrokers]
GO

CREATE PROCEDURE [dbo].[deleteBrokers] 
AS
	-- delete all broker expect default broker id=1
	DELETE FROM broker WHERE id<>1
	
	UPDATE broker SET enable=1 WHERE id=1;	
GO


----- EMS 2.15_04, add procedure 'setActiveBroker' 
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[setActiveBroker]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[setActiveBroker]
GO

CREATE PROCEDURE [dbo].[setActiveBroker]
	@broker_id	int
AS
	UPDATE broker SET enable=0 WHERE enable<>0
	UPDATE broker SET enable=1 WHERE id=@broker_id
GO


----- EMS 2.15_04, add procedure 'getAgentsDriverAgents' 
----- EMS 2.67_01, modify procedure 'getAgentsDriverAgents', add new column 'version', 'repetition'
----- EMS 2.74_01, modify procedure 'getAgentsDriverAgents', add new column pm_enable
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getAgentsDriverAgents]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getAgentsDriverAgents]
GO

CREATE PROCEDURE [dbo].[getAgentsDriverAgents]
	@agentsDriver_id	int	
AS

	SELECT 
		a.id, 
		n.name,
		n.type_id,
		a.ip_address,
		a.version,
		a.port, 
		a.port_trap,
		a.read_community, 
		a.write_community, 
		a.trap_community, 
	    a.repetition,
	    a.pm_enable
		FROM adlinks l, agent a, nodes n  
		WHERE l.agentsdriver_id=@agentsDriver_id AND l.agent_id=a.id AND a.id=n.id
GO


----- EMS 2.15_04, add procedure 'deleteAdlink' 
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[deleteAdlink]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[deleteAdlink]
GO

CREATE PROCEDURE [dbo].[deleteAdlink]
	@agent_id	     int,
	@agentsDriver_id int
AS
	DELETE FROM adlinks 
		WHERE agentsdriver_id=@agentsDriver_id AND agent_id=@agent_id
GO


----- EMS 2.15_04, add procedure 'deleteAdlinks' 
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[deleteAdlinks]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[deleteAdlinks]
GO

CREATE PROCEDURE [dbo].[deleteAdlinks]
	@broker_id int
AS
	DELETE FROM adlinks 
		WHERE agentsdriver_id in (SELECT id FROM agentsdriver WHERE broker_id=@broker_id)
GO


----- EMS 2.15_04, delete procedure 'admin_brokergetitem' 
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_brokergetitem]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_brokergetitem]
GO


----- EMS 2.15_04, delete procedure 'admin_brokerdelete' 
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_brokerdelete]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_brokerdelete]
GO


----- EMS 2.15_04, delete procedure 'admin_drivergetitem' 
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_drivergetitem]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_drivergetitem]
GO


----- EMS 2.15_04, delete procedure 'admin_getagents_out_driver'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_getagents_out_driver]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_getagents_out_driver]
GO

----- EMS 2.15_04, modify procedure 'aliasInsert', rename to 'addAlias'
----- EMS 2.20_02, modify procedure 'addAlias' for FRM220A
----- EMS 2.31_01, modify procedure 'addAlias' for FRM220A-1000EAS/X
----- EMS 2.35_07, modify procedure 'addAlias' for FMUX04E
----- EMS 2.36_02, modify procedure 'addAlias' for ERM-MUX/Plus
----- EMS 2.54_02, modify procedure 'addAlias' for FRM220B
----- EMS 2.57_01, modify procedure 'addAlias' for IMC-1000M
----- EMS 2.58_01, modify procedure 'addAlias' for FRM220A-1000EAS/X-1
----- EMS 2.62_01, modify procedure 'addAlias' for CHT-FRM220-1000EAS
----- EMS 2.62_03, modify procedure 'addAlias' for CHT-FRM220
----- EMS 2.63_01, modify procedure 'addAlias' rename CHT-FRM220-1000EAS to FRM220-1000EAS
----- EMS 2.63_01, modify procedure 'addAlias' remove CHT-FRM220
----- EMS 2.64_01, modify procedure 'addAlias', identify device by device id
----- EMS 2.66_01, modify procedure 'addAlias' for IMC-100M
----- EMS 2.73_01, modify procedure 'addAlias' for new model FMUX160
----- EMS 2.73_01, modify procedure 'addAlias' for new model FMUX80
----- EMS 2.73_01, modify procedure 'addAlias' for new model FMUX1600
----- EMS 2.73_01, modify procedure 'addAlias' for new model FMUX800
----- EMS 2.75_01, modify procedure 'addAlias' for FRM220-100AS-1
----- EMS 2.75_01, modify procedure 'addAlias' for FRM220-1000EAS/X-2F
----- EMS 2.88_01, modify procedure 'addAlias' for FRM220R4

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[aliasInsert]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[aliasInsert]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[addAlias]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[addAlias]
GO	

CREATE PROCEDURE [dbo].[addAlias]
	@id int		-- node id
AS
DECLARE 
	@type_id  tinyint,
	@rack_id  int,
	@site_id  int,
	@idx      int,			 
	@c        int,	-- operate rack_id
	@c1		  int,	-- operate site_id
	@c2		  int	-- operate idx				
	
	--SELECT @type_name=(SELECT n2.name FROM nodes n2 WHERE n2.id=n.type_id) FROM nodes n WHERE id=@id				
	SELECT @type_id=type_id FROM nodes WHERE id=@id
	
	-- ETU01A, ELINK, FMUX04E, FMUX160, FMUX80, FMUX1600, FMUX800, FRM220A-1000EAS/X-1, IMC-1000M, IMC-100M, FRM220-100AS-1 
	IF @type_id IN (21, 24, 33, 34, 35, 36, 37, 45, 71, 74, 80)
	BEGIN
		SET @rack_id=1			-- standalone 
		SET @site_id=2			-- local/remote
		SET @idx    =1			-- index start from 1, 1 alias index for 1 site
	END
				
	-- ERM-MUX/Plus
	ELSE IF @type_id=25
	BEGIN
		SET @rack_id=1			-- standalone 
		SET @site_id=2			-- local/remote
		SET @idx    =10			-- index start from 1, 1 site has 10 io slots. 10 for 10 io slots
	END
	
	-- FMUX01A, FMUX01APlus
	ELSE IF @type_id IN (30, 31)
	BEGIN
		SET @rack_id=1			-- standalone
		SET @site_id=2			-- local/remote
		SET @idx    =4*5    	-- index start from 1, site has 4 ports, port has 4 channels. 1 alias index for 1 port, 4 alias index for 4 channels 
	                            -- index 1,6,11,16 is for port, others is for 4 channels
	END
	
	-- FMUX04
	ELSE IF @type_id=32	
	BEGIN
		SET @rack_id=1			-- standalone
		SET @site_id=2			-- local/remote
		SET @idx    =5			-- index start from 1, site has 4 ports, port has 4 channels. 1 alias index for 1 port, 4 alias index for 4 channels  
	                            -- index 1 is for port, others is for 4 channels
	END
	
	-- FRM220, FRM220B
	ELSE IF @type_id IN (40, 44)
	BEGIN
		SET @rack_id=10			-- 10 rack,
		SET @site_id=3			-- local/remote(A)/remoteB
		SET @idx    =20			-- index start from 1, site has 20 slots, 20 alias index for 20 slots
	END
	
	-- FRM220A, FRM220R4
	ELSE IF @type_id IN (41, 83)
	BEGIN
		SET @rack_id=10			-- 10 rack,
		SET @site_id=5			-- local/remote(A)/remoteB/remoteC/remoteD
		SET @idx    =20			-- index start from 1, site has 20 slots, 20 alias index for 20 slots
	END
	
	-- FRM220A-1000EAS/X, FRM220-1000EAS, FRM220-1000EAS/X-2F 
	ELSE IF @type_id IN (42, 47, 81)
	BEGIN
		SET @rack_id=1			-- standalone
		SET @site_id=3			-- local/remoteA/remoteB
		SET @idx    =1			-- index start from 1, 1 alias index for 1 site
	END	
	
	BEGIN TRAN
		SET @c=0
	
		WHILE @c<@rack_id
		BEGIN
			SET @c1=0
	
			WHILE @c1<@site_id		
			BEGIN
				SET @c2=1              --index start from 1
	
				WHILE @c2<=@idx
				BEGIN
					INSERT alias(node_id, rack_id, site_id, idx, name) 
						VALUES(@id, @c, @c1, @c2, '')
					
					IF @@error<>0 goto ERR
	
					SET @c2=@c2+1
				END
	
				SET @c1=@c1+1
			END
		
			SET @c=@c+1
		END
	COMMIT TRAN
	RETURN 0
	
ERR:
	ROLLBACK TRAN
	RETURN -1

GO

----- EMS 2.68_01, delete procedure 'getPollingAgent'
----- EMS 2.200, delete procedure 'getPollingAgent', change type error 'getPollingAgents' to 'getPollingAgent'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getPollingAgent]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getPollingAgent]
GO


----- EMS 2.15_04, modify procedure 'admin_getagents_in_driver', rename to 'getPollingAgents'
----- EMS 2.68_01, modify procedure 'getPollingAgents', edit order by column ip_address
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_getagents_in_driver]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_getagents_in_driver]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getPollingAgents]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getPollingAgents]
GO

CREATE PROCEDURE [dbo].[getPollingAgents]
	@broker_id int,
	@orderCol varchar(100),
	@orderDir varchar(100)
AS
	IF @orderCol = 'ip_address'
		SET @orderCol = 'dbo.ipValue(ip_address)'

	IF OBJECT_ID(N'[tempdb].[dbo].[#x]') IS NOT NULL
		DROP TABLE #x

	SELECT 
		agent_id=a.id, driver_id=ad.id, driver_name=ad.name 
		INTO #x 	-- new temp table
		FROM agent a, adlinks l, agentsdriver ad 
		WHERE a.id=l.agent_id AND l.agentsdriver_id=ad.id AND ad.broker_id=@broker_id


	IF OBJECT_ID(N'[tempdb].[dbo].[#order]') IS NOT NULL
		DROP TABLE #order
		
----- EMS 2.90_01, modify procedure 'getPollingAgents', change name length 100 to 768. UI length 128, DB needs 768.
	CREATE TABLE #order (
		id             int,
		name           varchar(768),
		ip_address     varchar(100),
		driver_id      int,
		driver_name    varchar(100),
		polling_status int
	)

	INSERT INTO #order
		SELECT 
			a.id, 
			n.name, 
			a.ip_address, 
			driver_id=isnull((SELECT driver_id FROM #x d WHERE a.id=d.agent_id), '-1'), 
			driver_name=isnull((SELECT driver_name FROM #x d WHERE a.id=d.agent_id), ''),
			polling_status=isnull((SELECT 1 FROM #x d WHERE a.id=d.agent_id), '0')
			FROM nodes n, agent a
			WHERE n.id=a.id
	
	-- order by statement
	EXEC('SELECT * FROM #order ORDER BY polling_status DESC, '+@orderCol+' '+@orderDir)
	DROP TABLE #order

	DROP TABLE #x

GO


----- EMS 2.15_04, modify procedure 'admin_brokerupdate', rename to 'editBroker' 
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_brokerupdate]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_brokerupdate]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[editBroker]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[editBroker]
GO

CREATE PROCEDURE [dbo].[editBroker] 
	@broker_id   int,
	@brokerName  varchar(100),	-- could be unicode format %uxxxx for 1 char
	@ipAddress   varchar(32),
	@scanPeriod  int,
	@servicePort int			-- name service port
AS
	UPDATE broker
		SET name=@brokerName,
			ip_address=@ipAddress,
			scanningperiod=@scanPeriod,
			port=@servicePort
		WHERE id=@broker_id
GO	


----- EMS 2.15_04, modify procedure 'admin_driverupdate', rename to 'editAgentsDriver' 
----- EMS 2.41_02, edit procedure 'editAgentsDriver' 
----- EMS 2.45_01, modify procedure 'editAgentsDriver'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_driverupdate]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_driverupdate]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[editAgentsDriver]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[editAgentsDriver]
GO
CREATE PROCEDURE [dbo].[editAgentsDriver]    
    @driverId       int,                     
    @driverName     varchar(100),            
    @delayRead      int,                     
    @interval       int,                     
    @timeout        int,                     
    @type           int,                     
    @thread         int                      
                                             
AS                                           
    UPDATE agentsdriver                      
	    SET name          = @driverName,     
		    delayread     = @delayRead,      
		    interval      = @interval,  
		    timeout       = @timeout,   
		    type          = @type,           
		    thread        = @thread          
	    WHERE id=@driverId                   
GO


----- EMS 2.15_04, modify procedure 'admin_agentInsert', rename to 'addAgent'
----- EMS 2.64_01, modify procedure 'addAgent'
----- EMS 2.67_01, modify procedure 'addAgent', add new column 'version', 'repetition'
----- EMS 2.74_01, modify procedure 'addAgent', add new column pm_enable
----- EMS 2.90_01, modify procedure 'addAgent', add column 'syncTime'
----- EMS 2.90_01, modify procedure 'addAgent', change name length 100 to 768. UI length 128, DB needs 768.
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_agentInsert]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_agentInsert]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[addAgent]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[addAgent]
GO

CREATE PROCEDURE [dbo].[addAgent]
	@name            varchar(768),	-- could be unicode format %uxxxx for 1 char 
	@node_type_id    tinyint,
	@ip_address      varchar(50),
	@port            int,			-- snmp port
	@port_trap       int,
	@mib             varchar(64),
	@read_community  varchar(64),
	@write_community varchar(64),
	@trap_community  varchar(64),
	@op_name         varchar(50),	-- operator name
	@version         tinyint,
	@repetition      tinyint	
AS

DECLARE 
	@username_admin varchar(50),	-- client user admin
	@agent_id       int,			-- agent/node id which is inserted 
	@r              int

	-- query admin's username
	SELECT @username_admin=name FROM client WHERE id=1
	
	BEGIN TRAN
		-- create nodes, treelinks
		EXEC @agent_id=admin_agentNodeInsert @username_admin, @name, @node_type_id	
		IF @@error<>0 OR @agent_id=-1 GOTO ERR	

		-- create agent
		INSERT INTO agent(id, ip_address, port, port_trap, mib, read_community, write_community, trap_community, op_name, [version], repetition, pm_enable, syncTime)
			VALUES(@agent_id, @ip_address, @port, @port_trap, @mib, @read_community, @write_community, @trap_community, @op_name, @version, @repetition, 0, 0)	
		IF @@error<>0 GOTO ERR
	
		-- create alias
		EXEC @r=addAlias @agent_id
		IF @@error<>0 OR @r=-1 GOTO ERR
		
	COMMIT TRAN
	
	SELECT agent_id=@agent_id
	
	RETURN 0
ERR:
	ROLLBACK TRAN
	RETURN -1

GO



----- EMS 2.15_04, modify procedure 'admin_agentUpdate', rename to 'editAgent'
----- EMS 2.66_01, modify procedure 'editAgent'
----- EMS 2.67_01, modify procedure 'editAgent', add new column 'version', 'repetition'
----- EMS 2.90_01, modify procedure 'editAgent', change name length 100 to 768. UI length 128, DB needs 768.
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_agentUpdate]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_agentUpdate]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[editAgent]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[editAgent]
GO

CREATE PROCEDURE [dbo].[editAgent]
	@agent_id		 int,
	@name			 varchar(768),	-- could be unicode format %uxxxx for 1 char  
	@type_id		 tinyint,		-- device type from node id
	@ip_address		 varchar(50),
	@port			 int,			-- snmp port
	@port_trap		 int,
	@mib			 varchar(64),
	@read_community	 varchar(64),
	@write_community varchar(64),
	@trap_community	 varchar(64),
	@op_name		 varchar(50),
	@version         tinyint,
	@repetition      tinyint 
AS

	DECLARE @old_type_id int

	SELECT @old_type_id=type_id FROM nodes WHERE id=@agent_id

	BEGIN TRAN
		-- update nodes
		UPDATE nodes 
			SET name=@name,type_id=@type_id 
			WHERE id=@agent_id
		
		IF @@error<>0 GOTO ERR
	
		-- update agent
		UPDATE agent 
			SET	ip_address      = @ip_address,
				port            = @port,
				port_trap       = @port_trap,
				mib             = @mib,
				read_community  = @read_community,
				write_community = @write_community,
				trap_community  = @trap_community,
				op_name         = @op_name,
				[version]       = @version,
				repetition      = @repetition
			WHERE id=@agent_id
		
		IF @@error<>0 GOTO ERR
	
		-- update treelinks
		DECLARE @parent_id int, -- treelink	
				@indx      int  -- treelink
	
		-- origin type parent node, shift children idx above changed node          	
		SELECT @parent_id=parent_id, @indx=idx 
			FROM treelinks 
			WHERE tree_id=1 AND child_id=@agent_id
	  
		UPDATE treelinks 
			SET idx=idx-1 
			WHERE tree_id=1 AND parent_id=@parent_id AND idx>@indx
		
		IF @@error<>0 GOTO ERR
	
		-- new type parent join chaged node
		--SELECT @parent_id=root_id FROM node_types 
		--WHERE id=@type_id
		SET @parent_id=@type_id
	
		IF NOT EXISTS (SELECT 1 FROM treelinks WHERE tree_id=1 AND parent_id=@parent_id AND child_id!=@agent_id)
			SELECT @indx=0   -- no other data
		ELSE 
			SELECT @indx=MAX(idx)+1 
				FROM treelinks
				WHERE tree_id=1 AND parent_id=@parent_id AND child_id!=@agent_id
	
		-- only update tree_id 1 (default repository tree)
		UPDATE treelinks 
			SET parent_id=@parent_id,idx=@indx	
			WHERE tree_id=1 AND child_id=@agent_id
		
		IF @@error<>0 GOTO ERR
	
		-- update alias 
		--delete from alias where node_id=@agent_id
		--if @@error<>0 goto ERR
	
		-- insert alias
		--declare @c int
		
		--exec @c=aliasInsert @agent_id
		--if @c=-1 goto ERR
		
	COMMIT TRAN
	
	IF @old_type_id = @type_id
		SELECT type_changed='0'
	ELSE 
		SELECT type_changed='1'	
	
	RETURN 0

ERR:
    ROLLBACK TRAN
    RETURN -1

GO


----- EMS 2.15_04, modify procedure 'nodeDelete', rename to 'deleteNode'
----- EMS 2.76_01, modify procedure 'deleteNode', rename to 'deleteTreeNode'
----- EMS 2.81_01, modify procedure 'deleteTreeNode', remove param '@idx', add param '@selectedNode_id'
----- EMS 2.88_01, modify procedure 'deleteTreeNode', add write to clientActionLog
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[nodeDelete]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[nodeDelete]
GO

IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[deleteNode]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[deleteNode]
GO

IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[deleteTreeNode]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[deleteTreeNode]
GO

CREATE PROCEDURE [dbo].[deleteTreeNode]
	@worker_name     varchar(50),	
	@tree_id         int,			
	@parent_id       int,			
	-- @idx          int -- not to use UI tree node index, it may changed, 'query' the right value here
	@selectedNode_id int,
	@time            datetime			

AS	
	-- remove parent node's index in the tree. 
	-- not allowed for not administrators (acl<>255), who try to do it in repository

	-- IF @idx<0 GOTO ERR

	DECLARE 
		@workerId   int,			-- client id
		@c		    int,			-- total children count
		@tree_type  int,			-- tree
		--	@is_rep     tinyint,	-- tree
		--	@acl_client tinyint,	-- client
		@type_id    tinyint,		-- node
		--	@acl_node   tinyint,	-- parent node created acl
		@id         int,				
		@r          int,			-- exec
		@idx        int             -- not to use UI tree node index, it may changed, 'query' the right value here

	SELECT @idx=idx FROM treelinks WHERE tree_id=@tree_id AND parent_id=@parent_id AND child_id=@selectedNode_id

	SELECT @workerId=id FROM client WHERE name=@worker_name
	--SELECT @acl_client=acl FROM client WHERE name=@worker_name
	--SELECT @tree_type=type, @is_rep=repository FROM trees t WHERE id=@tree_id  -- is_repository=1 default tree 

	-- check parent node acl 
	--SELECT @acl_node=n.acl FROM nodes n, treelinks l 
	--WHERE l.tree_id=@tree_id and l.parent_id=-1 and l.child_id=n.id

	-- only worker acl <= parent node's acl can do except public tree type=1
	--if @acl_client>@acl_node and @tree_type<>1 goto ERR1

	-- check tree is modified
	----- EMS 2.81_01, remove procedure 'treeIsModify'
	-- EXEC @r=treeIsModify @worker_name, @tree_id 
	-- IF @r=0 GOTO ERR1

	-- only administrator can modify default repository tree 
	--if @is_rep=1 and @workerId<>1 goto ERR1		--client id=1 is super admin

	--SELECT @type_id=type_id FROM nodes WHERE id=@parent_id
	--if @type_id in (10,11,12,13,14) goto err1

	CREATE TABLE #x(id int NULL)		-- store all nodes id to be delete
	CREATE TABLE #y(id int NULL)		-- store node id  
	CREATE TABLE #z(id int NULL)		-- store node's children id

	-- get the deleted index node's children and children relative nodes in the tree 
	-- remove the node, also need to remove the nodes below it
	INSERT #x SELECT child_id FROM treelinks 
		WHERE tree_id=@tree_id AND parent_id=@parent_id AND idx=@idx
	
	INSERT #y SELECT id FROM #x

	SELECT @c=1
	WHILE @c>0 
	BEGIN
		TRUNCATE TABLE #z
		INSERT #z SELECT t.child_id FROM treelinks t, #y 
			WHERE t.tree_id=@tree_id AND t.parent_id=#y.id
		
		SELECT @c=count(*) FROM #z
	
		INSERT #x SELECT id FROM #z
		TRUNCATE TABLE #y
		INSERT #y SELECT id FROM #z
	END

	-- prepare for write to clientActionLog
	-- get delete node name before deleted
	DECLARE @delNodeName varchar(128), @parentNodeName varchar(128), @content varchar(256)  
	SELECT @delNodeName=name FROM nodes WHERE id=@selectedNode_id
	SELECT @parentNodeName=name FROM nodes WHERE id=@parent_id
	SET @content = '10:'+@delNodeName+',9:'+@parentNodeName

BEGIN TRAN
	-- delete relative tables based on the delete node

	DELETE FROM treelinks 
		WHERE tree_id=@tree_id AND child_id IN (SELECT id FROM #x)
	IF @@ERROR<>0 GOTO ERR

	DELETE FROM nodes 
		WHERE NOT EXISTS(SELECT 1 FROM treelinks WHERE nodes.id=treelinks.child_id)
	IF @@ERROR<>0 GOTO ERR

	DELETE FROM agent 
		WHERE NOT EXISTS(SELECT 1 FROM nodes WHERE agent.id=nodes.id)
	IF @@error<>0 GOTO ERR

	-- delete topology link
	-- delete clientActionLog
    DECLARE cur CURSOR FOR (SELECT id from #x)   
	OPEN cur                                                                                         
	FETCH NEXT FROM cur INTO @id                     
	WHILE @@FETCH_STATUS=0                         
	BEGIN                                            
		EXEC deleteTopologyDeviceLink null, @id, null 
		EXEC deleteTopologyEquipLink null, @id, null 
	                         
	    DELETE FROM clientActionLog 
	    WHERE (CHARINDEX('1:'+CAST(@id AS varchar), content)>0       -- code Node
			    OR CHARINDEX('9:'+CAST(@id AS varchar), content)>0   -- code Parent
			    OR CHARINDEX('10:'+CAST(@id AS varchar), content)>0) -- code Child
	    AND   (CHARINDEX('11:'+CAST(@tree_id AS varchar), content)>0 -- code Tree
	            OR CHARINDEX(',11:', content)=0) -- some action has no tree record
	    
	    DELETE FROM clientActionLog 
		WHERE (CHARINDEX('3:['+CAST(@tree_id AS varchar)+' ', content)=1 -- code TopologyDeviceLink
	           OR CHARINDEX('4:['+CAST(@tree_id AS varchar)+' ', content)=1) -- code TopologyEquipLink 
		AND CHARINDEX(' '+CAST(@id AS varchar)+' ', content)>0
	    
		FETCH NEXT FROM cur INTO @id                 
	END                                                                                              
	CLOSE cur                                        
	DEALLOCATE cur                                   

	-- delete adlinks, has done by FK
	--DELETE FROM adlinks 
	--	WHERE not exists (SELECT 1 FROM agent WHERE adlinks.agent_id=agent.id)
	--IF @@error<>0 GOTO ERR

	DELETE FROM objimage 
		WHERE NOT EXISTS(SELECT 1 FROM nodes WHERE objimage.node=nodes.id)
	IF @@error<>0 GOTO ERR

	-- shift index -1 for treelink index > delete node's   
	UPDATE treelinks 
		SET idx=idx-1 
		WHERE tree_id=@tree_id AND parent_id=@parent_id AND idx>@idx
	IF @@error<>0 GOTO ERR
	
	-- write to clientActionLog
	IF @time IS NOT NULL 
		INSERT INTO clientActionLog ([time],[client_id],[classify_id],[action_id],[content])  
		VALUES(@time, @workerId, 4, 403, @content) 
	
COMMIT TRAN

	DROP TABLE #z
	DROP TABLE #y
	DROP TABLE #x

	SELECT id=0
	RETURN 0

ERR:
ROLLBACK TRAN
	DROP TABLE #z
	DROP TABLE #y
	DROP TABLE #x

ERR1:			
	SELECT id=-1
	RETURN -1
GO




----- EMS 2.15_04, modify procedure 'admin_agentDelete', rename to 'deleteAgent'
----- EMS 2.52_01, modify procedure 'deleteAgent', when agent deleted in admin panel, also delete slot(s) of this agent in table inventoryList	
----- EMS 2.56_02, modify procedure 'deleteAgent', update script for delete inventory
----- EMS 2.76_01, modify procedure 'deleteAgent'
----- EMS 2.81_01, modify procedure 'deleteAgent', procedure 'deleteTreeNode' remove param '@idx', add param '@selectedNode_id'
----- EMS 2.88_01, modify procedure 'deleteAgent', delete client action log of this agent
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_agentDelete]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_agentDelete]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[deleteAgent]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[deleteAgent]
GO

CREATE PROCEDURE [dbo].[deleteAgent]
	@agent_id	int
AS
DECLARE 
	@adminName varchar(50),		--admin privilege username
	@tree_id   int, 
	@idx       int, 
	@parent_id int, 
	@r         int,
	@count     int

	CREATE TABLE #a(
		id        int IDENTITY(1,1),
		tree_id   int NOT NULL, 
		parent_id int NOT NULL) 
		-- idx    int)

	SELECT @adminName=name FROM client WHERE id=1
	--select @tree_id=id from trees where repository=1	-- agent node exists in default repository tree
	
	--select @parent_id=parent_id,@idx=idx from treelinks 
	--where tree_id=@tree_id and child_id=@agent_id
	
	-- every tree has it's only one device agent
	INSERT #a 
		-- SELECT tree_id, parent_id, idx FROM treelinks WHERE child_id=@agent_id
		SELECT tree_id, parent_id FROM treelinks WHERE child_id=@agent_id
	
	BEGIN TRAN
		-- delete nodes and treelinks
		SELECT @count=count(*) FROM #a 
		
		WHILE @count>0
		BEGIN
			SELECT @tree_id=tree_id,@parent_id=parent_id -- ,@idx=idx 
			FROM #a 
			WHERE id=@count
			
			-- EXEC @r=deleteTreeNode @adminName, @tree_id, @parent_id, @idx
			EXEC @r=deleteTreeNode @adminName, @tree_id, @parent_id, @agent_id, NULL -- EMSv288, add time as null
			
			IF @r<>0 GOTO ERR
	
			SET @count=@count-1
		END	
	
		-- delete adlinks, has done by table FK
		--DELETE FROM adlinks WHERE agent_id=@agent_id
		--IF @@error<>0 GOTO ERR
		
		-- delete agent
		DELETE FROM agent WHERE id=@agent_id
		
		-- delete inventory
		DELETE FROM inventoryListByServer WHERE agent_id=@agent_id
		
		-- delete log 'Ack Alarm', action id=601, code id=5
		-- 5:168,true
		DELETE FROM clientActionLog 
		WHERE action_id=601 
		AND (SELECT COUNT(id) 
				FROM alarmLog 
				WHERE id=CAST(SUBSTRING(content,3,CHARINDEX(',',content)-3) AS int))=0  
		-- AND CAST(SUBSTRING(content,3,CHARINDEX(',',content)-3) AS int)  
		-- IN (SELECT id FROM alarmLog WHERE agent_id=@agent_id)
		
		-- delete log 'Ack Trap', action id=602, code id=6
		--6:168,true
		DELETE FROM clientActionLog 
		WHERE  action_id=602 
		AND (SELECT COUNT(id) 
				FROM trapLog 
				WHERE id=CAST(SUBSTRING(content,3,CHARINDEX(',',content)-3) AS int))=0  
		-- AND CAST(SUBSTRING(content,3,CHARINDEX(',',content)-3) AS int)  
		-- IN (SELECT id FROM trapLog WHERE agent_id=@agent_id)
		
		-- delete client action log, content code=1 for Node
		DELETE FROM clientActionLog 
		WHERE CHARINDEX('1:'+CONVERT(VARCHAR,@agent_id),content)>0 
		OR CHARINDEX(' '+CONVERT(VARCHAR,@agent_id)+' ',content)>0 -- topology link
	
		IF @@error<>0 GOTO ERR
	COMMIT TRAN
	
	DROP TABLE #a
	
	RETURN 0
	
ERR:
DROP TABLE #a
ROLLBACK TRAN 
RETURN -1
GO


----- EMS 2.15_04, modify procedure 'admin_addDriverAgents', rename to 'addAdlink'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_addDriverAgents]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_addDriverAgents]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[addAdlink]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[addAdlink]
GO

CREATE PROCEDURE [dbo].[addAdlink]
	@agent_id	     int,
	@agentsDriver_id int
AS
	DECLARE @broker_id int
	
	-- check if the driver's broker exists in the mapping, it means that the agent had joined broker's drivers before.  
	-- broker's agents only can join one driver of the same broker.
	SELECT @broker_id=broker_id from agentsdriver where id=@agentsDriver_id 
	
	IF EXISTS (SELECT * FROM adlinks l, agentsdriver ad WHERE l.agent_id=@agent_id and l.agentsdriver_id=ad.id AND ad.broker_id=@broker_id)
		GOTO ERR

	INSERT INTO adlinks 
		VALUES (@agentsDriver_id, @agent_id);

	RETURN 0
	
ERR:
RETURN -1		
GO


----- EMS 2.16_03, add procedure 'getClientLogs'
----- EMS 2.30_01, modify procedure 'getClientLogs'
----- EMS 2.88_01, remove procedure 'getClientLogs' 
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getClientLogs]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getClientLogs]
GO

----- EMS 2.16_03, add procedure 'getAgentByName'
----- EMS 2.67_01, modify procedure 'getAgentByName', add new column 'version', 'repetition'
----- EMS 2.74_01, modify procedure 'getAgentByName', add new column pm_enable
----- EMS 2.90_01, modify procedure 'getAgentByName', change agentName length 100 to 768. UI length 128, DB needs 768.
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getAgentByName]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getAgentByName]
GO

CREATE PROCEDURE [dbo].[getAgentByName]
	@agentName	varchar(768)
AS

	SELECT
		a.id, 
		n.name,
		n.type_id,
		a.ip_address,
		a.version,
		a.port, 
		a.port_trap,
		a.read_community, 
		a.write_community, 
		a.trap_community,
	    a.repetition,
	    a.pm_enable 
		FROM agent a, nodes n WHERE a.id=n.id AND n.name=@agentName

GO


----- EMS 2.94_01, modify table 'clientActionLog', change 'content' length 128 to 3840
IF EXISTS (SELECT * FROM syscolumns WHERE name='content' and id=OBJECT_ID('clientActionLog'))
BEGIN	
	IF (select CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='clientActionLog' and COLUMN_NAME='content' ) < 3840 	
	BEGIN 
		ALTER TABLE clientActionLog ALTER COLUMN [content] VARCHAR(3840) 
	END
END
GO

----- EMS 2.16_03, add procedure 'getClientActions'
----- EMS 2.30_01, modify procedure 'getClientActions'
----- EMS 2.88_01, remove procedure 'getClientActions'
----- EMS 2.88_01, add procedure 'getClientActionLog'
----- EMS 2.94_01, modify procedure 'getClientActionLog', change content column length 128 to 3840 
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getClientActions]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getClientActions]
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getClientActionLog]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getClientActionLog]
GO

CREATE PROCEDURE [dbo].[getClientActionLog]
	@mode     int,	
	@pageRow  int,
	@dataRow  int,
	@fromSql  varchar(1024),
	@orderCol varchar(100),
	@orderDir varchar(100)	
AS
	-- convert column name to real column in table
	IF (@orderCol='client_name')	
		SET @orderCol='client_id'

	-- create order column statement 
	-- add sub-index for order column if need.
	DECLARE 
		@orderState1 varchar(100),
		@orderState2 varchar(100)

	IF(@orderDir='ASC')
	BEGIN
		SET @orderState1 = @orderCol+' ASC,  id ASC'
		SET @orderState2 = @orderCol+' DESC, id DESC'
	END
	ELSE
	BEGIN
		SET @orderState1 = @orderCol+' DESC, id DESC'
		SET @orderState2 = @orderCol+' ASC,  id ASC'
	END

	-- create tmp table with older data for further query
	IF OBJECT_ID(N'[tempdb].[dbo].[#order]') IS NOT NULL
		DROP TABLE #order

	CREATE TABLE #order (
		[id]           int,
		[time]         datetime,
		[client_id]    int,
		[classify_id]  int,
		[action_id]    int,
		[content]      varchar(3840)
	)
	
	IF (@mode = 1)	-- page	
	BEGIN 
		-- select row for page
		EXEC('INSERT INTO #order 
			SELECT * FROM (SELECT TOP '+@pageRow+' * FROM 
				(SELECT TOP '+@dataRow+' * FROM '+@fromSql+' ORDER BY '+@orderState1+') t1 
				 ORDER BY '+@orderState2+') t2 ORDER BY '+@orderState1
		)
	END	
	ELSE IF (@mode = 2)	-- report	
	BEGIN
		-- select all rows for report
		EXEC('INSERT INTO #order 
				SELECT * FROM '+@fromSql+' ORDER BY '+@orderState1
		)
	END
	ELSE IF (@mode = 3)	-- history
	BEGIN
		-- select inserted record for history file storage
		EXEC('INSERT INTO #order
				SELECT * FROM '+@fromSql
		)
	END
	
	-- parse content
	DECLARE @id int, @time datetime, @clientId int, @classifyId int, @actionId int, @content varchar(3840), 
	        @parsed varchar(3840), @idxA int, @idxB int, 
	        @tmp5 varchar(5), @tmp10 varchar(10), @tmp20 varchar(20), @tmp100 varchar(3840), @tmp128 varchar(3840) 
	
	CREATE TABLE #order2 (
		[id]           int,
		[time]         datetime,
		[client_id]    varchar(128),
		[classify_id]  int,
		[action_id]    int,
		[content]      varchar(3840)
	)
	
	DECLARE cur CURSOR FOR (SELECT [id],[time],[client_id],[classify_id],[action_id],[content] from #order) 
	OPEN cur 
	FETCH NEXT FROM cur INTO @id, @time, @clientId, @classifyId, @actionId, @content 
	WHILE @@FETCH_STATUS=0 
	BEGIN 
		-- action id=501/502/503/504/505 for 'Configure Param', 'Upgrade', 'Backup Param', 'Restore Param', 'Copy Param'
		-- action id=301/302 for Edit/Delete Inventory
		-- action id=418/419 for Map Import/Scale
		-- action id=603 for Edit Device Alarm
		-- content code=1/2/11/12 for Node/Location/Tree/Alias
		IF @actionId IN (501,502,503,504,505,301,302,418,419,603) 
		BEGIN
			-- 1:1001,[ oidxx.xx ]: disable --> enable
			-- 1:1001,2015-10-30xxxxxx
			-- 1:1001,backupFileName
			-- 1:1001,backupWebMessage
			-- 1:1001,restoreWebMessage
			-- 1:1001,copyWebMessage
			-- 1:1001,2:[4:0][5:1][1]
			-- 1:1015,14:map.png,11:2
			-- 1:1015,13:150,11:2
			-- 1:1001,2:[4:0][5:1][1]
			-- 1:1001,19:modelId
			
			SET @idxA = CHARINDEX(',',@content) -- first comma index
			SET @tmp5 = SUBSTRING(@content,3,@idxA-3) -- agentDbId
			SET @parsed = (SELECT name FROM nodes WHERE id=CONVERT(int,@tmp5)) -- agent name, UI length 16, DB needs 96.
			 
			SET @tmp128 = SUBSTRING(@content,@idxA+1,3999) -- [ oidxx.xx ]: disable --> enable
			                                               -- 2015-10-30xxxxxx
			                                               -- filePath
			                                               -- 2:[4:0][5:1][1]
			                                               -- 14:map.png,11:2
			                                               -- 13:150,11:2
			                                               -- 19:modelId
			IF @actionId IN (301,302,418,419) -- remove location/image/scale code  
				SET @tmp128 = SUBSTRING(@tmp128,CHARINDEX(':',@tmp128)+1,3999) -- [4:0][5:1][1]
																			   -- map.png,11:2
																			   -- 150,11:2
			IF @actionId IN (418,419) 
			BEGIN
				SET @idxA = CHARINDEX(':',@tmp128) -- first colon index
				SET @tmp5 = SUBSTRING(@tmp128,@idxA+1,3999) -- treeId
				SET @tmp128 = SUBSTRING(@tmp128,1,CHARINDEX(',',@tmp128)-1) -- image/scale
				SET @tmp128 = @tmp128 +', '+ (SELECT n.name FROM nodes n, trees t WHERE t.id=CAST(@tmp5 AS int) AND t.node_id=n.id)
			END
			
			SET @parsed = @parsed+', '+@tmp128 
			
			INSERT INTO #order2 VALUES(@id, @time, @clientId, @classifyId, @actionId, @parsed) 
		END
		
		-- action id=305/306 for enable/disable PM Setting
		-- action id=401 for Add Tree
		ELSE IF @actionId IN (305,306,401)
		BEGIN
			-- 1:1001
			SET @tmp5 = SUBSTRING(@content,3,3999) -- agentDbId
			SET @tmp100 = (SELECT name FROM nodes WHERE id=CONVERT(int,@tmp5)) -- agent name, UI length 16, DB needs 96.
			INSERT INTO #order2 VALUES(@id, @time, @clientId, @classifyId, @actionId, @tmp100)
		END
		
		-- action id=402/420/421 for 'Add Node', 'Topology Add Node', 'Topology Delete Node'
		-- code id=9/10/11 for Parent/Child/Tree
		ELSE IF @actionId IN (402,420,421)
		BEGIN
			-- 10:1006,9:1005,11:2
			-- equipName,9:1005,11:2
			SET @idxA = CHARINDEX(',',@content) -- first comma index
			IF @actionId=402
			BEGIN
				SET @tmp5 = SUBSTRING(@content,4,@idxA-4) -- childDbId 
				SET @parsed = (SELECT name FROM nodes WHERE id=CONVERT(int,@tmp5)) -- child name, UI length 16, DB needs 96.
			END
			ELSE BEGIN
				SET @parsed = SUBSTRING(@content,1,@idxA-1) -- equip name
			END
			
			
			SET @content = SUBSTRING(@content,@idxA+1,3999) -- 9:1005,11:2
			SET @idxA = CHARINDEX(',',@content) -- first comma index
			SET @tmp5 = SUBSTRING(@content,3,@idxA-3) -- parentDbId 
			SET @tmp100 = (SELECT name FROM nodes WHERE id=CONVERT(int,@tmp5)) -- parent name, UI length 16, DB needs 96.
			SET @parsed = @parsed+','+@tmp100 
						
			SET @content = SUBSTRING(@content,@idxA+1,3999) -- 11:2
			SET @idxA = CHARINDEX(':',@content) -- colon index
			SET @tmp5 = SUBSTRING(@content,@idxA+1,3999) -- treeId 
			SET @tmp100 = (SELECT n.name FROM nodes n, trees t WHERE t.id=CONVERT(int,@tmp5) AND t.node_id=n.id) -- tree name, UI length 16, DB needs 96.
			SET @parsed = @parsed+','+@tmp100 
			
			INSERT INTO #order2 VALUES(@id, @time, @clientId, @classifyId, @actionId, @parsed)
		END
		
		-- action id=404/405/407 for 'Move Node Up', 'Move Node Down', 'Edit Role Access'
		-- code id=1/11 for Node/Tree
		ELSE IF @actionId IN (404,405,407)
		BEGIN
			-- 1:1006,11:2
			SET @idxA = CHARINDEX(',',@content) -- first comma index
			SET @tmp5 = SUBSTRING(@content,3,@idxA-3) -- nodeDbId 
			SET @parsed = (SELECT name FROM nodes WHERE id=CONVERT(int,@tmp5)) -- node name
						
			SET @content = SUBSTRING(@content,@idxA+1,3999) -- 11:2
			SET @idxA = CHARINDEX(':',@content) -- colon index
			SET @tmp5 = SUBSTRING(@content,@idxA+1,3999) -- treeId 
			SET @tmp10 = (SELECT n.name FROM nodes n, trees t WHERE t.id=CONVERT(int,@tmp5) AND t.node_id=n.id) -- tree name
			SET @parsed = @parsed+','+@tmp10 
			
			INSERT INTO #order2 VALUES(@id, @time, @clientId, @classifyId, @actionId, @parsed)
		END
		
		-- action id=406/408 for 'Edit Name', 'Edit Alias'
		-- content code=1/2/11/12 for Node/Location/Tree/Alias
		ELSE IF @actionId IN (406,408)
		BEGIN
			-- 1:1001,namexx --> namexxx,11:2
			SET @idxA = CHARINDEX(',',@content) -- first comma index
			SET @content = SUBSTRING(@content,@idxA+1,3999) -- namexx --> namexxx,11:2
			SET @idxA = CHARINDEX(',',@content) -- first comma index
			SET @parsed = SUBSTRING(@content,1,@idxA-1) -- namexx --> namexxx 
			
			INSERT INTO #order2 VALUES(@id, @time, @clientId, @classifyId, @actionId, @parsed)
		END
		
		-- action id=422/423/424 for Topology Drag Location/Device/Equip Node
		-- action id=425/426/427 for Topology Location/Device/Equip Node Icon
		-- content code=1/9/11/15/16 for Node/Parent/Tree/PositionX/PositionY
		ELSE IF @actionId IN (422,423,424,425,426,427)
		BEGIN
			DECLARE @codeX varchar(5), @codeY varchar(5) 
			IF @actionId IN (422,423,424)
			BEGIN
				SET @codeX = '15:' -- position X
				SET @codeY = '16:' -- position Y
			END
			ELSE BEGIN
				SET @codeX = '17:' -- width
				SET @codeY = '18:' -- height
			END
		
			-- 1:1015,15:500,16:500,9:1013,11:2
			-- equipName,15:500,16:500,9:1013,11:2
			SET @idxA = CHARINDEX(',',@content) -- first comma index
			
			IF @actionId IN (422,423,425,426)
			BEGIN
				SET @tmp5 = SUBSTRING(@content,3,@idxA-3) -- location/device nodeDbId
				SET @parsed = (SELECT name FROM nodes WHERE id=CONVERT(int,@tmp5)) -- location/device nodeName
			END
			ELSE BEGIN
				SET @parsed = SUBSTRING(@content,1,@idxA-1) -- equip nodeName
			END
			
			SET @content = SUBSTRING(@content,@idxA+1,3999) -- 15:500,16:500,9:1013,11:2
			SET @content = REPLACE(@content,@codeX,'') -- 500,16:500,9:1013,11:2
			SET @idxA = CHARINDEX(',',@content) -- first comma index
			SET @parsed = @parsed + ',' + SUBSTRING(@content,1,@idxA-1) -- nodeName,500
			
			SET @content = SUBSTRING(@content,@idxA+1,3999) -- 16:500,9:1013,11:2
			SET @content = REPLACE(@content,@codeY,'') -- 500,9:1013,11:2
			SET @idxA = CHARINDEX(',',@content) -- first comma index
			SET @parsed = @parsed + ',' + SUBSTRING(@content,1,@idxA-1) -- nodeName,500,500
			
			SET @content = SUBSTRING(@content,@idxA+1,3999) -- 9:1013,11:2
			SET @content = REPLACE(@content,'9:','') -- 1013,11:2
			SET @idxA = CHARINDEX(',',@content) -- first comma index
			SET @tmp5 = SUBSTRING(@content,1,@idxA-1) -- parent nodeDbId
			SET @tmp100 = (SELECT name FROM nodes WHERE id=CONVERT(int,@tmp5)) -- parentName
			SET @parsed = @parsed + ',' + @tmp100 -- nodeName,500,500,parentName

			SET @idxA = CHARINDEX(':',@content) -- first colon index
			SET @tmp5 = SUBSTRING(@content,@idxA+1,3999) -- treeId
			SET @tmp100 = (SELECT n.name FROM nodes n, trees t WHERE t.id=CONVERT(int,@tmp5) AND t.node_id=n.id) -- treeName
			SET @parsed = @parsed + ',' + @tmp100 -- nodeName,500,500,parentName,treeName
				
			INSERT INTO #order2 VALUES(@id, @time, @clientId, @classifyId, @actionId, @parsed)
		END
		
		-- action id=409/410 for Topology Add Dvc/Eqp Link
		-- action id=413/414 for Topology Delete Dvc/Eqp Link
		-- content code=3/4 for Topology Dvc/Eqp Link
		ELSE IF @actionId IN (409,410,413,414)
		BEGIN
			-- add device link, 3:[treeId node1DbId if1 node2DbId if2] 
			-- add equip link,  4:[treeId node1DbId if1 node2DbId name]
			-- delete link,     3:[treeId node1DbId if1]
			SET @idxA = CHARINDEX('[',@content) -- first '[' index
			SET @content = SUBSTRING(@content,@idxA+1,3999) -- treeId node1DbId if1 node2DbId if2]
			SET @idxA = CHARINDEX(' ',@content) -- first space index
			SET @tmp5 = SUBSTRING(@content,1,@idxA-1) -- treeId
			SELECT @parsed=n.name FROM trees t, nodes n WHERE t.id=CAST(@tmp5 AS int) AND t.node_id=n.id -- treeName
			
			SET @content = SUBSTRING(@content,@idxA+1,3999) -- node1DbId if1 node2DbId if2]
			SET @idxA = CHARINDEX(' ',@content) -- first space index
			SET @tmp5 = SUBSTRING(@content,1,@idxA-1) -- node1DbId
			SELECT @tmp100=[name], @tmp10=[type_id] FROM nodes WHERE id=CAST(@tmp5 AS int) -- node1Name, node1DeviceType
			SET @parsed = @parsed+','+@tmp100+','+@tmp10 -- treeName,node1Name,node1DeviceType
			
			IF @actionId IN (413,414)
			BEGIN
				SET @content = SUBSTRING(@content,@idxA+1,3999) -- if1]
				SET @idxA = CHARINDEX(']',@content) -- first ']' index
				SET @tmp20 = SUBSTRING(@content,1,@idxA-1) -- if1
				SET @parsed = @parsed+','+@tmp20 -- treeName,node1Name,,node1DeviceType,if1
			END
			
			IF @actionId IN (409,410)
			BEGIN
				SET @content = SUBSTRING(@content,@idxA+1,3999) -- if1 node2DbId if2]
				SET @idxA = CHARINDEX(' ',@content) -- first space index
				SET @tmp20 = SUBSTRING(@content,1,@idxA-1) -- if1
				SET @parsed = @parsed+','+@tmp20 -- treeName,node1Name,,node1DeviceType,if1
			
				SET @content = SUBSTRING(@content,@idxA+1,3999) -- node2DbId if2]
				SET @idxA = CHARINDEX(' ',@content) -- first space index
				SET @tmp5 = SUBSTRING(@content,1,@idxA-1) -- node2DbId
				SELECT @tmp100=[name] , @tmp10=[type_id] FROM nodes WHERE id=CAST(@tmp5 AS int) -- node2Name, node2DeviceType
				SET @parsed = @parsed+','+@tmp100+','+@tmp10 -- treeName,node1Name,node1DeviceType,if1,node2Name,node2DeviceType
				
				SET @content = SUBSTRING(@content,@idxA+1,3999) -- if2]
				SET @idxA = CHARINDEX(']',@content) -- first ']' index

				----- EMS 2.100_01, modify procedure 'getClientActionLog', fix actionId 410 bug, if2 becomes equip name, length not enough
				SET @tmp100 = SUBSTRING(@content,1,@idxA-1) -- if2
				SET @parsed = @parsed+','+@tmp100 -- treeName,node1Name,node1DeviceType,if1,node2Name,node2DeviceType,if2
			END 
			
			INSERT INTO #order2 VALUES(@id, @time, @clientId, @classifyId, @actionId, @parsed)
		END
		
		-- action id=601 for Ack Alarm
		-- content code=5 for Alarm Log
		ELSE IF @actionId=601
		BEGIN
			-- 5:alarmLogId,true
			SET @idxA = CHARINDEX(',',@content) -- first comma index
			SET @tmp5 = SUBSTRING(@content,3,@idxA-3) -- logDbId 
			SET @parsed = SUBSTRING(@content,@idxA+1,3999) -- true
			
			SET @tmp10 = (SELECT agent_id FROM alarmLog WHERE id=CAST(@tmp5 AS int)) -- agentDbId
			SET @parsed = @parsed + ',' + (SELECT name FROM nodes WHERE id=CAST(@tmp10 AS int)) -- true,agentName 
			SET @parsed = @parsed + ',' + (SELECT location+','+message FROM alarmLog WHERE id=CAST(@tmp5 AS int)) -- true,agentName,location,message
			
			INSERT INTO #order2 VALUES(@id, @time, @clientId, @classifyId, @actionId, @parsed)
		END
		
		-- action id=602 for Ack Trap
		-- content code=6 for Trap Log
		ELSE IF @actionId=602
		BEGIN
			-- 6:trapLogId,true
			SET @idxA = CHARINDEX(',',@content) -- first comma index
			SET @tmp5 = SUBSTRING(@content,3,@idxA-3) -- logDbId 
			SET @parsed = SUBSTRING(@content,@idxA+1,3999) -- true
			
			SET @tmp10 = (SELECT agent_id FROM trapLog WHERE id=CAST(@tmp5 AS int)) -- agentDbId
			SET @parsed = @parsed + ', ' + (SELECT name FROM nodes WHERE id=CAST(@tmp10 AS int)) -- true, agentName 
			SET @parsed = @parsed + ', ' + (SELECT [message] FROM trapLog WHERE id=CAST(@tmp5 AS int)) -- true, agentName, message
			
			INSERT INTO #order2 VALUES(@id, @time, @clientId, @classifyId, @actionId, @parsed)
		END
		
		-- others
		ELSE BEGIN
			INSERT INTO #order2 VALUES(@id, @time, @clientId, @classifyId, @actionId, @content) 
		END
		                                             
		FETCH NEXT FROM cur INTO @id, @time, @clientId, @classifyId, @actionId, @content 
	END                                                                                              
	CLOSE cur                                        
	DEALLOCATE cur        
	
----- EMS 2.88_01, modify procedure 'getClientActionLog', fix SQL 2014 ordry by issue
	IF(@orderDir='ASC')
	BEGIN
		SET @orderState1 = 'o2.'+@orderCol+' ASC,  o2.id ASC'
	END
	ELSE IF(@orderDir='DESC')
	BEGIN
		SET @orderState1 = 'o2.'+@orderCol+' DESC, o2.id DESC'
	END
	ELSE
	BEGIN
		SET @orderState1 = 'o2.id ASC,  o2.time ASC'
	END
	
	EXEC('
		SELECT o2.[id], o2.[time], client_name=c.[name], o2.[classify_id], o2.[action_id], o2.[content]
		FROM #order2 o2, client c 
		WHERE o2.[client_id]=c.[id] 
	
		ORDER BY '+@orderState1)
	
	DROP TABLE #order
	DROP TABLE #order2
GO


----- EMS 2.16_03, add procedure 'getFirstAgentDeviceType'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getFirstAgentDeviceType]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getFirstAgentDeviceType]
GO
CREATE PROCEDURE [dbo].[getFirstAgentDeviceType]
AS
	SELECT TOP 1 type_id FROM agent a, nodes n where a.id=n.id
GO



----- EMS 2.30_01, add procedure 'addAlarmlog'   
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[addAlarmLog]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[addAlarmLog]
GO

CREATE PROCEDURE [dbo].[addAlarmLog]
    @agent_id	int,           
    @time_begin datetime,        
    @location	varchar(100),           
    @severity   int,           
    @message    varchar(100)
     
AS
	INSERT INTO alarmLog(agent_id, time_begin, time_end, location, severity, message, ack, time_ack)
		VALUES(@agent_id, @time_begin, '', @location, @severity, @message, 0, '')
	
	IF @@error<>0 
		GOTO ERR

	-- select record for file storage in host pc		
	DECLARE @fromSql varchar(512)
	/*
	SET @fromSql='alarmLog WHERE agent_id='''+convert(varchar(512), @agent_id)+''''
			+' AND time_begin='''+convert(varchar(512), @time_begin,120)+''''
			+' AND location='''+convert(varchar(512), @location)+'''' 
			+' AND severity='''+convert(varchar(512), @severity)+''''
			+' AND message='''+convert(varchar(512), @message)+''''
	*/
	SET @fromSql='alarmLog WHERE id='''+convert(varchar(100), (SELECT @@identity))+''''

	EXEC getAlarmLogs '3', '', '', @fromSql, '', ''

	RETURN 0

ERR:
RETURN -1
GO


----- EMS 2.30_01, add procedure 'editAlarmLog'
----- EMS 2.63_01, modify procedure 'editAlarmLog', rename to 'editAlarmLogAck'   
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[editAlarmLog]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[editAlarmLog]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[editAlarmLogAck]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[editAlarmLogAck]
GO

CREATE PROCEDURE [dbo].[editAlarmLogAck] 
	@clientName	varchar(100),	
	@id			int,
	@ack		tinyint,
	@time_ack	datetime
	
AS
	DECLARE @client_id int

	SELECT @client_id=(SELECT id FROM client WHERE name=@clientName)
	IF @client_id IS NULL
		SET @client_id=NULL

	-- ack 0:to be non-acked, erase use and ack time
	-- ack 1:to be acked, record ack time 
	IF @ack != 1
	BEGIN
		SET @client_id=NULL
		SET @time_ack=''
	END

	UPDATE alarmLog
		SET ack=@ack, client_id=@client_id, time_ack=@time_ack	
		WHERE id=@id


	-- get data for EMS server to do ack alarm event
	SELECT id, agent_id, time_begin, location, severity, message, ack 
		FROM alarmLog
		WHERE id=@id
GO

----- EMS 2.63_01, add procedure 'editAlarmLogEndTime'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[editAlarmLogEndTime]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[editAlarmLogEndTime]
GO

CREATE PROCEDURE [dbo].[editAlarmLogEndTime] 
	@id			int,
	@time_end	datetime
	
AS

	UPDATE alarmLog
		SET time_end=@time_end	WHERE id=@id
GO


----- EMS 2.30_01, add procedure 'getAlarmLogs'
----- EMS 2.89_03, modify procedure 'getAlarmLogs', fix SQL 2014 order by issue
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[getAlarmLogs]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getAlarmLogs]
GO

CREATE PROCEDURE [dbo].[getAlarmLogs]
	@mode     int,
	@pageRow  int,
	@dataRow  int,
	@fromSql  varchar(512),
	@orderCol varchar(100),
	@orderDir varchar(100)	
AS
	-- convert column name to real column in table
	IF (@orderCol='actor')	
		SET @orderCol='client_id'

	-- create order column statement 
	-- add sub-index for order column if need.
	DECLARE 
		@orderState1 varchar(100),
		@orderState2 varchar(100)

	IF(@orderDir='ASC')
	BEGIN
		SET @orderState1 = @orderCol+' ASC,  id ASC'
		SET @orderState2 = @orderCol+' DESC, id DESC'
	END
	ELSE
	BEGIN
		SET @orderState1 = @orderCol+' DESC, id DESC'
		SET @orderState2 = @orderCol+' ASC,  id ASC'
	END

	-- create tmp table with older data for further query
	IF OBJECT_ID(N'[tempdb].[dbo].[#order]') IS NOT NULL
		DROP TABLE #order

	CREATE TABLE #order (
		id      	int,
		agent_id    int,
		time_begin  datetime,
		time_end    datetime,
		location    varchar(100),
		severity    int,
		message     varchar(100),
		ack         tinyint,
		client_id	int,
		time_ack	datetime
	)


	IF(@mode = 1)	-- page	
	BEGIN 
		-- select rows for page
		EXEC('INSERT INTO #order 
			SELECT * FROM (SELECT TOP '+@pageRow+' * FROM 
				(SELECT TOP '+@dataRow+' * FROM '+@fromSql+' ORDER BY '+@orderState1+') t1 
				 ORDER BY '+@orderState2+') t2 ORDER BY '+@orderState1
		)
	END
	ELSE IF (@mode = 2)	-- report	
	BEGIN
		-- select all rows for report
		EXEC('INSERT INTO #order 
				SELECT * FROM '+@fromSql+' ORDER BY '+@orderState1
		)
	END
	ELSE IF (@mode = 3) -- history
	BEGIN
		-- select inserted record for history file storage
		EXEC('INSERT INTO #order
				SELECT * FROM '+@fromSql
		)
	END
	
	IF(@orderDir='ASC')
	BEGIN
		SET @orderState1 = 'o.'+@orderCol+' ASC,  o.id ASC'
	END
	ELSE IF(@orderDir='DESC')
	BEGIN
		SET @orderState1 = 'o.'+@orderCol+' DESC, o.id DESC'
	END 
	ELSE BEGIN
		SET @orderState1 = 'o.time_begin ASC,  o.id ASC'
	END

	EXEC('
		SELECT o.id, o.ack, o.time_begin, o.time_end, device=n.name, a.ip_address, o.location, o.message, o.severity, actor=c.name, o.time_ack 
		FROM #order o LEFT OUTER JOIN client c on o.client_id=c.id, agent a, nodes n
		WHERE o.agent_id=a.id AND o.agent_id=n.id 
		 
		ORDER BY '+@orderState1)
		
	DROP TABLE #order
GO


----- EMS 2.30_01, modify procedure 'insertTrapList', rename to 'addTrapList'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[insertTrapList]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[insertTrapList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[addTrapList]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[addTrapList]
GO

CREATE PROCEDURE [dbo].[addTrapList]
    @agent_id         int,           -- agentDBId
    @receive_time     datetime,      -- receiveTime
    @timestamp_device int,           -- timeStamp
    @trap_id          int,           -- specificId
    @body             varchar(1024)  -- value    
AS
	INSERT INTO traplist(agent_id, timestamp_system, trap_id, timestamp_device, body, op_name)
		SELECT @agent_id, @receive_time, @trap_id, @timestamp_device, @body, a.op_name
			FROM agent a where a.id=@agent_id
	
	IF @@error<>0 
		GOTO ERR	

	--select @id = @@identity 
	--if @@error <> 0 return -267
	--if @trap_id in (0,10,11,12,13) exec gen_decompositiontrap @id

	-- waiting to integer the select record for report in host pc

	RETURN 0
	
ERR:
RETURN -1
GO
 
 
----- EMS 2.44_07, rename procedure 'addTrapList' to 'addTrapLog'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[addTrapList]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[addTrapList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[addTrapLog]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[addTrapLog]
GO
CREATE PROCEDURE [dbo].[addTrapLog]
    @agent_id         int,           -- agentDdId
    @time             datetime,      -- receiveTime
    @timestamp        int,           -- timeStamp
    @specific_type    int,           -- specificType
    @message          varchar(1024)  -- message       

AS
	INSERT INTO trapLog(agent_id, time, timestamp, specific_type, message)
		values(@agent_id, @time, @timestamp, @specific_type, @message)
	
	IF @@error<>0 
		GOTO ERR	

	-- select record for file storage in host pc		
	DECLARE @fromSql varchar(512)

	SET @fromSql='trapLog WHERE id='''+convert(varchar(100), (SELECT @@identity))+''''

	EXEC getTrapLogs '3', '', '', @fromSql, '', ''

	RETURN 0
	
ERR:
RETURN -1
GO


----- EMS 2.44_07, rename procedure 'getTrapList' to 'getTrapLogs'
----- EMS 2.89_03, modify procedure 'getTrapLogs', fix SQL 2014 order by issue
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getTrapList]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getTrapList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getTrapLogs]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getTrapLogs]
GO
CREATE PROCEDURE [dbo].[getTrapLogs]
	@mode     int,
	@pageRow  int,
	@dataRow  int,
	@fromSql  varchar(512),
	@orderCol varchar(100),
	@orderDir varchar(100)	

AS
	-- convert column name to real column in table
	IF (@orderCol='actor')	
		SET @orderCol='client_id'

	-- create order column statement 
	-- add sub-index for order column if need.
	DECLARE 
		@orderState1 varchar(100),
		@orderState2 varchar(100)

	IF(@orderDir='ASC')
	BEGIN
		SET @orderState1 = @orderCol+' ASC,  id ASC'
		SET @orderState2 = @orderCol+' DESC, id DESC'
	END
	ELSE
	BEGIN
		SET @orderState1 = @orderCol+' DESC, id DESC'
		SET @orderState2 = @orderCol+' ASC,  id ASC'
	END

	-- create tmp table with older data for further query
	IF OBJECT_ID(N'[tempdb].[dbo].[#order]') IS NOT NULL
		DROP TABLE #order
	
	CREATE TABLE #order(
		id             int,
		agent_id       int,
		time           datetime,
		specific_type  int,
	    timestamp      int,
	    message       varchar(1024), 
	    ack            tinyint,
		clear          tinyint,	     
		time_ack       datetime,
		remark         varchar(50),
		client_id      int
	)

	IF(@mode = 1)	-- page	
	BEGIN 
		-- select rows for page
		EXEC('INSERT INTO #order 
			SELECT * FROM (SELECT TOP '+@pageRow+' * FROM 
				(SELECT TOP '+@dataRow+' * FROM '+@fromSql+' ORDER BY '+@orderState1+') t1 
				 ORDER BY '+@orderState2+') t2 ORDER BY '+@orderState1
		)
	END
	ELSE IF (@mode = 2)	-- report	
	BEGIN
		-- select all rows for report
		EXEC('INSERT INTO #order 
				SELECT * FROM '+@fromSql+' ORDER BY '+@orderState1
		)
	END
	ELSE IF (@mode = 3) -- history
	BEGIN
		-- select inserted record for history file storage
		EXEC('INSERT INTO #order
				SELECT * FROM '+@fromSql
		)
	END
	
	IF(@orderDir='ASC')
	BEGIN
		SET @orderState1 = 'o.'+@orderCol+' ASC,  o.id ASC'
	END
	ELSE IF(@orderDir='DESC')
	BEGIN
		SET @orderState1 = 'o.'+@orderCol+' DESC,  o.id DESC'
	END
	ELSE
	BEGIN
		SET @orderState1 = 'o.time ASC,  o.id ASC'
	END

	EXEC('
		SELECT o.id, o.ack, o.time, device=n.name, a.ip_address, o.timestamp, o.specific_type, o.message, actor=c.name, o.time_ack 
		FROM #order o LEFT OUTER JOIN client c on o.client_id=c.id, agent a, nodes n
		WHERE o.agent_id=a.id AND o.agent_id=n.id	
		
		ORDER BY '+@orderState1)

	DROP TABLE #order
GO


----- EMS 2.44_07, add procedure 'editTrapLog' 
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[editTrapLog]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[editTrapLog]
GO
CREATE PROCEDURE [dbo].[editTrapLog] 
	@clientName	varchar(100),	
	@id			int,
	@ack		tinyint,
	@time_ack	datetime

AS
	DECLARE @client_id int

	SELECT @client_id=(SELECT id FROM client WHERE name=@clientName)

	-- ack 0:to be non-acked, erase use and ack time
	-- ack 1:to be acked, record ack time 
	IF @ack != 1
	BEGIN
		SET @client_id=NULL
		SET @time_ack=''
	END

	UPDATE trapLog
		SET ack=@ack, client_id=@client_id, time_ack=@time_ack	
		WHERE id=@id
GO


----- EMS 2.30_01, modify procedure 'insertPMList', rename to 'addPMList'
----- EMS 2.45_05, rename procedure 'addPMList' to 'addPmLog' 
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[insertPMList]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[insertPMList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[addPMList]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[addPMList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[addPmLog]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[addPmLog]
GO

CREATE PROCEDURE [dbo].[addPmLog]
    @agent_id    int,
    @receiveTime datetime, 
	@body        varchar(1024)
	
AS 
	INSERT INTO pmLog(agent_id, time, trap_id, timestamp, body) 
		VALUES(@agent_id, @receiveTime, 0, 0, @body)

	IF @@error<>0 
		GOTO ERR

	-- select record for file storage in host pc		
	DECLARE @fromSql varchar(512)

	SET @fromSql='pmLog WHERE id='+convert(varchar(100), (SELECT @@identity))

	EXEC getPmLogs '3', '', '', @fromSql, '', ''

	RETURN 0

ERR:
RETURN -1
GO


----- EMS 2.45_05, add procedure 'getPmLogs'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getPmLogs]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getPmLogs]
GO
CREATE PROCEDURE [dbo].[getPmLogs]
	@mode     int,
	@pageRow  int,
	@dataRow  int,
	@fromSql  varchar(512),
	@orderCol varchar(100),
	@orderDir varchar(100)	

AS
	-- create order column statement 
	-- add sub-index for order column if need.
	DECLARE 
		@orderState1 varchar(100),
		@orderState2 varchar(100)

	IF(@orderDir='ASC')
	BEGIN
		SET @orderState1 = @orderCol+' ASC,  id ASC'
		SET @orderState2 = @orderCol+' DESC, id DESC'
	END
	ELSE
	BEGIN
		SET @orderState1 = @orderCol+' DESC, id DESC'
		SET @orderState2 = @orderCol+' ASC,  id ASC'
	END

	-- create tmp table with older data for further query
	IF OBJECT_ID(N'[tempdb].[dbo].[#order]') IS NOT NULL
		DROP TABLE #order
	
	CREATE TABLE #order(
		id             int,
		agent_id       int,
		time           datetime,
		trap_id        int,
	    timestamp      int,
	    body           varchar(1024), 
	)

	IF(@mode = 1)	-- page	
	BEGIN 
		-- select rows for page
		EXEC('INSERT INTO #order 
			SELECT * FROM (SELECT TOP '+@pageRow+' * FROM 
				(SELECT TOP '+@dataRow+' * FROM '+@fromSql+' ORDER BY '+@orderState1+') t1 
				 ORDER BY '+@orderState2+') t2 ORDER BY '+@orderState1
		)
	END
	ELSE IF (@mode = 2)	-- report	
	BEGIN
		-- select all rows for report
		EXEC('INSERT INTO #order 
				SELECT * FROM '+@fromSql+' ORDER BY '+@orderState1
		)
	END
	ELSE IF (@mode = 3) -- history
	BEGIN
		-- select inserted record for history file storage
		EXEC('INSERT INTO #order
				SELECT * FROM '+@fromSql
		)
	END
	
	SELECT o.id, o.time, 'device'=n.name, a.ip_address, o.body
		FROM #order o, agent a, nodes n
		WHERE o.agent_id=a.id AND o.agent_id=n.id	
		
	DROP TABLE #order
GO


----- EMS 2.45_04, rename procedure 'treeList' to 'getUserTrees'
----- EMS 2.81_01, modify procedure 'getUserTrees', add role access check
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[treeList]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[treeList]
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getUserTrees]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getUserTrees]
GO
CREATE PROCEDURE [dbo].[getUserTrees]
	@username varchar(50), 
	@orderCol varchar(100),
	@orderDir varchar(100)
	
AS 
	DECLARE 
		@client_id int

	-- client information
	SELECT @client_id=id
		FROM client 
		WHERE name=@username 

	IF OBJECT_ID(N'[tempdb].[dbo].[#t]') IS NOT NULL
		DROP TABLE #t

	-- add public trees and trees created by user
	-- excluding default repository tree (id=1)
	-- search tree's root node in tree links.
	SELECT t.id, n.name, t.type, 'username'=c.name INTO #t
		FROM trees t, treelinks l, nodes n, client c  
		WHERE l.parent_id=-1 AND l.child_id=t.node_id
			  AND l.tree_id=t.id AND t.node_id=n.id AND n.client_id=c.id 
			  AND t.id<>1 AND (t.type=1 OR c.id=@client_id)
			  AND t.node_id IN (SELECT id FROM [dbo].[fn_getAllowedNodesByUserName](@username)) 
	
	-- distinguish duplication
	-- select distinct tree_id, name, type from #t  
	
	EXEC('SELECT * FROM #t ORDER BY '+ @orderCol +' '+ @orderDir)

	DROP TABLE #t
GO

----- EMS 2.52_01, add procedure 'addInventoryList', 2013-0617
----- EMS 2.54_01, remove the script for add procedure 'addInventoryList'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[addInventoryList]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[addInventoryList]
GO


----- EMS 2.52_01, add procedure 'getInventoryList', 2013-0617
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getInventoryList]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getInventoryList]
GO

----- EMS 2.54_01, modify procedure 'getInventoryList'
----- EMS 2.88_01, modify procedure 'getInventoryList', temp table column 'type' length should be 128
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[getInventoryList]
	@mode     int,
	@pageRow  int,
	@dataRow  int,
	@fromSql  varchar(512),
	@orderCol varchar(100),
	@orderDir varchar(100)	

AS
	-- create order column statement 
	-- add sub-index for order column if need.
	DECLARE 
		@orderState1 varchar(100),
		@orderState2 varchar(100)
		
	IF(@orderDir='ASC')
	BEGIN
		IF(@orderCol='agent_id')
		BEGIN
			SET @orderState1 = @orderCol+' ASC,  location ASC'
			SET @orderState2 = @orderCol+' DESC, location DESC'
		END
		ELSE
		BEGIN
			SET @orderState1 = @orderCol+' ASC,  agent_id ASC, location ASC'
			SET @orderState2 = @orderCol+' DESC, agent_id DESC, location DESC'
		END
	END
	ELSE
	BEGIN
		IF(@orderCol='agent_id')
		BEGIN
			SET @orderState1 = @orderCol+' DESC, location DESC'
			SET @orderState2 = @orderCol+' ASC,  location ASC'
		END
		ELSE
		BEGIN
			SET @orderState1 = @orderCol+' DESC, agent_id DESC, location DESC'
			SET @orderState2 = @orderCol+' ASC,  agent_id ASC, location ASC'
		END
	END
	
	-- create tmp table with older data for further query
	-- temp table column 'type' length should be 128
	IF OBJECT_ID(N'[tempdb].[dbo].[#order]') IS NOT NULL
	DROP TABLE #order
	
----- EMS 2.87_15, modify procedure 'getInventoryList', change alias length 128 to 768. UI length 128, DB needs 768.
	CREATE TABLE #order(
		id       int,
		agent_id int,
        location varchar(64), 
        type     varchar(128), -- temp table column 'type' length should be 128
        hw       varchar(64),
        fw       varchar(64),
        sn       varchar(64),
        alias    varchar(768),
        status   varchar(16),
        date     datetime,
        userId   varchar(512),
        remark1  varchar(512),
        remark2  varchar(512),
        remark3  varchar(512)
	)
		
	IF(@mode = 1)	-- page	
	BEGIN 
		-- select rows for page
		EXEC('INSERT INTO #order
			SELECT * FROM (SELECT TOP '+@pageRow+' * FROM 
				(SELECT TOP '+@dataRow+' * FROM '+@fromSql+' ORDER BY '+@orderState1+') t1 
				 ORDER BY '+@orderState2+') t2 ORDER BY '+@orderState1
		)
	END
	ELSE IF (@mode = 2)	-- report	
	BEGIN
		-- select all rows for report
		EXEC('INSERT INTO #order
				SELECT * FROM '+@fromSql+' ORDER BY '+@orderState1
		)
	END
	ELSE IF (@mode = 3) -- history
	BEGIN
		-- select inserted record for history file storage
		EXEC('INSERT INTO #order
				SELECT * FROM '+@fromSql
		)
	END
		
----- EMS 2.89_03, modify procedure 'getInventoryList', fix SQL 2014 ordry by issue
	IF(@orderDir='ASC')
	BEGIN
		IF(@orderCol='agent_id')
		BEGIN
			SET @orderState1 = @orderCol+' ASC,  location ASC'
		END
		ELSE
		BEGIN
			SET @orderState1 = @orderCol+' ASC,  agent_id ASC, location ASC'
		END
	END
	ELSE IF(@orderDir='DESC')
	BEGIN
		IF(@orderCol='agent_id')
		BEGIN
			SET @orderState1 = @orderCol+' DESC, location DESC'
		END
		ELSE
		BEGIN
			SET @orderState1 = @orderCol+' DESC, agent_id DESC, location DESC'
		END
	END
	ELSE 
	BEGIN
		SET @orderState1 = 'o.agent_id ASC, o.location ASC'
	END
		
	EXEC('
		SELECT o.id, o.agent_id, device=n.name, ip=a.ip_address, o.location, o.type, o.hw, o.fw, o.sn, o.alias, o.status, o.date, o.userId, o.remark1, o.remark2, o.remark3 
		FROM #order o, agent a, nodes n 
		WHERE o.agent_id=a.id AND o.agent_id=n.id
		
		ORDER BY '+@orderState1)

	DROP TABLE #order

GO

----- EMS 2.52_01, add procedure 'editInventoryList', 2013-0617
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[editInventoryList]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[editInventoryList]
GO

----- EMS 2.54_01, modify procedure 'editInventoryList'
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[editInventoryList] 
	@agentId    int,
	@location   varchar(128),
	@idt 	    varchar(512),
	@remark1	varchar(512),
	@remark2	varchar(512),
	@remark3	varchar(512)

AS
	
	UPDATE inventoryListByServer 
		SET userId = @idt, remark1 = @remark1, remark2 = @remark2, remark3 = @remark3  	
		WHERE agent_id = @agentId AND location = @location
GO

----- EMS 2.52_01, add procedure 'deleteInventoryList', 2013-0617
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[deleteInventoryList]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[deleteInventoryList]
GO

----- EMS 2.54_01, modify procedure 'deleteInventoryList'
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[deleteInventoryList] 
	@agentId     int,
	@location    varchar(128)

AS
	
	DELETE FROM inventoryListByServer
		WHERE agent_id=@agentId AND location=@location
GO


----- EMS 2.63_01, add procedure 'getAlarms'
----- EMS 2.64_01, modify procedure 'getAlarms'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getAlarms]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getAlarms]
GO

CREATE PROCEDURE [dbo].[getAlarms]
	@agent_id		int

AS
	
	SELECT * FROM alarm WHERE agent_id=@agent_id

GO


----- EMS 2.64_01, add procedure 'addAlarm'
----- EMS 2.68_01, modify procedure 'addAlarm', add column param for DD alarm threshold
----- EMS 2.72_01, modify procedure 'addAlarm', no parameter for model_name,  add one parameter for 'model_id'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[addAlarm]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[addAlarm]
GO

CREATE PROCEDURE [dbo].[addAlarm]
    @agent_id	 int,
    @rack		 tinyint,
    @slot		 tinyint,
    @side		 tinyint,
    -- @model_name	 varchar(50),
    @type		 smallint,
    @idx		 tinyint, 
    @param	     varchar(10),
    @severity	 tinyint,
    @enable		 bit,
    @model_id int
     
AS
	INSERT INTO alarm(agent_id, rack, slot, side, type, idx, param, severity, enable, model_id)
		VALUES(@agent_id, @rack, @slot, @side, @type, @idx, @param, @severity, @enable, @model_id)

GO


----- EMS 2.64_01, add procedure 'deleteAlarm'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[deleteAlarm]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[deleteAlarm]
GO

CREATE PROCEDURE [dbo].[deleteAlarm]
	@agent_id	int,
	@rack		int,
	@slot		int,
	@side		int,
	@type		int,
	@idx		int

AS
	
	IF @idx != -1
		-- delete specified alarm
		DELETE FROM alarm WHERE agent_id=@agent_id AND rack=@rack AND slot=@slot AND side=@side AND type=@type AND idx=@idx
	
	ELSE IF @type != -1
		-- delete type alarms
		DELETE FROM alarm WHERE agent_id=@agent_id AND rack=@rack AND slot=@slot AND side=@side AND type=@type
	
	ELSE IF @side != -1
	BEGIN 
		-- delete side alarms
		-- delete local side, also delete all remote sides
		IF @side = 0
			DELETE FROM alarm WHERE agent_id=@agent_id AND rack=@rack AND slot=@slot
		ELSE
			DELETE FROM alarm WHERE agent_id=@agent_id AND rack=@rack AND slot=@slot AND side=@side 
	END
	
	ELSE
		-- delete device alarm
		DELETE FROM alarm WHERE agent_id=@agent_id
GO


----- EMS 2.64_01, add procedure 'editAlarm'
----- EMS 2.68_01, modify procedure 'editAlarm', add column param for DD alarm threshold
----- EMS 2.72_01, modify procedure 'editAlarm', no paramater for 'model_name'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[editAlarm]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[editAlarm]
GO

CREATE PROCEDURE [dbo].[editAlarm]
    @agent_id	int,
    @rack		tinyint,
    @slot		tinyint,
    @side		tinyint,
    -- @model_name	varchar(50),
    @type		smallint,
    @idx		tinyint,
    @param	    varchar(10),  
    @severity	tinyint,
    @enable		bit
	
AS
	UPDATE alarm 
		SET param=@param, 
		    severity=@severity, 
		    enable=@enable 
		WHERE agent_id=@agent_id AND rack=@rack AND slot=@slot AND side=@side AND type=@type AND idx=@idx

GO

----- EMS 2.68_01, add procedure 'globalEditAlarm'
----- EMS 2.72_01, modify procedure 'globalEditAlarm', no parameter for 'model_name', add one parameter for 'model_id'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[globalEditAlarm]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].globalEditAlarm
GO

CREATE PROCEDURE [dbo].globalEditAlarm
    @agtId		int,
    -- model_name varchar(50),
    @modelId	int,
    @type		smallint,
    @idx		tinyint, 
    @param	    varchar(10),
    @severity	tinyint,
    @enable		bit
	
AS	
	UPDATE alarm 
	SET param=@param, 
		severity=@severity, 
		enable=@enable 
	WHERE agent_id=@agtId AND model_id=@modelId AND type=@type AND idx=@idx 
GO

----- EMS 2.72_01, add new table 'alarmTemplate' and create new templates for CHT/Zelax/CNT models
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[alarmTemplate]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[alarmTemplate](
		[id]		[int] NOT NULL,
		[side]		[tinyint] NOT NULL,
		[type]		[smallint] NOT NULL,
		[idx]		[tinyint] NOT NULL,
		[severity]	[tinyint] NOT NULL,
		[enable]	[bit] NOT NULL,
		[param]		[varchar](10) NOT NULL,
	 CONSTRAINT [PK_alarmTemplate] PRIMARY KEY CLUSTERED 
	(
		[id] ASC,
		[side] ASC,
		[type] ASC,
		[idx] ASC
	)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
	) ON [PRIMARY]
END
GO

DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0710), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm
	    
----- DEVICE_IGS803(72)
SET @dvc = 72
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 1, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 2, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,4, 1, 4,@ena,'') -- ALARM_FAULT_ON(4), SEVERITY_MINOR(4)    
    
	WHILE (@cnt <= 8) -- 8 UTP
	BEGIN		
		IF (@cnt <= 5) -- 5 Ring
		BEGIN
			IF (@cnt <= 3)  -- 3 FIBER
			BEGIN
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)        
			END
		
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,7, @cnt, 4,@ena,'') -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)        
		END	
			
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2, @cnt, 5,@ena,'') -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)        
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,5, @cnt, 3,@ena,'') -- ALARM_POEBUDGET_EXCEED(5), SEVERITY_MAJOR(3)        
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,6, @cnt, 3,@ena,'') -- ALARM_POEPD_OVERLOAD(6), SEVERITY_MAJOR(3)        
		
		SET @cnt = @cnt + 1
	END
END

----- EMS 2.86_01, add new alarm template IGS-804
----- DEVICE_IGS804(79)
SET @dvc = 79
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 1, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 2, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,4, 1, 4,@ena,'') -- ALARM_FAULT_ON(4), SEVERITY_MINOR(4)    
    
	WHILE (@cnt <= 8) -- 8 UTP
	BEGIN		
		IF (@cnt <= 5) -- 5 Ring
		BEGIN
			IF (@cnt <= 4)  -- 4 FIBER
			BEGIN
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)        
			END
		
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,7, @cnt, 4,@ena,'') -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)        
		END	
			
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2, @cnt, 5,@ena,'') -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)        
		-- IGS-804 has no PoE
		
		SET @cnt = @cnt + 1
	END
END

----- DEVICE_IGS402(73)
SET @dvc = 73
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 1, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 2, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,4, 1, 4,@ena,'') -- ALARM_FAULT_ON(4), SEVERITY_MINOR(4)    
    
	WHILE (@cnt <= 4) -- 4 UTP
	BEGIN		
		IF (@cnt <= 3) -- 3 Ring
		BEGIN
			IF (@cnt <= 2)  -- 2 FIBER
			BEGIN
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)        
			END
		
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,7, @cnt, 4,@ena,'') -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)        
		END	
			
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2, @cnt, 5,@ena,'') -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)        
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,5, @cnt, 3,@ena,'') -- ALARM_POEBUDGET_EXCEED(5), SEVERITY_MAJOR(3)        
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,6, @cnt, 3,@ena,'') -- ALARM_POEPD_OVERLOAD(6), SEVERITY_MAJOR(3)        
		
		SET @cnt = @cnt + 1
	END
END

----- DEVICE_IGS404(77)
SET @dvc = 77
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 1, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 2, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,4, 1, 4,@ena,'') -- ALARM_FAULT_ON(4), SEVERITY_MINOR(4)    
    
	WHILE (@cnt <= 4) -- 4 UTP, 4 FIBER, 4 Ring
	BEGIN		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,7,  @cnt, 4,@ena,'')    -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)	
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)        
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,5,  @cnt, 3,@ena,'')    -- ALARM_POEBUDGET_EXCEED(5), SEVERITY_MAJOR(3)        
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,6,  @cnt, 3,@ena,'')    -- ALARM_POEPD_OVERLOAD(6), SEVERITY_MAJOR(3)        
		
		SET @cnt = @cnt + 1
	END
END

----- EMS 2.77_01, modify table 'alarmTemplate', change max ring number from 10 to 5
----- DEVICE_IGS812(75)
SET @dvc = 75
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 1, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 2, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,4, 1, 4,@ena,'') -- ALARM_FAULT_ON(4), SEVERITY_MINOR(4)    
    
	WHILE (@cnt <= 12) -- 12 FIBER
	BEGIN
		IF (@cnt <= 8) -- 8 UTP, IGS812 No POE
		BEGIN
			IF (@cnt <= 5)  -- 5 Ring
			BEGIN
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,7, @cnt, 4,@ena,'') -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)
			END
			
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,2, @cnt, 5,@ena,'') -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		END	
			
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)
		
		SET @cnt = @cnt + 1
	END
END

----- EMS 2.77_01, modify table 'alarmTemplate', change max ring number from 10 to 5
----- DEVICE_IGS1604 (76)
SET @dvc = 76
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 1, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 2, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,4, 1, 4,@ena,'') -- ALARM_FAULT_ON(4), SEVERITY_MINOR(4)    
    
	WHILE (@cnt <= 16) -- 16 UTP, IGS1604 No POE
	BEGIN
		IF (@cnt <= 5) -- 5 Ring
		BEGIN
			IF (@cnt <= 4)  -- 4 FIBER
			BEGIN
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
			END	
			
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,7, @cnt, 4,@ena,'') -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)        
		END	
			
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2, @cnt, 5,@ena,'') -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		
		SET @cnt = @cnt + 1
	END
END

----- DEVICE_IGS404(77)
SET @dvc = 77
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 1, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 2, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,4, 1, 4,@ena,'') -- ALARM_FAULT_ON(4), SEVERITY_MINOR(4)    
    
	WHILE (@cnt <= 4) -- 4 UTP
	BEGIN		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)        
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,5,  @cnt, 3,@ena,'')    -- ALARM_POEBUDGET_EXCEED(5), SEVERITY_MAJOR(3)        
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,6,  @cnt, 3,@ena,'')    -- ALARM_POEPD_OVERLOAD(6), SEVERITY_MAJOR(3)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,7,  @cnt, 4,@ena,'')    -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)        
		
		SET @cnt = @cnt + 1
	END
END

	
----- DEVICE_MSW202(48)
SET @dvc = 48
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 3) -- 3 UTP
	BEGIN
		IF (@cnt <= 2)  -- 2 FIBER, 2 Ring
		BEGIN
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,7,  @cnt, 4,@ena,'')    -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)
		END	
			
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2, @cnt, 5,@ena,'') -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		
		SET @cnt = @cnt + 1
	END	
END


----- DEVICE_MX210(49)
SET @dvc = 49
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 3) -- 3 FIBER
	BEGIN
		IF (@cnt <= 2)  -- 2 UTP, 2 Ring
		BEGIN
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,2, @cnt, 5,@ena,'') -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,7, @cnt, 4,@ena,'') -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)
		END	
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END	
END
GO

DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0710), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm

----- DEVICE_FRM220_1000EAS(47)
SET @dvc = 47
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 2) -- 2 FIBER, 2 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END	
END


----- DEVICE_FRM220A(41)
SET @dvc = 41
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 4) -- 4 FIBER, 4 UTP
	BEGIN
		IF (@cnt <= 2)  -- 2 Power, 2 Fan, 2 Alarm
		BEGIN
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,1,  @cnt, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,8,  @cnt, 4,@ena,'') -- ALARM_FAN_OFF(8), SEVERITY_MINOR(4)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,9,  @cnt, 4,@ena,'') -- ALARM_ALARM_ON(9), SEVERITY_MINOR(4)
		END
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'') -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'') -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		SET @cnt = @cnt + 1
	END	
END

	
----- CARD_NMC(1001)
SET @dvc = 1001
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 2) -- 2 Power, 2 Fan, 2 Alarm
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,1,  @cnt, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,8,  @cnt, 4,@ena,'') -- ALARM_FAN_OFF(8), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,9,  @cnt, 4,@ena,'') -- ALARM_ALARM_ON(9), SEVERITY_MINOR(4)
		
		SET @cnt = @cnt + 1
	END		
END


----- EMS 2.88_01, add new alarm template NMC-R4
----- CARD_NMC_R4(1048)
SET @dvc = 1048
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,47, @cnt, 3,@ena,'')    -- ALARM_ALL_SLOTS_LINK_DOWN(47), SEVERITY_MAJOR(3)
	    
	WHILE (@cnt <= 4) -- 4 Fan
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,8,  @cnt, 4,@ena,'') -- ALARM_FAN_OFF(8), SEVERITY_MINOR(4)
		
		IF (@cnt <= 2) -- 2 Power, 2 Alarm, 2 Fiber, 2 UTP
		BEGIN
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,1,  @cnt, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,9,  @cnt, 4,@ena,'') -- ALARM_ALARM_ON(9), SEVERITY_MINOR(4)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		END
		
		SET @cnt = @cnt + 1
	END		
END


----- CARD_1000EASX(1002)
SET @dvc = 1002
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 2) -- 2 FIBER, 2 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		
END


----- CARD_1000EAS(1003)
SET @dvc = 1003
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 2) -- 2 FIBER, 2 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		
END

    
----- CARD_1000EAS_2F(1004)
SET @dvc = 1004
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 2) -- 2 FIBER, 0 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		    
END

    
----- CARD_1000EA_2F(1005)
SET @dvc = 1005
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 2) -- 2 FIBER, 0 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		        
END

    
----- CARD_1000EAS_1(1006)
SET @dvc = 1006
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
END


----- CARD_1000EA_1(1007)
SET @dvc = 1007
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
END
GO

DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0710), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm

----- CARD_2R4G_2S(1008)
SET @dvc = 1008
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 2) -- 2 FIBER, 0 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,15, @cnt, 5,@ena,'')    -- ALARM_FIBER_TX_FAIL(15), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		
END

    
----- CARD_2R4G_3S(1009)
SET @dvc = 1009
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 3) -- 3 FIBER, 0 UTP
	BEGIN
		IF(@cnt<=2)
		BEGIN
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')  -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		END
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,15, @cnt, 5,@ena,'')    -- ALARM_FIBER_TX_FAIL(15), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		    
END

    
----- CARD_3R27G_2S(1010)
SET @dvc = 1010
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 2) -- 2 FIBER, 0 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,15, @cnt, 5,@ena,'')    -- ALARM_FIBER_TX_FAIL(15), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		    
END

    
----- CARD_3R27G_3S(1011)
SET @dvc = 1011
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 3) -- 3 FIBER, 0 UTP
	BEGIN
		IF(@cnt<=2)
		BEGIN
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')  -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		END
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,15, @cnt, 5,@ena,'')    -- ALARM_FIBER_TX_FAIL(15), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		    
END

    
----- CARD_3R10G_SS(1012)
SET @dvc = 1012
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,18, @cnt, 3,@ena,'') -- ALARM_CARD_ERROR(18), SEVERITY_MAJOR(3)
		
	WHILE (@cnt <= 2) -- 2 FIBER, 0 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,15, @cnt, 5,@ena,'')    -- ALARM_FIBER_TX_FAIL(15), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		    
END

    
----- CARD_10G_SX(1013)
SET @dvc = 1013
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,18, @cnt, 3,@ena,'') -- ALARM_CARD_ERROR(18), SEVERITY_MAJOR(3)
		
	WHILE (@cnt <= 2) -- 2 FIBER, 0 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		        
END


----- CARD_10G_XX(1014)
SET @dvc = 1014
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,18, @cnt, 3,@ena,'') -- ALARM_CARD_ERROR(18), SEVERITY_MAJOR(3)
		
	WHILE (@cnt <= 2) -- 2 FIBER, 0 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		            
END

	
----- CARD_10G_SXX(1015)
SET @dvc = 1015
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,18, @cnt, 3,@ena,'') -- ALARM_CARD_ERROR(18), SEVERITY_MAJOR(3)
		
	WHILE (@cnt <= 3) -- 3 FIBER, 0 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		-- CHT only, must be filtered out in GUI.
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,16, @cnt, 7,@ena,'') -- ALARM_FIBER_TX_BERT_TEST(16), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,17, @cnt, 7,@ena,'') -- ALARM_FIBER_RX_BERT_TEST(17), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,19, @cnt, 3,@ena,'') -- ALARM_FIBER_WAVELENGTH_ABNORMAL(19), SEVERITY_MAJOR(3)	
		
		SET @cnt = @cnt + 1
	END		            	
END

----- EMS 2.82_01, add new alarm template for NMC line card 16G-3R
----- CARD_16G_3R(1047)
SET @dvc = 1047
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
    WHILE (@cnt <= 4) -- 4 FIBER, 0 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,15, @cnt, 5,@ena,'')    -- ALARM_FIBER_TX_FAIL(15), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		            	
END

----- EMS 2.88_01, add new alarm template for NMC-R4 line card 12G-3R
----- CARD_12G_3R(1049)
SET @dvc = 1049
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
    WHILE (@cnt <= 4) -- 4 FIBER, 0 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,43, @cnt, 5,@ena,'72')  -- ALARM_FIBER_CV_Abnormal(43), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,44, @cnt, 5,@ena,'72')  -- ALARM_FIBER_ES_Abnormal(44), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,45, @cnt, 5,@ena,'2')   -- ALARM_FIBER_SES_Abnormal(45), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,46, @cnt, 5,@ena,'10')  -- ALARM_FIBER_UAS_Abnormal(46), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,15, @cnt, 5,@ena,'')    -- ALARM_FIBER_TX_FAIL(15), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,26, @cnt, 5,@ena,'')    -- ALARM_FIBER_HAS_NO_OPTICAL_SIGNAL(26), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		            	
END

SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc AND type=3) = 0)
BEGIN    
    WHILE (@cnt <= 4) -- 4 FIBER, 0 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		SET @cnt = @cnt + 1
	END		            	
END

----- EMS 2.88_01, add new alarm template for NMC-R4 line card Protection
----- CARD_Protection(1050)
SET @dvc = 1050
SET @cnt = 1

DELETE FROM alarmTemplate WHERE id=@dvc AND type IN (50,51,52) -- ALARM_WORKPATH_PRI_SIGLOSS(50),ALARM_WORKPATH_SEC_SIGLOSS(51),ALARM_BOTH_CHAN_SIGLOSS(52)

IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc AND type IN (18)) = 0)
BEGIN    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,18, @cnt, 3,@ena,'')  -- ALARM_CARD_ERROR(18), SEVERITY_MAJOR(3)
END

IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc AND type IN (53,54,55)) = 0)
BEGIN    
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,53, @cnt, 3,@ena,'')  -- ALARM_WORKPATH_SIGLOSS(53), SEVERITY_MAJOR(3)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,54, @cnt, 5,@ena,'')  -- ALARM_PRI_CHAN_SIGLOSS(54), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,55, @cnt, 5,@ena,'')  -- ALARM_SEC_CHAN_SIGLOSS(55), SEVERITY_WARNING(5)			            	
END


----- CARD_1000DS(1016)
SET @dvc = 1016
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 2) -- 2 FIBER, 0 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,15, @cnt, 5,@ena,'')    -- ALARM_FIBER_TX_FAIL(15), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		        
END
GO
    
DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0710), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm    
    
----- CARD_100M(1017)
----- CARD_100MS(1018)
----- CARD_1000M(1019)
----- CARD_1000MS(1020)
----- CARD_IMC_100M(1021)
----- CARD_IMC_100MS(1022)
----- CARD_IMC_1000M(1023)
----- CARD_IMC_1000MS(1024)
SET @dvc = 1017
SET @cnt = 1    
WHILE (@dvc <= 1024)
BEGIN
	IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
	
		IF(@dvc >= 1021) -- IMC only
		BEGIN
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 1, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 2, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)    
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,4, 1, 4,@ena,'') -- ALARM_FAULT_ON(4), SEVERITY_MINOR(4)
		END
	END	
	
	SET @dvc = @dvc + 1
END
    
    
----- CARD_MSW202(1025)
SET @dvc = 1025
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 2) -- 2 FIBER, 2 UTP, 2 Ring
	BEGIN			
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,7,  @cnt, 4,@ena,'')    -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)
		
		SET @cnt = @cnt + 1
	END	        
END

        
----- CARD_MX210(1026)
SET @dvc = 1026
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 3) -- 3 FIBER
	BEGIN
		IF (@cnt <= 2)  -- 2 Ring
		BEGIN
			IF (@cnt <= 1)  -- 1 UTP
			BEGIN
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,2, @cnt, 5,@ena,'') -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
			END
		
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,7, @cnt, 4,@ena,'') -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)
		END	
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END	            
END
GO

----- EMS 2.99_01, add new alarm template for NMC-R3 line card FMC1000MS
DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0710), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm    
    
----- CARD_FMC1000MS(1054)
SET @dvc = 1054
SET @cnt = 1    

IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)
END
GO

DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0710), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm    

----- CARD_1000EASX_1(1027)
SET @dvc = 1027
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)
END

----- EMS 2.79_01, add new alarm template for NMC line card 1000EAS/X-2F and 100AS-1
----- CARD_100AS_1(1045)
SET @dvc = 1045
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)
END

----- CARD_1000EASX_2F(1046)
SET @dvc = 1046
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 2) -- 2 FIBER, no UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		
END

----- CARD_100I(1028)
SET @dvc = 1028
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN   
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,20, @cnt, 4,@ena,'')    -- ALARM_FIBER_FEF_ON(20), SEVERITY_MINOR(4) 
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)
END

----- CARD_FMC_100I(1029)
SET @dvc = 1029
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN   
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,20, @cnt, 4,@ena,'')    -- ALARM_FIBER_FEF_ON(20), SEVERITY_MINOR(4) 
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)
END

GO

----- EMS 2.72_01, add procedure 'getTemplateAlarms'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getTemplateAlarms]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getTemplateAlarms]
GO

CREATE PROCEDURE [dbo].[getTemplateAlarms]
	@id		int,
	@side	int

AS	
	SELECT * FROM alarmTemplate WHERE id = @id AND side = @side

GO

----- EMS 2.72_01, add procedure 'editTemplateAlarm'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[editTemplateAlarm]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[editTemplateAlarm]
GO

CREATE PROCEDURE [dbo].[editTemplateAlarm]
    @id			int,
    @side		tinyint,
    @type		smallint,
    @idx		tinyint,
    @param		varchar(10), 
    @severity	tinyint,
    @enable		bit
AS
	UPDATE alarmTemplate 
		SET severity=@severity,
			param=@param,
		    enable=@enable 
		WHERE id=@id AND side=@side AND type=@type AND idx=@idx  
GO




----- EMS 2.73_01, add new alarm template FMUX160, FMUX80, FMUX1600, FMUX800
DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0807), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm
    
----- DEVICE_FMUX160(34)
----- DEVICE_FMUX80(35)
----- DEVICE_FMUX1600(36)
----- DEVICE_FMUX800(37)
	SET @dvc = 34
	WHILE (@dvc <= 37)
	BEGIN
		IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
		BEGIN
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,1,  1, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,1,  2, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,25, 1, 4,@ena,'') -- ALARM_FIBER_BIT_ERROR(25), SEVERITY_MINOR(4)
			
			DECLARE @e1Num INT
			
			IF @dvc IN (34, 36)
				SET @e1Num = 16
			
			IF @dvc IN (35, 37)
				SET @e1Num = 8
			
			SET @cnt = 1
			WHILE (@cnt <= @e1Num) -- 8/16 E1
			BEGIN
				IF (@cnt <= 4)  -- 4 UTP
				BEGIN
					IF (@cnt <= 2)  -- 2 FIBER
					BEGIN
						INSERT INTO alarmTemplate VALUES(@dvc,@sid,15, @cnt, 3,@ena,'')    -- ALARM_FIBER_TX_FAIL(15), SEVERITY_MAJOR(3)
						INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
						INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
						INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
						INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
						INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)							
					END
				
					INSERT INTO alarmTemplate VALUES(@dvc,@sid,2, @cnt, 5,@ena,'') -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
				END	
				
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,21, @cnt, 5,@ena,'') -- ALARM_E1Chan_RX_LOSS(21), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,22, @cnt, 4,@ena,'') -- ALARM_E1Chan_AIS_ON(22), SEVERITY_MINOR(4)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,23, @cnt, 3,@ena,'') -- ALARM_E1Chan_TX_FAIL(23), SEVERITY_MAJOR(3)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,24, @cnt, 7,@ena,'') -- ALARM_E1Chan_LOOPBACK_TEST(24), SEVERITY_TESTING(7)	
				
				SET @cnt = @cnt + 1
			END	
		END
		
		SET @dvc = @dvc + 1
	END
	
GO	


----- EMS 2.74_01, add procedure 'addPmParameterLog'
----- EMS 2.88_01, modify procedure 'addPmParameterLog', add 'errCode' and 'dataType'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[addPmParameterLog]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[addPmParameterLog]
GO

CREATE PROCEDURE [dbo].[addPmParameterLog]
    @agent_id int,
    @time     datetime, 
	@data     varbinary(MAX),
	@eCode tinyint,
	@dType tinyint
AS 
	INSERT INTO pmParameterLog(agent_id, time, data, type, errCode) 
		VALUES(@agent_id, @time, @data, @dType, @eCode)

	IF @@error<>0 
		GOTO ERR

	RETURN 0

ERR:
RETURN -1

GO

----- EMS 2.88_01, add procedure 'editPmParameterLog'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[editPmParameterLog]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[editPmParameterLog]
GO

CREATE PROCEDURE [dbo].[editPmParameterLog]
    @agent_id int,
    @time     datetime, 
	@data     varbinary(MAX)
AS 
	UPDATE pmParameterLog SET data=@data 
	WHERE agent_id=@agent_id AND time=@time 

	IF @@error<>0 
		GOTO ERR

	RETURN 0

ERR:
RETURN -1

GO


----- EMS 2.74_01, add procedure 'getPmParameterLog'
----- EMS 2.88_01, modify procedure 'getPmParameterLog', add 'errCode' and 'dataType'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getPmParameterLog]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getPmParameterLog]
GO

CREATE PROCEDURE [dbo].[getPmParameterLog]
    @agent_id  int,
    @timeBegin datetime,
    @timeEnd   datetime
	
AS 
	SELECT agent_id, time=CONVERT(varchar, time, 120), data, type, errCode FROM pmParameterLog 
		WHERE agent_id=@agent_id AND time>=@timeBegin AND time<=@timeEnd

GO


----- EMS 2.74_01, add procedure 'deletePmParameterLog'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[deletePmParameterLog]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[deletePmParameterLog]
GO
CREATE PROCEDURE [dbo].[deletePmParameterLog]
	@agent_id int

AS
	DELETE FROM pmParameterLog WHERE agent_id=@agent_id

GO	


----- EMS 2.74_02, add procedure 'deletePmParameterLogbyTime'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[deletePmParameterLogbyTime]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[deletePmParameterLogbyTime]
GO
CREATE PROCEDURE [dbo].[deletePmParameterLogByTime]
	@time datetime

AS
	DECLARE @id int

	DECLARE cur CURSOR FOR (SELECT id FROM agent)
	OPEN cur

	FETCH NEXT FROM cur INTO @id
	WHILE @@FETCH_STATUS = 0
	BEGIN
		DELETE FROM pmParameterLog WHERE agent_id=@id AND time<@time
		
		FETCH NEXT FROM cur INTO @id
	END

	CLOSE cur
	DEALLOCATE cur
GO


----- EMS 2.74_01, add procedure 'editAgentPmEnable'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[editAgentPmEnable]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[editAgentPmEnable]
GO

CREATE PROCEDURE [dbo].[editAgentPmEnable] 
	@id     int,
	@enable bit
	
AS

	UPDATE agent
		SET pm_enable=@enable WHERE id=@id

GO

----- EMS 2.75_01, add new alarm template iMUX4T/S, iMUX5T/S, iMUX8T/S, iMUX16T/S
DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0807), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm
    
----- CARD_4E1ET100T(1030)
----- CARD_4E1ET100S(1031)
----- CARD_5E1ET100T(1032)
----- CARD_5E1ET100S(1033)
	SET @dvc = 1030
	WHILE (@dvc <= 1033)
	BEGIN
		IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
		BEGIN
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, 1, 3,@ena,'') -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
			
			IF @dvc IN (1030, 1032) -- UTP
			BEGIN
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  1, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
			END
			
			IF @dvc IN (1031, 1033) -- FIBER
			BEGIN
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  1, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,26, 1, 5,@ena,'')    -- ALARM_FIBER_PORT_HAS_NO_OPTICAL_SIGNAL(26), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, 1, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, 1, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, 1, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)		
			END
			
			SET @cnt = 1
			DECLARE @e1Num INT
			
			IF @dvc IN (1030, 1031)
				SET @e1Num = 4
			
			IF @dvc IN (1032, 1033)
				SET @e1Num = 5
			
			WHILE (@cnt <= @e1Num)
			BEGIN
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,34, @cnt, 7,@ena,'') -- ALARM_E1_LOOPBACK_TEST(34), SEVERITY_TESTING(7)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,35, @cnt, 7,@ena,'') -- ALARM_E1_BERT_TEST(35), SEVERITY_TESTING(7)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,36, @cnt, 7,@ena,'') -- ALARM_E1_BERT_TEST_HAS_ERROR(36), SEVERITY_TESTING(7)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,32, @cnt, 4,@ena,'') -- ALARM_E1_SIGNAL_LOSS(32), SEVERITY_MINOR(4)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,33, @cnt, 4,@ena,'') -- ALARM_E1_SYNC_LOSS(33), SEVERITY_MINOR(4)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,28, @cnt, 5,@ena,'') -- ALARM_E1_AIS_ON(28), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,29, @cnt, 5,@ena,'') -- ALARM_E1_RAI_ON(29), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,30, @cnt, 5,@ena,'') -- ALARM_E1_LOMF_ON(30), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,31, @cnt, 5,@ena,'') -- ALARM_E1_DEFECTED(31), SEVERITY_WARNING(5)
			
				SET @cnt = @cnt + 1
			END
		END
		
		SET @dvc = @dvc + 1
	END
	
GO

DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0807), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm
    
----- CARD_8E1ET100T(1034)
----- CARD_8E1ET100S(1035)
	SET @dvc = 1034
	WHILE (@dvc <= 1035)
	BEGIN
		IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
		BEGIN
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, 1, 3,@ena,'') -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
			
			IF @dvc = 1034 -- UTP
			BEGIN
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  1, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
			END
			
			IF @dvc = 1035 -- FIBER
			BEGIN
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  1, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,26, 1, 5,@ena,'')    -- ALARM_FIBER_PORT_HAS_NO_OPTICAL_SIGNAL(26), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, 1, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, 1, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, 1, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)		
			END
			
			SET @cnt = 1
			DECLARE @e1Num INT
			SET @e1Num = 8
			
			WHILE (@cnt <= @e1Num)
			BEGIN
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,34, @cnt, 7,@ena,'') -- ALARM_E1_LOOPBACK_TEST(34), SEVERITY_TESTING(7)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,35, @cnt, 7,@ena,'') -- ALARM_E1_BERT_TEST(35), SEVERITY_TESTING(7)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,36, @cnt, 7,@ena,'') -- ALARM_E1_BERT_TEST_HAS_ERROR(36), SEVERITY_TESTING(7)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,32, @cnt, 4,@ena,'') -- ALARM_E1_SIGNAL_LOSS(32), SEVERITY_MINOR(4)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,33, @cnt, 4,@ena,'') -- ALARM_E1_SYNC_LOSS(33), SEVERITY_MINOR(4)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,28, @cnt, 5,@ena,'') -- ALARM_E1_AIS_ON(28), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,29, @cnt, 5,@ena,'') -- ALARM_E1_RAI_ON(29), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,30, @cnt, 5,@ena,'') -- ALARM_E1_LOMF_ON(30), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,31, @cnt, 5,@ena,'') -- ALARM_E1_DEFECTED(31), SEVERITY_WARNING(5)
			
				SET @cnt = @cnt + 1
			END
		END
		
		SET @dvc = @dvc + 1
	END
	
GO

DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0807), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm
    
----- CARD_16E1ET100T(1036)
----- CARD_16E1ET100S(1037)
	SET @dvc = 1036
	WHILE (@dvc <= 1037)
	BEGIN
		IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
		BEGIN
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, 1, 3,@ena,'') -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
			
			IF @dvc = 1036 -- UTP
			BEGIN
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  1, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
			END
			
			IF @dvc = 1037 -- FIBER
			BEGIN
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  1, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,26, 1, 5,@ena,'')    -- ALARM_FIBER_PORT_HAS_NO_OPTICAL_SIGNAL(26), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, 1, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, 1, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, 1, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)		
			END
			
			SET @cnt = 1
			DECLARE @e1Num INT
			SET @e1Num = 16
			
			WHILE (@cnt <= @e1Num)
			BEGIN
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,34, @cnt, 7,@ena,'') -- ALARM_E1_LOOPBACK_TEST(34), SEVERITY_TESTING(7)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,35, @cnt, 7,@ena,'') -- ALARM_E1_BERT_TEST(35), SEVERITY_TESTING(7)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,36, @cnt, 7,@ena,'') -- ALARM_E1_BERT_TEST_HAS_ERROR(36), SEVERITY_TESTING(7)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,32, @cnt, 4,@ena,'') -- ALARM_E1_SIGNAL_LOSS(32), SEVERITY_MINOR(4)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,33, @cnt, 4,@ena,'') -- ALARM_E1_SYNC_LOSS(33), SEVERITY_MINOR(4)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,28, @cnt, 5,@ena,'') -- ALARM_E1_AIS_ON(28), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,29, @cnt, 5,@ena,'') -- ALARM_E1_RAI_ON(29), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,30, @cnt, 5,@ena,'') -- ALARM_E1_LOMF_ON(30), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,31, @cnt, 5,@ena,'') -- ALARM_E1_DEFECTED(31), SEVERITY_WARNING(5)
			
				SET @cnt = @cnt + 1
			END
		END
		
		SET @dvc = @dvc + 1
	END
	
GO

----- EMS 2.75_01, add new alarm template 1000T(S)
DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0807), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm
    
----- CARD_1000T(1038)
SET @dvc = 1038
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
END

----- CARD_1000TS(1039)
SET @dvc = 1039
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)
END

GO

----- EMS 2.75_01, add new alarm template FTEC
DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- model Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0925), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm
    
----- MODEL_FTEC(1040)
	SET @dvc = 1040
	IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,32, 1, 4,@ena,'') -- ALARM_E1_SIGNAL_LOSS(32), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,33, 1, 4,@ena,'') -- ALARM_E1_SYNC_LOSS(33), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,27, 1, 5,@ena,'') -- ALARM_E1_ALARM_ON(27), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,28, 1, 5,@ena,'') -- ALARM_E1_AIS_ON(28), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,34, 1, 7,@ena,'') -- ALARM_E1_LOOPBACK_TEST(34), SEVERITY_TESTING(7)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,37, 1, 4,@ena,'') -- ALARM_T1_SIGNAL_LOSS(37), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,38, 1, 4,@ena,'') -- ALARM_T1_SYNC_LOSS(38), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,39, 1, 5,@ena,'') -- ALARM_T1_ALARM_ON(39), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,40, 1, 5,@ena,'') -- ALARM_T1_AIS_ON(40), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,41, 1, 7,@ena,'') -- ALARM_T1_LOOPBACK_TEST(41), SEVERITY_TESTING(7)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,42, 1, 7,@ena,'') -- ALARM_FRONT_LOOPBACK_TEST(42), SEVERITY_TESTING(7)	
	END
GO

----- EMS 2.75_01, add new alarm template FXOFXS
----- EMS 2.75_01, add new alarm template FXOFXS4
DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- model Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0925), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm
    
----- MODEL_FXOFXS(1041)
----- MODEL_FXOFXS4(1042)
SET @dvc = 1041
	
WHILE (@dvc <= 1042)
BEGIN
	IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  1, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,20, 1, 4,@ena,'')    -- ALARM_FIBER_FEF_ON(20), SEVERITY_MINOR(4)
		
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, 1, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, 1, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, 1, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)
	END
	
	SET @dvc = @dvc + 1
END
GO

----- EMS 2.75_01, add new alarm templates for FRM220A-1000EAS/X, FRM220A-1000EAS/X-1, FRM220-100AS-1, FRM220-1000EAS/X-2F
DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- model Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0925), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm

----- DEVICE_FRM220A_1000EASX(42)
SET @dvc = 42
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 2) -- 2 FIBER, 2 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,20, @cnt, 4,@ena,'')    -- ALARM_FIBER_FEF_ON(20), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
						
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		        
END

----- DEVICE_FRM220A_1000EASX1(45)
SET @dvc = 45
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,20, @cnt, 4,@ena,'')    -- ALARM_FIBER_FEF_ON(20), SEVERITY_MINOR(4)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
						
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)		        
END

----- DEVICE_FRM220_100AS1(80)
SET @dvc = 80
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,20, @cnt, 4,@ena,'')    -- ALARM_FIBER_FEF_ON(20), SEVERITY_MINOR(4)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
						
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)		        
END

----- DEVICE_FRM220_1000EASX2F(81)
SET @dvc = 81
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 2) -- 2 FIBER, 0 UTP
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, @cnt, 3,@ena,'')    -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,20, @cnt, 4,@ena,'')    -- ALARM_FIBER_FEF_ON(20), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, @cnt, 7,@ena,'')    -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)
						
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END		        
END

GO

----- EMS 2.75_01, add new alarm template GFOM04
DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- model Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0925), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm

----- MODEL_GFOM04(1043)
SET @dvc = 1043
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,10, 1, 3,@ena,'') -- ALARM_REMOTE_POWER_OFF(10), SEVERITY_MAJOR(3)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,20, 1, 4,@ena,'') -- ALARM_FIBER_FEF_ON(20), SEVERITY_MINOR(4)	
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,25, 1, 4,@ena,'') -- ALARM_FIBER_BIT_ERROR(25), SEVERITY_MINOR(4)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,11, 1, 7,@ena,'') -- ALARM_FIBER_LOOPBACK_TEST(11), SEVERITY_TESTING(7)			
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  1, 5,@ena,'') -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
			
	DECLARE @e1Num INT
	SET @e1Num = 4
			
	SET @cnt = 1
	WHILE (@cnt <= @e1Num) -- 4 E1/T1
	BEGIN
		IF (@cnt <= 2)  -- 2 FIBER
		BEGIN
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,15, @cnt, 3,@ena,'')    -- ALARM_FIBER_TX_FAIL(15), SEVERITY_MAJOR(3)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)							
		END
				
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,21, @cnt, 5,@ena,'') -- ALARM_E1Chan_RX_LOSS(21), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,22, @cnt, 4,@ena,'') -- ALARM_E1Chan_AIS_ON(22), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,23, @cnt, 3,@ena,'') -- ALARM_E1Chan_TX_FAIL(23), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,24, @cnt, 7,@ena,'') -- ALARM_E1Chan_LOOPBACK_TEST(24), SEVERITY_TESTING(7)	
				
		SET @cnt = @cnt + 1
	END	
END

GO

----- EMS 2.75_01, add new alarm template IPS-803
DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0807), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm
    
----- DEVICE_IPS803(78)
SET @dvc = 78
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 1, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 2, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 3, 4,@ena,'') -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)    
    INSERT INTO alarmTemplate VALUES(@dvc,@sid,4, 1, 4,@ena,'') -- ALARM_FAULT_ON(4), SEVERITY_MINOR(4)    
    
	WHILE (@cnt <= 8) -- 8 UTP
	BEGIN		
		IF (@cnt <= 5) -- 5 Ring
		BEGIN
			IF (@cnt <= 3)  -- 3 FIBER
			BEGIN
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)        
			END
		
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,7, @cnt, 4,@ena,'') -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)        
		END	
			
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2, @cnt, 5,@ena,'') -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)        
		
		SET @cnt = @cnt + 1
	END
END

GO


DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0807), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm
    
----- EMS 2.90_01, add new alarm template MSW404
----- DEVICE_MSW404(84)
SET @dvc = 84
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 4) -- 4 FIBER, 4 UTP, 4 Ring
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,7,  @cnt, 4,@ena,'')    -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)	
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		
		SET @cnt = @cnt + 1
	END	
END

----- EMS 2.90_01, add new alarm template MSW4424A
----- DEVICE_MSW4424A(85)
SET @dvc = 85
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	WHILE (@cnt <= 28) -- 28 FIBER, 0 UTP, no ring
	BEGIN
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
		INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)	
		
		SET @cnt = @cnt + 1
	END	
END

GO

DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0710), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm    

----- EMS 2.99_01, add new alarm template MSW4424C
----- DEVICE_MSW4424C(82)
SET @dvc = 82
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 1, 4,@ena,'')  -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4) 
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 2, 4,@ena,'')  -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,8, 1, 4,@ena,'')  -- ALARM_FAN_OFF(8), SEVERITY_MINOR(4)
		    
	WHILE (@cnt <= 29) -- 29 port
	BEGIN
		IF (@cnt <= 28)  -- 28 port
		BEGIN
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4) 
		END	

		INSERT INTO alarmTemplate VALUES(@dvc,@sid,49, @cnt, 5,@ena,'')  -- ALARM_PORT_LINK_DOWN(49), SEVERITY_WARNING(5)
		
		SET @cnt = @cnt + 1
	END	            
END
GO

DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0710), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm    

----- EMS 2.90_01, add new alarm template ICSG24S4X
----- DEVICE_ICSG24S4X(93)
SET @dvc = 93
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 1, 4,@ena,'')  -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4) 
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 2, 4,@ena,'')  -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,9, 1, 4,@ena,'')  -- ALARM_ALARM_ON(9), SEVERITY_MINOR(4)
		    
	WHILE (@cnt <= 29) -- 29 port
	BEGIN
		IF (@cnt <= 28)  -- 28 port
		BEGIN
			IF (@cnt <= 14)  -- 14 Ring
			BEGIN		
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,7, @cnt, 4,@ena,'') -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)
			END
						
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4) 
		END	

		INSERT INTO alarmTemplate VALUES(@dvc,@sid,49, @cnt, 5,@ena,'')  -- ALARM_PORT_LINK_DOWN(49), SEVERITY_WARNING(5)
		
		SET @cnt = @cnt + 1
	END	            
END
GO


DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0710), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm    

----- EMS 2.90_01, add new alarm template ICSG24S2X
----- DEVICE_ICSG24S2X(94)
SET @dvc = 94
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 1, 4,@ena,'')  -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4) 
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 2, 4,@ena,'')  -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,9, 1, 4,@ena,'')  -- ALARM_ALARM_ON(9), SEVERITY_MINOR(4)
		    
	WHILE (@cnt <= 27) -- 27 port
	BEGIN
		IF (@cnt <= 26)  -- 26 port
		BEGIN
			IF (@cnt <= 13)  -- 13 Ring
			BEGIN		
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,7, @cnt, 4,@ena,'') -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)
			END
						
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4) 
		END	

		INSERT INTO alarmTemplate VALUES(@dvc,@sid,49, @cnt, 5,@ena,'')  -- ALARM_PORT_LINK_DOWN(49), SEVERITY_WARNING(5)
		
		SET @cnt = @cnt + 1
	END	            
END
GO

DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0710), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm    

----- EMS 2.90_01, add new alarm template IGS-S2804TM
----- DEVICE_IGS-S2804TM(95)
SET @dvc = 95
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 1, 4,@ena,'')  -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4) 
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,1, 2, 4,@ena,'')  -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,9, 1, 4,@ena,'')  -- ALARM_ALARM_ON(9), SEVERITY_MINOR(4)
		    
	WHILE (@cnt <= 29) -- 29 port
	BEGIN
		IF (@cnt <= 28)  -- 28 port
		BEGIN
			IF (@cnt <= 14)  -- 14 Ring
			BEGIN		
				INSERT INTO alarmTemplate VALUES(@dvc,@sid,7, @cnt, 4,@ena,'') -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)
			END
						
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4) 
		END	

		INSERT INTO alarmTemplate VALUES(@dvc,@sid,49, @cnt, 5,@ena,'')  -- ALARM_PORT_LINK_DOWN(49), SEVERITY_WARNING(5)
		
		SET @cnt = @cnt + 1
	END	            
END

GO


DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0710), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm    

----- EMS 2.91_01, add new alarm template GSW3208M2
----- DEVICE_GSW3208M2(86)
SET @dvc = 86
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,9, 1, 4,@ena,'')  -- ALARM_ALARM_ON(9), SEVERITY_MINOR(4)
		    
	WHILE (@cnt <= 8) -- 8 utp
	BEGIN
		IF (@cnt <= 2)  -- 2 fiber 
		BEGIN
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4) 
		END	

		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		
		SET @cnt = @cnt + 1
	END	            
END

----- EMS 2.92_01, add new alarm template GSW1005MS
----- DEVICE_GSW1005MS(87)
SET @dvc = 87
SET @cnt = 1
IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
	WHILE (@cnt <= 5) -- 5 utp
	BEGIN
		IF (@cnt <= 1)  -- 1 fiber 
		BEGIN
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  @cnt, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, @cnt, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, @cnt, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
			INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, @cnt, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4) 
		END	

		INSERT INTO alarmTemplate VALUES(@dvc,@sid,2,  @cnt, 5,@ena,'')    -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
		
		SET @cnt = @cnt + 1
	END	            
END

GO


----- EMS 2.76_01, add procedure 'addImage'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[addImage]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[addImage]
GO

CREATE PROCEDURE [dbo].[addImage] 
	@name varchar(200),
	@size int,
	@date varchar(50),
	@data varbinary(MAX)

AS
	-- if the item existed, overwrite it.
	IF EXISTS(SELECT * FROM image WHERE name=@name)
		UPDATE image 
			SET size=@size, 
		        date=@date, 
		        data=@data 
			WHERE name=@name
	ELSE		                  
		INSERT INTO image(name, size, date, data) 
			VALUES(@name, @size, @date, @data)
GO


----- EMS 2.76_01, add procedure 'addTopologyDevice'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[addTopologyDevice]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[addTopologyDevice]
GO

CREATE PROCEDURE [dbo].[addTopologyDevice] 
	@tree_id  int,
	@node_id  int
	
AS
	-- create device for tree which existed before topology implement
	IF NOT EXISTS(SELECT * FROM topologyDevice WHERE tree_id=@tree_id) 
	BEGIN		
		-- add topology device
		DECLARE @child_id int
     
		DECLARE cur1 CURSOR FOR (SELECT child_id FROM treelinks WHERE tree_id=@tree_id) 
		OPEN cur1                                          
		FETCH NEXT FROM cur1 INTO @child_id
		WHILE @@FETCH_STATUS=0                          
		BEGIN
			IF EXISTS(SELECT * FROM agent WHERE id=@child_id)		
				INSERT INTO topologyDevice(tree_id, node_id, location_x, location_y, width, height) 
					VALUES(@tree_id, @child_id, 0, 0, 0, 0)			
				
			FETCH NEXT FROM cur1 INTO @child_id                  
		END
		CLOSE cur1                                          
		DEALLOCATE cur1    	
	END
	ELSE
		INSERT INTO topologyDevice(tree_id, node_id, location_x, location_y, width, height) 
			VALUES(@tree_id, @node_id, 0, 0, 0, 0)
GO


----- EMS 2.76_01, add procedure 'addTopologyDeviceLink'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[addTopologyDeviceLink]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[addTopologyDeviceLink]
GO

CREATE PROCEDURE [dbo].[addTopologyDeviceLink] 
	@tree_id     int,
	@node_id1    int,
	@interface1  varchar(50),
	@node_id2    int,
	@interface2  varchar(50)	
	
AS
	INSERT INTO topologyDeviceLink(tree_id, node_id1, interface1, node_id2, interface2) 
		VALUES(@tree_id, @node_id1, @interface1, @node_id2, @interface2)
GO


----- EMS 2.76_01, add procedure 'addTopologyEquip'
----- EMS 2.88_01, modify procedure 'addTopologyEquip', add write to clientActionLog
----- EMS 2.100_01, modify procedure 'addTopologyEquip', fix write to clientActionLog content length bug
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[addTopologyEquip]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[addTopologyEquip]
GO

CREATE PROCEDURE [dbo].[addTopologyEquip] 
	@tree_id    int,
	@node_id    int,
	@name       varchar(200),
	@location_x int,
	@location_y int,
	@time       datetime,
	@username   varchar(200)

AS	
	INSERT INTO topologyEquip(tree_id, node_id, name, location_x, location_y, width, height) 
			VALUES(@tree_id, @node_id, @name, @location_x, @location_y, 0, 0)
			
	-- write to clientActionLog
	DECLARE @clientId int, @content varchar(1000) 
	SET @clientId = (SELECT id FROM client WHERE name=@username) 
	
	-- code 9/11 for Parent/Tree
	SET @content = @name+',9:'+CAST(@node_id AS varchar)+',11:'+CAST(@tree_id AS varchar) 
	 
	INSERT INTO clientActionLog ([time], [client_id], [classify_id], [action_id], [content])
			VALUES (@time, @clientId, 4, 420, @content) 
GO


----- EMS 2.76_01, add procedure 'addTopologyEquipLink'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[addTopologyEquipLink]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[addTopologyEquipLink]
GO

CREATE PROCEDURE [dbo].[addTopologyEquipLink] 
	@tree_id     int,
	@node_id1    int,
	@interface1  varchar(50),
	@node_id2    int,
	@equip_name  varchar(200)	
	
AS
	INSERT INTO topologyEquipLink(tree_id, node_id1, interface1, node_id2, name2) 
		VALUES(@tree_id, @node_id1, @interface1, @node_id2, @equip_name)
GO


----- EMS 2.76_01, add procedure 'addTopologyLocation'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[addTopologyLocation]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[addTopologyLocation]
GO

CREATE PROCEDURE [dbo].[addTopologyLocation] 
	@tree_id  int,
	@node_id  int
	
AS
	-- create location for tree which existed before topology implement
	IF NOT EXISTS(SELECT * FROM topologyLocation WHERE tree_id=@tree_id) 
	BEGIN	
		DECLARE @child_id int
     
		DECLARE cur1 CURSOR FOR (SELECT child_id FROM treelinks WHERE tree_id=@tree_id) 
		OPEN cur1                                          
		FETCH NEXT FROM cur1 INTO @child_id
		WHILE @@FETCH_STATUS=0                          
		BEGIN
			IF NOT EXISTS(SELECT * FROM agent WHERE id=@child_id)		
				INSERT INTO topologyLocation(tree_id, node_id, image_name, scale, location_x, location_y, width, height) 
					VALUES(@tree_id, @child_id, NULL, 0, 0, 0, 0, 0)				
				
			FETCH NEXT FROM cur1 INTO @child_id                  
		END
		CLOSE cur1                                          
		DEALLOCATE cur1   	
	END
	ELSE
		INSERT INTO topologyLocation(tree_id, node_id, image_name, scale, location_x, location_y, width, height) 
			VALUES(@tree_id, @node_id, NULL, 0, 0, 0, 0, 0)
GO



----- EMS 2.76_01, add procedure 'deleteImage'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[deleteImage]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[deleteImage]
GO

CREATE PROCEDURE [dbo].[deleteImage]
	@name varchar(200)

AS
	DELETE FROM image WHERE name=@name
GO


----- EMS 2.76_01, add procedure 'deleteTopologyDeviceLink'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[deleteTopologyDeviceLink]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[deleteTopologyDeviceLink]
GO

CREATE PROCEDURE [dbo].[deleteTopologyDeviceLink]
	@tree_id     int,
	@node_id1    int,
	@interface1  varchar(50)	
	
AS
	IF @tree_id IS NULL
			-- delete links to the node in all trees
		DELETE FROM topologyDeviceLink WHERE node_id1=@node_id1 OR node_id2=@node_id1
	
	ELSE IF @interface1 IS NULL
		-- delete links belong to the node in the tree.
		DELETE FROM topologyDeviceLink 
			WHERE @tree_id=tree_id AND node_id1=@node_id1 OR node_id2=@node_id1
	
	ELSE
		-- delete the link to the node in the tree. 
		DELETE FROM topologyDeviceLink WHERE tree_id=@tree_id 
			AND (node_id1=@node_id1 AND interface1=@interface1) 
			OR  (node_id2=@node_id1 AND interface2=@interface1) 
GO



----- EMS 2.76_01, add procedure 'deleteTopologyEquip'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[deleteTopologyEquip]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[deleteTopologyEquip]
GO

CREATE PROCEDURE [dbo].[deleteTopologyEquip]
	@tree_id int,
	@node_id int,
	@name    varchar(200)
	
AS
	-- delete topology equip
	DELETE FROM topologyEquip 
		WHERE tree_id=@tree_id AND node_id=@node_id AND name=@name
		
	-- delete topology equip link
	DELETE FROM topologyEquipLink
		WHERE tree_id=@tree_id
		AND node_id2=@node_id
		AND name2=@name		
GO


----- EMS 2.76_01, add procedure 'deleteTopologyEquipLink'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[deleteTopologyEquipLink]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[deleteTopologyEquipLink]
GO

CREATE PROCEDURE [dbo].[deleteTopologyEquipLink]
	@tree_id     int,
	@node_id1    int,
	@interface1  varchar(50)
	
AS
	IF @tree_id IS NULL
		-- delete links to the node in all trees
		DELETE FROM topologyEquipLink WHERE node_id1=@node_id1

	ELSE IF @interface1 IS NULL
		-- delete links belong to the node in the tree.
		DELETE FROM topologyEquipLink 
			WHERE @tree_id=tree_id AND node_id1=@node_id1	
	
	ELSE
		-- delete the link to the node in the tree. 
		DELETE FROM topologyEquipLink WHERE tree_id=@tree_id 
			AND node_id1=@node_id1 AND interface1=@interface1
GO


----- EMS 2.76_01, modify procedure 'treeDelete', rename to 'deleteTree'
----- EMS 2.88_01, modify procedure 'deleteTree', add write to clientActionLog
----- EMS 2.200, modify procedure 'deleteTree', change @treeNodeName varchar 100 to varchar 768
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[treeDelete]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[treeDelete]
GO

IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[deleteTree]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[deleteTree]
GO

CREATE PROCEDURE [dbo].[deleteTree]
	@worker_name varchar(100),
	@tree_id     int,
	@time        datetime

AS
	DECLARE 
		@client_id  int, 	
		--@acl_client tinyint, 
		--@acl_node   tinyint,
		@tree_type  int,
		@r			int		--exec

	-- worker info
	--select @acl_client=acl,@client_id=id from client where name=@worker_name
	--select @acl_node=n.acl, @tree_type=t.type from nodes n,trees t 
	--where t.id=@tree_id and t.node_id=n.id 

	SELECT @client_id=id FROM client WHERE name=@worker_name
	SELECT @tree_type=t.type FROM nodes n, trees t 
		WHERE t.id=@tree_id and t.node_id=n.id 

	-- only acl<creator can modify the tree, except public tree type=1 
	--if @acl_client>@acl_node and @tree_type<>1 goto ERR1

	-- check tree is modified
	----- EMS 2.81_01, remove procedure 'treeIsModify'
	-- EXEC @r=treeIsModify @worker_name, @tree_id 
	-- IF @r=0 GOTO ERR1 

	-- check tree type, only creator can modify the private tree
	SELECT @tree_type=type FROM trees WHERE id=@tree_id
	
	IF @tree_type=0		-- private tree
	BEGIN
		IF NOT EXISTS(
			SELECT * FROM trees t, nodes n 
				WHERE t.id=@tree_id and type=0 and t.node_id=n.id and n.client_id=@client_id
			)
		GOTO ERR1  
	END

	-- prepare for clientActionLog
	DECLARE @treeNodeDbId int, @treeNodeName varchar(768) 
	SELECT @treeNodeDbId=node_id FROM trees WHERE id=@tree_id
	SELECT @treeNodeName=n.name FROM trees t, nodes n WHERE t.id=@tree_id AND t.node_id=n.id 
	
BEGIN TRAN

	-- delete treelinks
	DELETE FROM treelinks where tree_id=@tree_id	
	IF @@error<>0 GOTO ERR

	-- delete trees
	DELETE FROM trees WHERE @tree_id=id
	IF @@error<>0 GOTO ERR

	-- delete nodes
	DELETE FROM nodes 
		WHERE client_id=@client_id	
			AND NOT EXISTS(SELECT 1 FROM treelinks WHERE treelinks.child_id=nodes.id)
			AND NOT EXISTS(SELECT 1 FROM treelinks WHERE treelinks.parent_id=nodes.id)
	IF @@error<>0 GOTO ERR
	
	-- delete clientActionLog
	DELETE FROM clientActionLog 
	WHERE CHARINDEX('11:'+CAST(@tree_id AS varchar),content)>0  -- code Tree id=11
	OR CHARINDEX('1:'+CAST(@treeNodeDbId AS varchar),content)>0 -- code Node id=1
	OR CHARINDEX('3:['+CAST(@tree_id AS varchar)+' ',content)=1     -- code TopologyDeviceLink id=3
	OR CHARINDEX('4:['+CAST(@tree_id AS varchar)+' ',content)=1     -- code TopologyEquipLink id=4
		
	-- write to clientActionLog
	INSERT INTO clientActionLog ([time],[client_id],[classify_id],[action_id],[content])
	VALUES (@time, @client_id, 4, 403, @treeNodeName)

COMMIT TRAN

	SELECT id=0
	
	RETURN 0

ERR:
	ROLLBACK TRAN 
	
ERR1:
	SELECT id=-1
	
	RETURN -1
GO


----- EMS 2.76_01, add procedure 'editTopologyDevice'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[editTopologyDevice]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[editTopologyDevice]
GO

CREATE PROCEDURE [dbo].[editTopologyDevice] 
	@tree_id      int,
	@node_id      int,
	@location_x   smallint,
	@location_y   smallint,
	@width        tinyint, 
	@height       tinyint
	
AS
	UPDATE topologyDevice 
		SET location_x=@location_x,
		    location_y=@location_y,
		    width=@width,
		    height=@height
		WHERE tree_id=@tree_id AND node_id=@node_id	
GO


----- EMS 2.76_01, add procedure 'editTopologyEquip'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[editTopologyEquip]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[editTopologyEquip]
GO

CREATE PROCEDURE [dbo].[editTopologyEquip] 
	@tree_id      int,
	@node_id      int,
	@name         varchar(200),
	@location_x   smallint,
	@location_y   smallint,
	@width        tinyint, 
	@height       tinyint
	
AS
	UPDATE topologyEquip
		SET location_x=@location_x,
		    location_y=@location_y,
		    width=@width,
		    height=@height
		WHERE tree_id=@tree_id AND name=@name
GO


----- EMS 2.76_01, add procedure 'editTopologyLocation'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[editTopologyLocation]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[editTopologyLocation]
GO

CREATE PROCEDURE [dbo].[editTopologyLocation] 
	@tree_id      int,
	@node_id      int,	
	@image_name   varchar(200),
	@scale        smallint,
	@location_x   smallint,
	@location_y   smallint,
	@width        tinyint,
	@height       tinyint
	
AS
	-- image may be removed.
	IF NOT EXISTS (SELECT * FROM image WHERE name=@image_name)
		SET @image_name=NULL


	UPDATE topologyLocation 
		SET image_name=@image_name,
		    scale=@scale,
		    location_x=@location_x,
		    location_y=@location_y,
		    width=@width,
		    height=@height		
		WHERE tree_id=@tree_id AND node_id=@node_id	
GO


----- EMS 2.76_01, modify procedure 'nodeUpdate', rename to 'editTreeNode'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[nodeUpdate]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[nodeUpdate]
GO

IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[editTreeNode]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[editTreeNode]
GO

----- EMS 2.90_01, modify procedure 'editTreeNode', change name length 100 to 768. UI length 128, DB needs 768.
CREATE PROCEDURE [dbo].[editTreeNode]
	@worker_name varchar(50),
	@tree_id     int,
	@node_id     int,
	@name        varchar(768)


AS
DECLARE  
	@client_id      int,			-- modifier
--	@acl	        tinyint, 
--	@node_acl       tinyint,		-- creator
--	@node_client_id int,
	@r				int				-- exec

	--SELECT @client_id=id, @acl=acl FROM client 
	--WHERE name=@worker_name

	--SELECT @node_client_id=client_id, @node_acl=acl FROM nodes 
	--WHERE id=@node_id

	--IF @node_client_id IS NULL GOTO ERR1

	-- modifier and creator are same client, can do node modify 
	-- different client to compare acl if has right to modify node, need acl > creator acl
	--IF @client_id<>@node_client_id AND @acl<=@node_acl GOTO ERR1	

	-- check tree is modified
	----- EMS 2.81_01, remove procedure 'treeIsModify'
	-- EXEC @r=treeIsModify @worker_name, @tree_id 
	-- if @r=0 goto ERR
	
	UPDATE nodes SET name=@name WHERE id=@node_id
 
	SELECT id=0
	RETURN 0

ERR:
	SELECT id=-1
	RETURN -1
GO


----- EMS 2.76_01, add procedure 'getImage'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getImage]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getImage]
GO

CREATE PROCEDURE [dbo].[getImage] 
	@name varchar(200)

AS
	SELECT name, size, date=CONVERT(varchar, date, 120), data FROM image 
		WHERE name=@name
GO


----- EMS 2.76_01, add procedure 'getImageInfos'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getImageInfos]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getImageInfos]
GO

CREATE PROCEDURE [dbo].[getImageInfos] 
AS
	SELECT name, size, date=CONVERT(varchar, date, 120) FROM image 
GO


----- EMS 2.76_01, add procedure 'getTopologyDeviceLinks'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getTopologyDeviceLinks]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getTopologyDeviceLinks]
GO

CREATE PROCEDURE [dbo].[getTopologyDeviceLinks]
	@tree_id  int
	
AS
	SELECT * FROM TopologyDeviceLink WHERE tree_id=@tree_id
GO


----- EMS 2.76_01, add procedure 'getTopologyDevices'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getTopologyDevices]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getTopologyDevices]
GO

CREATE PROCEDURE [dbo].[getTopologyDevices]
	@tree_id  int

AS
	SELECT * FROM TopologyDevice WHERE tree_id=@tree_id
GO


----- EMS 2.76_01, add procedure 'getTopologyEquipLinks'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getTopologyEquipLinks]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getTopologyEquipLinks]
GO

CREATE PROCEDURE [dbo].[getTopologyEquipLinks]
	@tree_id  int
	
AS
	SELECT * FROM TopologyEquipLink WHERE tree_id=@tree_id
GO


----- EMS 2.76_01, add procedure 'getTopologyEquips'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getTopologyEquips]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getTopologyEquips]
GO

CREATE PROCEDURE [dbo].[getTopologyEquips]
	@tree_id  int
	
AS
	SELECT * FROM topologyEquip WHERE tree_id=@tree_id
GO


----- EMS 2.76_01, add procedure 'getTopologyLocation'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getTopologyLocation]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getTopologyLocation]
GO

CREATE PROCEDURE [dbo].[getTopologyLocation]
	@tree_id  int,
	@node_id  int
AS
	SELECT * FROM TopologyLocation WHERE tree_id=@tree_id AND node_id=@node_id
GO


----- EMS 2.76_01, add procedure 'getTopologyLocations'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getTopologyLocations]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getTopologyLocations]
GO

CREATE PROCEDURE [dbo].[getTopologyLocations]
	@tree_id  int
AS
	-- create location/device for tree which existed before topology implement
	IF NOT EXISTS(SELECT * FROM topologyLocation WHERE tree_id=@tree_id)
		EXEC addTopologyLocation @tree_id, -1

	IF NOT EXISTS(SELECT * FROM topologyDevice WHERE tree_id=@tree_id)		
		EXEC addTopologyDevice @tree_id, -1
	
	SELECT * FROM TopologyLocation WHERE tree_id=@tree_id
GO

----- EMS 2.76_01, add procedure 'getTreeNode'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getTreeNode]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getTreeNode]
GO

CREATE PROCEDURE [dbo].[getTreeNode]
	@tree_id  int,
	@node_id  int

AS
	SELECT * FROM treelinks t, nodes n 
	WHERE t.tree_id=@tree_id AND child_id=@node_id AND t.child_id=n.id
GO

----- EMS 2.76_01, modify procedure 'selectNodes', change column 'text' varchar 64 to 100
----- EMS 2.81_01, modify procedure 'selectNodes', add param '@userName' for role access check
----- EMS 2.88_01, modify procedure 'selectNodes', fix bug that loss Product Tree nodes
----- EMS 2.200, modify procedure 'selectNodes', change column 'text' varchar 100 to 768
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[selectNodes]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[selectNodes]
GO

CREATE PROCEDURE [dbo].[selectNodes]
	@tree_id int,
	@node_id int,
	@userName varchar(64)
AS

declare @c int,@lvl int

create table #a(
	parent_id int,
	child_id int,
	idx int,
	lvl int
)

create table #b(
	parent_id int,
	child_id int,
	idx int,
	lvl int
)

create table #c(
	parent_id int,
	child_id int,
	idx int,
	lvl int
)

insert #b select parent_id,child_id,idx,lvl from treelinks where tree_id=@tree_id and parent_id=@node_id
select @c=count(*) from #b
while @c>0 begin
	truncate table #c
	insert #c select t1.parent_id,t1.child_id,t1.idx,t1.lvl 
		from treelinks t1, #b t2
		where t1.tree_id=@tree_id and t1.parent_id=t2.child_id

	select @c=count(*) from #b

	insert #a select * from #b

	truncate table #b
	insert #b select * from #c
end

create table #n(id int, text varchar(768) NULL,type_id tinyint NULL)

insert #n(id) values(@node_id)
insert #n(id) select distinct child_id from #a

update #n set text=n.name, type_id=n.type_id from #n, nodes n where #n.id=n.id

select dBId=id, name=text, typeId=type_id from #n 

-- check role access
WHERE id IN (SELECT id FROM [dbo].[fn_getAllowedNodesByUserName](@userName))
OR id<1001 -- fix bug that loss Product Tree nodes

drop table #n
drop table #b
drop table #c
drop table #a
return 0
err:
return -1
GO

----- EMS 2.81_01, modify procedure 'selectNodeLinks', add param '@userName' for role access check
----- EMS 2.81_01, modify procedure 'selectNodeLinks', adjust tree structure before return
----- EMS 2.88_01, modify procedure 'selectNodeLinks', fix bug that in the same level index doesn't reset when different parent
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[selectNodeLinks]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[selectNodeLinks]
GO

CREATE   procedure [dbo].[selectNodeLinks]
	@tree_id int,
	@node_id int,
	@userName varchar(64)
	
/**
	return tree links from parent node @node_id
*/
as

declare @c int,@lvl int

create table #a(
	parent_id int,
	child_id int,
	idx int,
	lvl int
)

create table #b(
	parent_id int,
	child_id int,
	idx int,
	lvl int
)

create table #c(
	parent_id int,
	child_id int,
	idx int,
	lvl int
)

insert #b select parent_id,child_id,idx,lvl from treelinks where tree_id=@tree_id and parent_id=@node_id
select @c=count(*) from #b
while @c>0 begin
	truncate table #c
	insert #c select t1.parent_id,t1.child_id,t1.idx,t1.lvl 
		from treelinks t1, #b t2
		where t1.tree_id=@tree_id and t1.parent_id=t2.child_id

	select @c=count(*) from #b

	insert #a select * from #b

	truncate table #b
	insert #b select * from #c
end

-- need to adjust tree structure
-- select parentId=parent_id,childId=child_id,level=lvl,'index'=idx from #a order by parent_id,idx

IF OBJECT_ID(N'[tempdb].[dbo].[#tNodes]') IS NOT NULL
	DROP TABLE #tNodes

SELECT * INTO #tNodes FROM [dbo].[fn_getAllowedNodesByUserName](@userName)

IF OBJECT_ID(N'[tempdb].[dbo].[#tLink]') IS NOT NULL
	DROP TABLE #tLink
	
select parentId=parent_id, childId=child_id, level=lvl,'index'=idx 
INTO #tLink
from #a 
WHERE (parent_id<1001 OR parent_id IN (SELECT id FROM #tNodes)) -- -1 for root's parent, 1~1000 for product tree nodes
		AND (child_id<1001  OR child_id  IN (SELECT id FROM #tNodes)) -- 1~1000 for product tree nodes 
order by lvl,parent_id,idx -- EMS 2.88, firstly order by level


IF OBJECT_ID(N'[tempdb].[dbo].[#tAdjIdx]') IS NOT NULL
	DROP TABLE #tAdjIdx
	
CREATE TABLE #tAdjIdx (
	[parentId] int, [childId] int, [level] int, [index] int IDENTITY(0,1)
) 

DECLARE @pid int, @cid int, @lv int, @compareParent int  

-- EMS 2.88, fix index bug
SELECT TOP(1) @compareParent=parentId FROM #tLink 
	
DECLARE Cur CURSOR FOR
SELECT parentId, childId, level FROM #tLink
OPEN Cur
FETCH NEXT FROM Cur INTO @pid, @cid, @lv    
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
	IF @compareParent<>@pid 
		DBCC checkident (#tAdjIdx, reseed, -1) 
	
	INSERT INTO #tAdjIdx (parentId, childId, level) VALUES (@pid, @cid, @lv) 
	
	SET @compareParent=@pid 
	FETCH NEXT FROM Cur INTO @pid, @cid, @lv	
END
CLOSE Cur 
DEALLOCATE Cur  

SELECT * FROM #tAdjIdx ORDER BY [level],[parentId],[index]

drop table #b
drop table #c
drop table #a
DROP TABLE #tNodes
DROP TABLE #tLink
DROP TABLE #tAdjIdx 

return 0
err:
return -1
GO

----- EMS 2.76_01, delete procedure 'treeLinkInsert'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[treeLinkInsert]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[treeLinkInsert]
GO


----- EMS 2.77_01, delete rows of table 'alarmTemplate' and 'alarm' where ring idx>5 
----- EMS 2.90_01, ICSG24S4X(93) has 14 ring
----- EMS 2.90_01, ICSG24S2X(94) has 13 ring
----- EMS 2.90_01, IGS-S2804TM(95) has 14 ring
DELETE FROM alarmTemplate WHERE type=7 AND idx>5 AND id NOT IN (93,94,95)  
DELETE FROM alarm WHERE type=7 AND idx>5 AND model_id NOT IN (93,94,95)
GO 


----- EMS 2.81_01, modify table 'privilege', rename table to 'userRole'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[privilege]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    EXEC sp_rename 'privilege', 'userRole' 
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[PK_privilege]') AND OBJECTPROPERTY(id, N'IsPrimaryKey')=1)
BEGIN
    EXEC sp_rename 'PK_privilege', 'PK_userRole'
END
GO

----- EMS 2.81_01, modify table 'userRole', add column 'function'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[userRole]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    IF NOT EXISTS (SELECT * FROM syscolumns WHERE name='function' and id=OBJECT_ID('userRole'))
    BEGIN
        ALTER TABLE userRole ADD [function] varchar(10) 	
    END
END
GO

IF ((SELECT [function] FROM [dbo].[userRole] WHERE [id]=1) IS NULL)
BEGIN
    -- set default function bit for administrator/operator/user
	UPDATE [dbo].[userRole] SET [function]='1111' WHERE [id]<3
	UPDATE [dbo].[userRole] SET [function]='0000' WHERE [id]=3
END
GO

----- EMS 2.88_01, modify table 'userRole', add column 'radius_id'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[userRole]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    IF NOT EXISTS (SELECT * FROM syscolumns WHERE name='radius_id' and id=OBJECT_ID('userRole'))
    BEGIN
        ALTER TABLE userRole ADD [radius_id] INT NOT NULL DEFAULT '0'	
    END
END
GO

-- set default radius id
UPDATE [dbo].[userRole] SET [radius_id]=[id] WHERE [radius_id]=0
GO

----- EMS 2.97_01, modify table 'userRole', fix radius id bug
-- first time CD install EMSv290 0/0/0/1/2/3 -> EMSv294 1/2/3/1/2/3 -> EMSv297 1/2/3/4/5/6
DECLARE @id int, @radiusMaxId int
SET @id=1
SELECT @radiusMaxId = radius_id FROM userRole WHERE radius_id = (SELECT MAX(radius_id) FROM userRole) 

WHILE(@id<=3)  -- system default role 1/2/3
BEGIN
	SET @radiusMaxId = @radiusMaxId+1
	UPDATE userRole SET radius_id = @radiusMaxId WHERE radius_id = @id AND id <> radius_id
	
	SET @id = @id+1
END


----- EMS 2.88_01, modify table 'userRole', change 'description' length 50 to 200. UI length 32, DB needs 192.
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[userRole]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    IF EXISTS (SELECT * FROM syscolumns WHERE name='description' and id=OBJECT_ID('userRole'))
    BEGIN
		IF (select CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='userRole' and COLUMN_NAME='description' ) < 200 	
		BEGIN 
			ALTER TABLE userRole ALTER COLUMN [description] VARCHAR(200) 
		END	
    END
END
GO




----- EMS 2.81_01, add table 'roleAccess'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[roleAccess]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[roleAccess](
	[role_id] [int] NOT NULL,
	[node_id] [int] NOT NULL,
    CONSTRAINT [PK_roleAccess] PRIMARY KEY CLUSTERED 
    (
	    [role_id] ASC,
	    [node_id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]     
    
    ALTER TABLE [dbo].[roleAccess]  WITH CHECK ADD  CONSTRAINT [FK_roleAccess_userRole] FOREIGN KEY ([role_id]) 
    REFERENCES [dbo].[userRole] ([id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
    
    ALTER TABLE [dbo].[roleAccess] CHECK CONSTRAINT [FK_roleAccess_userRole] 
    
    ALTER TABLE [dbo].[roleAccess]  WITH CHECK ADD  CONSTRAINT [FK_roleAccess_nodes] FOREIGN KEY ([node_id]) 
    REFERENCES [dbo].[nodes] ([id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
    
    ALTER TABLE [dbo].[roleAccess] CHECK CONSTRAINT [FK_roleAccess_nodes] 
END
GO

IF (SELECT COUNT(*) FROM roleAccess) = 0
BEGIN
	-- any role with 'Network' function can load product tree nodes
	-- if one role has no 'Network' function, UI button 'Add Tree Node' is disabled, and no chance to load product tree
	-- table 'roleAccess' has no rows for product tree nodes 
	INSERT INTO roleAccess SELECT 1, id FROM nodes WHERE id>1000 -- system default role administrator
	INSERT INTO roleAccess SELECT 2, id FROM nodes WHERE id>1000 -- system default role operator
	INSERT INTO roleAccess SELECT 3, id FROM nodes WHERE id>1000 -- system default role user
END
GO

----- EMS 2.81_01, add table 'clientRole'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[clientRole]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[clientRole](
	[client_id] [int] NOT NULL,
	[role_id] [int] NOT NULL,
    CONSTRAINT [PK_clientRole] PRIMARY KEY CLUSTERED 
    (
	    [client_id] ASC,
	    [role_id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]     
    
    ALTER TABLE [dbo].[clientRole]  WITH CHECK ADD  CONSTRAINT [FK_clientRole_client] FOREIGN KEY ([client_id]) 
    REFERENCES [dbo].[client] ([id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
    
    ALTER TABLE [dbo].[clientRole] CHECK CONSTRAINT [FK_clientRole_client] 
    
    ALTER TABLE [dbo].[clientRole]  WITH CHECK ADD  CONSTRAINT [FK_clientRole_userRole] FOREIGN KEY ([role_id]) 
    REFERENCES [dbo].[userRole] ([id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
    
    ALTER TABLE [dbo].[clientRole] CHECK CONSTRAINT [FK_clientRole_userRole] 
END
GO

----- EMS 2.81_01, modify table 'client', remove column 'acl' after INSERT into new table 'clientRole'
IF EXISTS (SELECT * FROM syscolumns WHERE name='acl' and id=OBJECT_ID('client'))
BEGIN
	IF OBJECT_ID(N'[tempdb].[dbo].[#tmpClient]') IS NOT NULL
		DROP TABLE #tmpClient

	-- NOTE: NOT to "select acl from client",
	--       EMSv281 remove column 'acl', EMSv282 has no column 'acl',
	--       the same script can only pass SQL compilation when EMSv281,
	--       and will has error 'invalid column' when EMSv282,
	--       so need to create a temp table, and select acl from this temp table.
	
	SELECT * INTO #tmpClient FROM client
	
	INSERT INTO [dbo].[clientRole] ([client_id],[role_id])
		SELECT id, acl FROM #tmpClient
        
	ALTER TABLE [dbo].[client] DROP COLUMN [acl] 
	ALTER TABLE [dbo].[nodes] DROP COLUMN [acl]
	
	DROP TABLE #tmpClient
END 
GO

----- EMS 2.88_01, modify table 'client', change 'description' length 50 to 200. UI length 32, DB needs 192.
----- EMS 2.88_01, modify table 'client', change 'division' length 32 to 100. UI length 16, DB needs 96.
----- EMS 2.88_01, modify table 'client', change 'phone' length 32 to 100. UI length 16, DB needs 96.
----- EMS 2.88_01, modify table 'client', change 'address' length 50 to 200. UI length 32, DB needs 192.
----- EMS 2.97_01, modify table 'client', change length of all columns to 768
IF EXISTS (SELECT * FROM syscolumns WHERE name='name' and id=OBJECT_ID('client'))
BEGIN	
	-- name
	IF (select CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='client' and COLUMN_NAME='name' ) < 768 	
	BEGIN 
		ALTER TABLE client ALTER COLUMN [name] VARCHAR(768) 
	END
	
	-- password
	IF (select CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='client' and COLUMN_NAME='password' ) < 768 	
	BEGIN 
		ALTER TABLE client ALTER COLUMN [password] VARCHAR(768) 
	END
	
	-- phone
	IF (select CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='client' and COLUMN_NAME='phone' ) < 768 	
	BEGIN 
		ALTER TABLE client ALTER COLUMN [phone] VARCHAR(768) 
	END
	
	-- division
	IF (select CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='client' and COLUMN_NAME='division' ) < 768 	
	BEGIN 
		ALTER TABLE client ALTER COLUMN [division] VARCHAR(768) 
	END
	
	-- address
	IF (select CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='client' and COLUMN_NAME='address' ) < 768 	
	BEGIN 
		ALTER TABLE client ALTER COLUMN [address] VARCHAR(768) 
	END	
	
	-- description
	IF (select CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='client' and COLUMN_NAME='description' ) < 768 	
	BEGIN 
		ALTER TABLE client ALTER COLUMN [description] VARCHAR(768) 
	END
END 
GO

----- EMS 2.87_15, modify table 'inventoryListByServer', change 'alias' length 128 to 768. UI length 128, DB needs 768.
IF EXISTS (SELECT * FROM syscolumns WHERE name='alias' and id=OBJECT_ID('inventoryListByServer'))
BEGIN	
	IF (select CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='inventoryListByServer' and COLUMN_NAME='alias' ) < 768 	
	BEGIN 
		ALTER TABLE inventoryListByServer ALTER COLUMN [alias] VARCHAR(768) 
	END
END

GO

----- EMS 2.16_03, modify procedure 'admin_clientList', rename to 'getClients'
----- EMS 2.81_01, modify procedure 'getClients'
----- EMS 2.88_01, modify procedure 'getClients', change column length, 'descripation' and 'address'.
----- EMS 2.97_01, modify procedure 'getClients', change length of all columns to 768
----- EMS 2.97_01, modify procedure 'getClients', replace role name list with total role number
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_clientList]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_clientList]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getClients]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getClients]
GO

CREATE PROCEDURE [dbo].[getClients]
	@orderCol varchar(100),
	@orderDir varchar(100)
AS
	IF OBJECT_ID(N'[tempdb].[dbo].[#order]') IS NOT NULL
		DROP TABLE #order

	CREATE TABLE #order (
		id          int,
		name        varchar(768),
		description varchar(768),
		role        int,
		division    varchar(768),
		phone       varchar(768),
		address     varchar(768)
	)
	
	DECLARE @tempId          int,
	        @tempName        varchar(768),
	        @tempDescription varchar(768),
		    @tempRole        int,
		    @tempDivision    varchar(768),
		    @tempPhone       varchar(768),
		    @tempAddress     varchar(768)
        
	DECLARE Cur CURSOR FOR
	SELECT id,name,description,division,phone,address FROM client

	-- EMSv297, replace role name list with total role number
	-- SET @tempRole = ''

	OPEN Cur
	FETCH NEXT FROM Cur INTO @tempId, @tempName, @tempDescription, @tempDivision, @tempPhone, @tempAddress   
	WHILE ( @@FETCH_STATUS = 0 )
    BEGIN
        SELECT @tempRole = COUNT(1) FROM clientRole WHERE client_id=@tempId    
        
        INSERT INTO #order  
        VALUES(@tempId,@tempName,@tempDescription,@tempRole,@tempDivision,@tempPhone,@tempAddress)  
        
        FETCH NEXT FROM Cur INTO @tempId, @tempName, @tempDescription, @tempDivision, @tempPhone, @tempAddress  
    END
	CLOSE Cur 
	DEALLOCATE Cur  
	
	-- order by statement
	EXEC('SELECT * FROM #order ORDER by ['+@orderCol+'] '+@orderDir)
	DROP TABLE #order
GO


----- EMS 2.16_03, modify procedure 'admin_clientInsert', rename to 'addClient'
----- EMS 2.81_01, modify procedure 'addClient', remove param acl
----- EMS 2.88_01, modify procedure 'addClient', change colunm length, 'phone', 'division', 'address', and 'description'.
----- EMS 2.93_01, modify procedure 'addClient', add default empty ACL ip/mac
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_clientInsert]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_clientInsert]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[addClient]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[addClient]
GO

CREATE PROCEDURE [dbo].[addClient]
	@name		  varchar(50),
	@password	  varchar(32),
	@role		  varchar(128),
	@phone  	  varchar(100),
	@division	  varchar(100),
	@address	  varchar(200),
	@description  varchar(200)
AS
	DECLARE @newId int
	
	INSERT INTO client (name, password, phone, division, address, description, default_tree)
		VALUES (@name, @password, @phone, @division, @address, @description, 0)
	
	IF @@error<>0 
		GOTO ERR
	
	SELECT @newId = @@identity
	
	DECLARE @i int  
    SET @role = RTRIM(LTRIM(@role))  
    SET @i = CHARINDEX(',',@role)  
    WHILE(@i>=1)  
    BEGIN  
		INSERT INTO clientRole VALUES(@newId, LEFT(@role,@i-1))  
		SET @role = SUBSTRING(@role,@i+1,LEN(@role)-@i)  
		SET @i = CHARINDEX(',',@role)  
    END  
    
    -- add default empty ACL ip/mac
    INSERT INTO clientACL VALUES(@newId, '', '')

ERR:
RETURN -1

GO


----- EMS 2.16_03, modify procedure 'admin_clientUpdate', rename to 'editClient'
----- EMS 2.81_01, modify procedure 'editClient', , remove param acl
----- EMS 2.88_01, modify procedure 'editClient', change colunm length, 'phone', 'division', 'address', and 'description'.
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_clientUpdate]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_clientUpdate]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[editClient]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[editClient]
GO

CREATE PROCEDURE [dbo].[editClient]
	@client_id   int,
	@name		 varchar(50),
	@password	 varchar(32),
	@role		 varchar(128),
	@phone  	 varchar(100),
	@division	 varchar(100),
	@address	 varchar(200),
	@description varchar(200)

AS
	UPDATE client
		SET	name     = 	CASE 
							WHEN @client_id=1 THEN name -- id=1 administrator name cannot be changed
							ELSE @name
						END,
			password = @password,
    		phone    = @phone,
    		division = @division,
    		address  = @address,
    		description = @description
		
		WHERE id=@client_id
		
	-- role
	-- account admin can not change role
	IF @client_id > 1
	BEGIN
		DELETE FROM clientRole WHERE client_id = @client_id
	
		DECLARE @i int  
		SET @role = RTRIM(LTRIM(@role))  
		SET @i = CHARINDEX(',',@role)  
		WHILE(@i>=1)  
		BEGIN  
			INSERT INTO clientRole VALUES(@client_id, LEFT(@role,@i-1))  
			SET @role = SUBSTRING(@role,@i+1,LEN(@role)-@i)  
			SET @i = CHARINDEX(',',@role)  
		END
	END  
GO


----- EMS 2.16_03, modify procedure 'admin_clientDelete', rename to 'deleteClient'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_clientDelete]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_clientDelete]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[deleteClient]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[deleteClient]
GO

CREATE PROCEDURE [dbo].[deleteClient]
	@client_id int
AS
	DELETE FROM client WHERE id=@client_id and id<>1	-- sql administrator should not be delete
GO


----- EMS 2.16_03, delete procedure 'admin_clientGet'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_clientGet]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_clientGet]
GO



----- EMS 2.81_01, add procedure 'getUserRoles'
----- EMS 2.83_01, modify procedure 'getUserRoles', move 'Radius Id' from the first column to the last
----- EMS 2.88_01, modify procedure 'getUserRoles', default roles Administrator/Operator/User fixed at top
----- EMS 2.88_01, modify procedure 'getUserRoles', add new column 'radius_id'
----- EMS 2.88_01, modify procedure 'getUserRoles', change 'description' length 100 to 200. UI length 32, DB needs 192.
----- EMS 2.97_01, modify procedure 'getUserRoles', change length of all columns to 768
----- EMS 2.97_01, modify procedure 'getUserRoles', replace user name list with total user number
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getUserRoles]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getUserRoles]
GO

CREATE PROCEDURE [dbo].[getUserRoles]
	@orderCol varchar(100),
	@orderDir varchar(100)
AS
	IF OBJECT_ID(N'[tempdb].[dbo].[#order]') IS NOT NULL
		DROP TABLE #order

	CREATE TABLE #order (
		[name]        varchar(768),
		[description] varchar(768),
		[function]    varchar(10),
		[user]        int,  -- allow empty account
		                    -- EMSv297, replace user name list with total user number
		                    
		[id]          int,  -- EMSv283 move from the first column to the last
		[radius_id]   int   -- EMSv288, add new column 'radius_id'
	)
	
	DECLARE @tempId          int,
	        @tempName        varchar(768),
	        @tempDescription varchar(768),
		    @tempFunction    varchar(10),
		    @tempUser        int, -- EMSv297, replace user name list with total user number
		    @tempRadius      int  -- EMSv288, add new column 'radius_id'
        
	DECLARE Cur CURSOR FOR
	SELECT [id],[name],[description],[function],[radius_id] FROM userRole
	
	-- EMSv297, replace user name list with total user number
	-- SET @tempUser = ''
	
	OPEN Cur
	FETCH NEXT FROM Cur INTO @tempId, @tempName, @tempDescription, @tempFunction, @tempRadius
	WHILE ( @@FETCH_STATUS = 0 )
    BEGIN
        SELECT @tempUser = COUNT(1) 
        FROM clientRole WHERE role_id=@tempId    
        
        INSERT INTO #order
        VALUES(@tempName,@tempDescription,@tempFunction,@tempUser,@tempId,@tempRadius)
        
        SET @tempUser = 0 
        FETCH NEXT FROM Cur INTO @tempId, @tempName, @tempDescription, @tempFunction, @tempRadius    
    END
	CLOSE Cur 
	DEALLOCATE Cur  
	
	-- EMS 2.88, default roles Administrator/Operator/User fixed at top
	IF OBJECT_ID(N'[tempdb].[dbo].[#order2]') IS NOT NULL
		DROP TABLE #order2

	CREATE TABLE #order2 (
		[name]        varchar(768),
		[description] varchar(768),
		[function]    varchar(10),
		[user]        int, -- allow empty account
		[id]          int, -- EMSv283 move from the first column to the last
		[radius_id]   int  -- EMSv288, add new column 'radius_id'
	)
	
	INSERT INTO #order2 SELECT * FROM #order WHERE id<4 ORDER BY id
	EXEC('INSERT INTO #order2 SELECT * FROM #order WHERE id>3 ORDER BY ['+@orderCol+'] '+@orderDir)
	
	SELECT [name],[description],[function],[user],[radius_id] FROM #order2
	
	DROP TABLE #order2
	DROP TABLE #order
GO

----- EMS 2.81_01, add procedure 'addUserRole'
----- EMS 2.88_01, modify procedure 'addUserRole', add param 'nodeIds'
----- EMS 2.88_01, modify procedure 'addUserRole', add new column 'radius_id'
----- EMS 2.88_01, modify procedure 'addUserRole', change 'description' length 50 to 200. UI length 32, DB needs 192.
----- EMS 2.97_01, modify procedure 'addUserRole', change length of all columns to 768
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[addUserRole]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[addUserRole]
GO

CREATE PROCEDURE [dbo].[addUserRole]
	@name		  varchar(768),
	@func	      varchar(10),
	@user		  varchar(768),
	@description  varchar(768),
	@node		  varchar(MAX), -- 500 devices, 500 trees, 500 locations, node id length 5
	                            -- CSV string length = 1500 * (5+1) = 9000
	@radiusId     int
AS
	DECLARE @newId int
	
	INSERT INTO userRole ([name], [description], [function], [radius_id])
		VALUES (@name, @description, @func, @radiusId)
	
	IF @@error<>0 
		GOTO ERR
	
	SELECT @newId = @@identity
	
	-- user
	DECLARE @i int  
    SET @user = RTRIM(LTRIM(@user))  
    SET @i = CHARINDEX(',',@user)  
    WHILE(@i>=1)  
    BEGIN  
		INSERT INTO clientRole VALUES(LEFT(@user,@i-1), @newId)  
		SET @user = SUBSTRING(@user,@i+1,LEN(@user)-@i)  
		SET @i = CHARINDEX(',',@user)  
    END
    
    -- tree node
    SET @node = RTRIM(LTRIM(@node))  
    SET @i = CHARINDEX(',',@node)  
    WHILE(@i>=1)  
    BEGIN  
		INSERT INTO roleAccess VALUES(@newId, LEFT(@node,@i-1))  
		SET @node = SUBSTRING(@node,@i+1,LEN(@node)-@i)  
		SET @i = CHARINDEX(',',@node)  
    END    
    
    -- radius
    IF @radiusId=0
		UPDATE userRole SET [radius_id]=[id] WHERE [id]=@newId 

ERR:
RETURN -1

GO


----- EMS 2.81_01, add procedure 'editUserRole'
----- EMS 2.88_01, modify procedure 'editUserRole', add param 'nodeIds', 'isNodeChanged'
----- EMS 2.88_01, modify procedure 'editUserRole', add new column 'radius_id'
----- EMS 2.88_01, modify procedure 'editUserRole', change 'description' length 50 to 200. UI length 32, DB needs 192.
----- EMS 2.97_01, modify procedure 'editUserRole', change length of all columns to 768
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[editUserRole]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[editUserRole]
GO

CREATE PROCEDURE [dbo].[editUserRole]
	@role_id     int,
	@name		 varchar(768),
	@func	     varchar(10),
	@user		 varchar(768), -- account admin already filtered out in UI 
	@description varchar(768),
	@userChanged bit,          -- UI check if account has any change 
	@node		 varchar(768), 
	@nodeChanged bit,          -- 1.UI check if node has any change 
	                           -- 2.role 'Administrator' is not allowed to add/delete node 
	@radiusId    int
	
AS
	IF @radiusId=0
		SET @radiusId = @role_id

	UPDATE userRole
		SET	[name]   = 	CASE 
							WHEN @role_id=1 THEN name -- id=1 administrator name cannot be changed
							ELSE @name
						END,
			[function] = @func,
    		[description] = @description,
    		[radius_id] = @radiusId
		
		WHERE id=@role_id
	
	DECLARE @i int
	
	-- account changed, need to edit table clientRole
	IF @userChanged=1
	BEGIN
		-- before edit table clientRole, prepare temp table to store account which has this role
		IF OBJECT_ID(N'[tempdb].[dbo].[#tTb]') IS NOT NULL
			DROP TABLE #tTb

		CREATE TABLE #tTb (
			[cid] int
		)
	
		INSERT INTO #tTb SELECT client_id FROM clientRole WHERE role_id=@role_id AND client_id > 1 -- id=1 for account admin
	
		-- edit step 1: delete
		DELETE FROM clientRole WHERE role_id = @role_id AND client_id > 1 -- id=1 for account admin
	
		-- edit step 2: recover by UI parameter @user	
		IF LEN(@user) > 0  -- role may have empty account
		BEGIN
			SET @user = RTRIM(LTRIM(@user))  
			SET @i = CHARINDEX(',',@user)  
			WHILE(@i>=1)  
			BEGIN
				INSERT INTO clientRole VALUES(LEFT(@user,@i-1),@role_id)	
				SET @user = SUBSTRING(@user,@i+1,LEN(@user)-@i)  
				SET @i = CHARINDEX(',',@user)  
			END
		END  
	
		-- edit step 3: check if account has no role	
		IF (SELECT COUNT(*) FROM #tTb) > 0
		BEGIN
			-- if account has no role, set to system default role user
			DECLARE @cid int 
			DECLARE Cur CURSOR FOR
			SELECT cid FROM #tTb
	
			OPEN Cur
			FETCH NEXT FROM Cur INTO @cid   
			WHILE ( @@FETCH_STATUS = 0 )
			BEGIN
				IF (SELECT TOP(1) role_id FROM clientRole WHERE client_id=@cid) IS NULL
					INSERT INTO clientRole VALUES(@cid,3) -- role id=3 for system default role user 
			
				FETCH NEXT FROM Cur INTO @cid	
			END
			CLOSE Cur 
			DEALLOCATE Cur		
		END
		
		DROP TABLE #tTb
	
	END -- end of edit table clientRole
	
	-- node changed, need to edit table roleAccess
	IF (@nodeChanged=1 AND @role_id>1) -- role 'Administrator' is not allowed to add/delete node 
	BEGIN
		-- edit step 1: delete
		DELETE FROM roleAccess WHERE role_id = @role_id 
	
		-- edit step 2: recover by UI parameter @node	
		IF LEN(@node) > 0  -- role may have empty tree node
		BEGIN
			SET @node = RTRIM(LTRIM(@node))  
			SET @i = CHARINDEX(',',@node)  
			WHILE(@i>=1)  
			BEGIN
				INSERT INTO roleAccess VALUES(@role_id, LEFT(@node,@i-1))	
				SET @node = SUBSTRING(@node,@i+1,LEN(@node)-@i)  
				SET @i = CHARINDEX(',',@node)  
			END
		END 	
	END -- end of edit table roleAccess	
	
GO


----- EMS 2.81_01, add procedure 'deleteUserRole'
----- EMS 2.88_01, modify procedure 'deleteUserRole', param is radius_id
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[deleteUserRole]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[deleteUserRole]
GO

CREATE PROCEDURE [dbo].[deleteUserRole]
	@radiusId int
AS
	DECLARE @role_id int
	SELECT @role_id=[id] FROM userRole WHERE [radius_id]=@radiusId

	-- prepare temp table to store account which has this role
	IF OBJECT_ID(N'[tempdb].[dbo].[#tTb]') IS NOT NULL
		DROP TABLE #tTb

	CREATE TABLE #tTb (
		[cid] int
	)
	
	INSERT INTO #tTb SELECT client_id FROM clientRole WHERE role_id=@role_id
	
	-- delete
	DELETE FROM userRole WHERE id=@role_id and id>3	-- not to delete system default roles admin/operator/user

	-- if account has no role, set to system role user
	DECLARE @cid int 
	DECLARE Cur CURSOR FOR
	SELECT cid FROM #tTb

	OPEN Cur
	FETCH NEXT FROM Cur INTO @cid   
	WHILE ( @@FETCH_STATUS = 0 )
    BEGIN
        IF (SELECT TOP(1) role_id FROM clientRole WHERE client_id=@cid) IS NULL
			INSERT INTO clientRole VALUES(@cid,3) -- role id=3 for system role user 
		
		FETCH NEXT FROM Cur INTO @cid	
    END
	CLOSE Cur 
	DEALLOCATE Cur  
	
	DROP TABLE #tTb 
GO

----- EMS 2.81_01, add procedure 'editRoleAccess'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[editRoleAccess]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[editRoleAccess]
GO

CREATE PROCEDURE [dbo].[editRoleAccess]
	@node_id     int,
	@role		 varchar(128) -- role 'administrator' already filtered out in UI 

AS
	-- edit step 1: delete
	DELETE FROM roleAccess WHERE node_id = @node_id AND role_id > 1 -- id=1 for role 'administrator'
	
	-- edit step 2: recover by UI parameter @role
	IF LEN(@role) > 0  -- one node may become only accessable by role 'administrator'
	BEGIN
		DECLARE @i int
		SET @role = RTRIM(LTRIM(@role))  
		SET @i = CHARINDEX(',',@role)  
		WHILE(@i>=1)  
		BEGIN
			INSERT INTO roleAccess VALUES(LEFT(@role,@i-1),@node_id) 
			SET @role = SUBSTRING(@role,@i+1,LEN(@role)-@i)  
			SET @i = CHARINDEX(',',@role)  
		END
	END
GO

----- EMS 2.81_01, modify procedure 'getTreeNodes', add param 'userName' for role access check
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getTreeNodes]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getTreeNodes]
GO

CREATE PROCEDURE [dbo].[getTreeNodes]
	@treeId int,
	@userName varchar(64)
AS

IF OBJECT_ID(N'[tempdb].[dbo].[#tLink]') IS NOT NULL
	DROP TABLE #tLink
	
CREATE TABLE #tLink (
	id int
)

insert into #tLink select distinct child_id from treelinks where tree_id=@treeId

select dBId=n.id, name=n.name, typeId=n.type_id  
from nodes n, #tLink k     
where n.id=k.id 
		AND (n.id<1001 OR n.id IN (SELECT id FROM [dbo].[fn_getAllowedNodesByUserName](@userName)))

drop table #tLink

GO

----- EMS 2.81_01, modify procedure 'getTreeLinks', add param 'userName' and check role access
----- EMS 2.81_01, modify procedure 'getTreeLinks', adjust tree structure before return
----- EMS 2.89_03, modify procedure 'getTreeLinks', fix SQL 2014 order by issue
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getTreeLinks]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getTreeLinks]
GO

CREATE PROCEDURE [dbo].[getTreeLinks]
	@treeId int,
	@userName varchar(64)
AS

IF OBJECT_ID(N'[tempdb].[dbo].[#tNodes]') IS NOT NULL
	DROP TABLE #tNodes

SELECT * INTO #tNodes FROM [dbo].[fn_getAllowedNodesByUserName](@userName)

IF OBJECT_ID(N'[tempdb].[dbo].[#tLink]') IS NOT NULL
	DROP TABLE #tLink
	
select parentId=parent_id, childId=child_id, level=lvl, 'index'=idx 
INTO #tLink
from treelinks 

-- where tree_id=@treeId order by lvl,idx 
WHERE tree_id=@treeId 
		AND (parent_id<1001 OR parent_id IN (SELECT id FROM #tNodes)) -- -1 for root's parent, 1~1000 for product tree nodes
		AND (child_id<1001  OR child_id  IN (SELECT id FROM #tNodes)) -- 1~1000 for product tree nodes

order by treelinks.lvl ASC, treelinks.parent_id ASC, treelinks.idx ASC

IF OBJECT_ID(N'[tempdb].[dbo].[#tAdjIdx]') IS NOT NULL
	DROP TABLE #tAdjIdx

DECLARE @pid int, @cid int, @lv int, @compareLV int, @newLV int, @compareParent int  
SELECT TOP(1) @compareLV=level FROM #tLink
ORDER BY [level] ASC, [parentId] ASC, [index] ASC


CREATE TABLE #tAdjIdx (
	[parentId] int, [childId] int, [level] int, [index] int IDENTITY(0,1)
) 

IF @compareLV=0 -- if first level not 0, this user not in allow list of root node
BEGIN
	SET @newLV=0 
	SET @compareParent=-1 
	
	DECLARE Cur CURSOR FOR
	SELECT [parentId], [childId], [level] FROM #tLink ORDER BY [level] ASC, [parentId] ASC, [index] ASC
	OPEN Cur
	FETCH NEXT FROM Cur INTO @pid, @cid, @lv    
	WHILE ( @@FETCH_STATUS = 0 )
	BEGIN
		IF @compareLV<>@lv
		BEGIN
			DBCC checkident (#tAdjIdx, reseed, -1)
			SET @compareLV=@lv
			SET @newLV = @newLV+1
		END
		ELSE
		BEGIN
			IF @compareParent<>@pid 
				DBCC checkident (#tAdjIdx, reseed, -1) 
		END
		
		INSERT INTO #tAdjIdx (parentId, childId, level) VALUES (@pid, @cid, @newLV) 
		
		SET @compareParent=@pid 
		FETCH NEXT FROM Cur INTO @pid, @cid, @lv	
	END
	CLOSE Cur 
	DEALLOCATE Cur  
END

SELECT * FROM #tAdjIdx ORDER BY [level] ASC, [index] ASC 

DROP TABLE #tNodes
DROP TABLE #tLink
DROP TABLE #tAdjIdx

GO

----- EMS 2.81_01, modify procedure 'loadUserTree', check role access
----- EMS 2.200, change procedure 'loadUserTree' to 'getUserTree'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[loadUserTree]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[loadUserTree]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getUserTree]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getUserTree]
GO

CREATE PROCEDURE [dbo].[getUserTree] 
	@username varchar(100)
AS
	
DECLARE
	@treeId   int,
	@clientId int

BEGIN
	-- Client default_tree id is set to 0 by default,
	SELECT @treeId=default_tree FROM client WHERE name=@username

	-- Tree has an instance	of node, and tree id is from 1 (repository product tree)
	-- If the tree of the tree id is not found, 
    -- select the the tree of max tree id created by user to be default_tree 
	IF NOT EXISTS(SELECT * FROM trees WHERE id=@treeId)
	BEGIN
		SELECT @clientId=id FROM client WHERE name=@username

		SELECT @treeId=isnull(max(t.id),0) FROM trees t, nodes n 
		WHERE t.id<>1 and t.node_id=n.id and n.client_id=@clientId
				 AND t.node_id IN (SELECT id FROM [dbo].[fn_getAllowedNodesByUserName](@username)) -- check role access

		-- add new loaded tree to be default tree
		update client set default_tree=@treeId where name=@username;
	END 	
END

SELECT tree_id=@treeId
GO

----- EMS 2.81_01, remove procedure 'treeIsModify'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[treeIsModify]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[treeIsModify]
	
	-- IF user login account role has no 'Network' function,
	-- user is not allowed to add_node, delete_node, ..., etc,
	-- and there is no chance to run DB procedure add_node, delete_node, ..., etc,
	-- once user can add_node, delete_node, ..., etc,
	-- this user must be allowed to modify tree,
	-- so this procedure 'treeIsModify' is useless from EMSv281.
	
	-- in this script please search: remove procedure 'treeIsModify'
GO

----- EMS 2.81_01, modify procedure 'admin_agentNodeInsert', remove acl
----- EMS 2.81_01, modify procedure 'admin_agentNodeInsert', new device node default allowed for role administrator/operator/user
----- EMS 2.90_01, modify procedure 'admin_agentNodeInsert', change agent_name length 100 to 768. UI length 128, DB needs 768.
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_agentNodeInsert]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_agentNodeInsert]
GO

CREATE PROCEDURE [dbo].[admin_agentNodeInsert]
    @worker_name  varchar(50),       
    @agent_name   varchar(768),      --Chinese to unicode 6 char %uxxxx
    @node_type_id tinyint

AS
DECLARE 
    @client_id int,
    -- @acl       tinyint, 
    @id        int, 
    @idx       int, 
    @lvl       int, 
    @i         int, 
    @j         int, 
    @k         int, 
    @l         int,
	@agent_id  int, 
	@rack_id   int, 
	@slot_id   int, 
	@loop_id   int, 
	@mark_id   int, 
	@port_id   int, 	
	@tree_id   int,
	@parent_id int

select @tree_id=1
--select @parent_id=root_id from node_types where id=@node_type_id
set @parent_id=@node_type_id
select @client_id=id from client where name=@worker_name
-- if @acl<>255 return -1
-- EMSv281 removed
-- if @acl<>1 return -1		-- only admin can run admin tool

begin tran
	SELECT @agent_id=isnull(max(id),1000)+1 from nodes where id>1000
	if @@error<>0 goto err

	if not exists (select 1 from treelinks where tree_id=@tree_id and parent_id=@parent_id)
		select @idx=0 
	else
		select @idx=max(idx)+1 from treelinks where tree_id=@tree_id and parent_id=@parent_id
	if @@error<>0 goto err

	select @lvl=lvl+1 from treelinks where tree_id=@tree_id and child_id=@parent_id
	if @@error<>0 goto err

-- insert nodes
	-- EMSv281, table 'nodes' has no column 'acl'
	insert nodes(id,name,type_id,client_id) values(@agent_id,@agent_name,@node_type_id,@client_id)
	if @@error<>0 goto err
	
	-- new device node default allowed for role administrator/operator/user
	INSERT INTO roleAccess SELECT id,@agent_id FROM userRole WHERE id<4

-- insert treelinks	
	insert treelinks(tree_id,parent_id,child_id,idx,lvl) values(@tree_id,@parent_id,@agent_id,@idx,@lvl)	
	if @@error<>0 goto err
commit tran
return @agent_id
err:
rollback tran
return -1
GO

----- EMS 2.76_01, modify procedure 'nodeInsert', rename to 'addTreeNode'
----- EMS 2.81_01, modify procedure 'addTreeNode', remove acl
----- EMS 2.81_01, modify procedure 'addTreeNode', new location node default allowed for creator roles and system roles administrator/operator/user
----- EMS 2.88_01, modify procedure 'addTreeNode', add one more 'WHERE AND' conditon for creator roles
----- EMS 2.90_01, modify procedure 'addTreeNode', change name length 100 to 768. UI length 128, DB needs 768.
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[addTreeNode]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[addTreeNode]
GO

CREATE PROCEDURE [dbo].[addTreeNode] 
	@worker_name varchar(50), 
	@tree_id     int, 
	@parent_id   int,
	@name        varchar(768)

AS
DECLARE 
	@client_id int,			
	-- @acl       tinyint,			
	@tree_type int,
	@id        int,
	@idx       int,	
	@lvl       int,		
	@r         int			

	-- get user info
	SELECT @client_id=id FROM client WHERE name=@worker_name 
	SELECT @tree_type=type FROM trees WHERE id=@tree_id

	-- only acl<creator can modify the tree, except public tree type=1 
	--if @acl_client>@acl_node and @tree_type<>1 goto ERR1		
	--if @is_rep=1 and @workerId<>1 goto ERR1	-- only client id=1 super admin can modify defaut repository tree

	-- select node has tree name to identify the tree acl when create
	--SELECT @acl_node=n.acl FROM nodes n, treelinks l 
	--WHERE l.tree_id=@tree_id and l.parent_id=-1 and l.child_id=n.id		

	-- check tree is modified
	----- EMS 2.81_01, remove procedure 'treeIsModify'
	-- EXEC @r=treeIsModify @worker_name, @tree_id 
	-- IF @r=0 GOTO ERR1

BEGIN TRAN
	-- add node
	SELECT @id=ISNULL(MAX(id), 1000)+1 FROM nodes WHERE id>1000
	
	-- EMSv281, table 'nodes' has no column 'acl'
	INSERT nodes(id, name, type_id, client_id) 
		VALUES(@id, @name, 1, @client_id)
	IF @@ERROR<>0 GOTO ERR
	
	-- new location node default allowed for system roles administrator/operator/user
	INSERT INTO roleAccess SELECT id,@id FROM userRole WHERE id<4

	-- new location node default allowed for creator roles 
	INSERT INTO roleAccess SELECT id,@id FROM [dbo].[fn_getRolesByUserName](@worker_name) WHERE id>3 
	-- EMS 2.88
	-- user02-Net/user04-Net has role '02,Network'/'04,Network', 
	-- 'Network' is function role, can access no location or device, 
	-- user02-Net add new location node '02-2659'
	-- bug is user04-Net can show location '02-2659'
	AND (SELECT COUNT(*) FROM roleAccess WHERE role_id=id AND node_id=@parent_id)>0
	
	
	-- find index, index starts from 0 
	SET @idx=(SELECT ISNULL(MAX(idx), -1) FROM treelinks 
		WHERE tree_id=@tree_id AND parent_id=@parent_id)
	
	-- find level,
	SET @lvl=(SELECT lvl FROM treelinks 
		WHERE tree_id=@tree_id AND child_id=@parent_id)	

	-- add tree link
	INSERT treelinks (tree_id, parent_id, child_id, idx, lvl) 
		VALUES (@tree_id, @parent_id, @id, @idx+1, @lvl+1)
	IF @@ERROR<>0 GOTO ERR	
	
	-- add topology location
	EXEC addTopologyLocation @tree_id, @id
	IF @@ERROR<>0 GOTO ERR	
	
COMMIT TRAN

	SELECT id=@id
	RETURN 0

ERR:
ROLLBACK TRAN

ERR1:
	RETURN -1
GO

----- EMS 2.76_01, modify procedure 'nodeCopy', rename to 'addTreeNodeFromProduct'
----- EMS 2.81_01, modify procedure 'addTreeNodeFromProduct', default allowed for creator roles
----- EMS 2.84_01, modify procedure 'addTreeNodeFromProduct', check if creator roles can access child nodes
----- EMS 2.88_01, modify procedure 'addTreeNodeFromProduct', add one more 'WHERE AND' condition for creator roles
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[nodeCopy]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[nodeCopy]
GO

IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[addTreeNodeFromProduct]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[addTreeNodeFromProduct]
GO

CREATE PROCEDURE [dbo].[addTreeNodeFromProduct]
	@worker_name      varchar(50),
	@tree_id          int,
	@node_id          int,
	@product_tree_id  int,
	@product_node_id  int

AS
	DECLARE
		@idx int, 
		@lvl int,		
		--@acl      tinyint,	-- client
		--@acl1     tinyint,	-- source tree node acl
		--@acl_node tinyint,	--  destination tree node acl
		@r   int

	-- worker acl
	--SELECT @acl=acl FROM client WHERE name=@worker_name

	-- source tree node acl
	--SELECT @acl1=n.acl FROM  treelinks l, nodes n 
	--WHERE l.tree_id=@from_tree_id and l.parent_id=-1 and l.child_id=n.id  

	-- destination tree node acl
	--SELECT @acl_node=n.acl FROM  treelinks l, nodes n 
	--WHERE l.tree_id=@to_tree_id and l.parent_id=-1 and l.child_id=n.id 

	-- acl must > tree node creator 
	--if (@acl>@acl_node) goto ERR1
	--if (@to_tree_id=@from_tree_id) goto ERR1	--same tree

	-- check tree is modified
	----- EMS 2.81_01, remove procedure 'treeIsModify'
	-- EXEC @r=treeIsModify @worker_name, @tree_id
	-- IF @r=0 GOTO ERR2
	
	
	-- check if same tree
	IF @tree_id=@product_tree_id GOTO ERR2	

	SET @lvl=(SELECT lvl FROM treelinks 
		WHERE tree_id=@tree_id AND child_id=@node_id)
	
	SET @idx=ISNULL((SELECT MAX(idx) FROM treelinks 
		WHERE tree_id=@tree_id AND parent_id=@node_id), -1)
	
	-- store tree links for nodes which will join to the destination tree
	CREATE TABLE #x(			
		parent_id int,
		child_id  int,
		idx       int,
		lvl       int
	)

	-- store node
	CREATE TABLE #a(			
		parent_id int,
		child_id  int,
		idx       int,
		lvl       int
	)

	-- store node's children
	CREATE TABLE #b(			
		parent_id int,
		child_id  int,
		idx       int,
		lvl       int
	)

	-- find all children nodes from the product node.
	INSERT #a SELECT parent_id, child_id, idx, lvl FROM treelinks 
		WHERE tree_id=@product_tree_id AND child_id=@product_node_id

	WHILE EXISTS(SELECT * FROM #a)
	BEGIN
		INSERT #b SELECT t.parent_id, t.child_id, t.idx, t.lvl 
			FROM treelinks t, #a a
			WHERE t.tree_id=@product_tree_id AND t.parent_id=a.child_id

		INSERT #x SELECT * FROM #a
		TRUNCATE TABLE #a

		INSERT #a SELECT * FROM #b
		TRUNCATE TABLE #b		
	END

	-- check if duplicate node
	IF EXISTS(
		SELECT * FROM treelinks t, #x x
			WHERE t.tree_id=@tree_id AND t.child_id=x.child_id
	)	
	GOTO ERR1
	
	-- store creator roles
	IF OBJECT_ID(N'[tempdb].[dbo].[#creatorRoles]') IS NOT NULL
		DROP TABLE #creatorRoles
	
	SELECT * INTO #creatorRoles FROM [dbo].[fn_getRolesByUserName](@worker_name)
	
	-- store role allowed nodes
	IF OBJECT_ID(N'[tempdb].[dbo].[#roleNodes]') IS NOT NULL
		DROP TABLE #roleNodes
	
	SELECT * INTO #roleNodes FROM [dbo].[fn_getAllowedNodesByUserName](@worker_name)

BEGIN TRAN
	DECLARE @child_id  int
     
    DECLARE cur CURSOR FOR (SELECT child_id FROM #x) 
    OPEN cur                                          
    FETCH NEXT FROM cur INTO @child_id
    WHILE @@FETCH_STATUS=0                          
    BEGIN
		-- insert node for agent, not for product series name 
		IF @child_id>1000	
		BEGIN
			-- create tree links, join product nodes to management tree
			SET @idx=@idx+1
			
			INSERT INTO treelinks(tree_id, parent_id, child_id, idx, lvl)
				VALUES(@tree_id, @node_id, @child_id, @idx, @lvl+1)
			IF @@ERROR<>0 GOTO ERR
		   
	   		-- add topology device
			EXEC addTopologyDevice @tree_id, @child_id			
			IF @@ERROR<>0 GOTO ERR
			
			-- default allowed for creator roles
			DELETE FROM roleAccess WHERE role_id IN (SELECT id FROM #creatorRoles) AND node_id=@child_id -- to avoid key duplication
			INSERT INTO roleAccess SELECT id,@child_id FROM #creatorRoles 
					WHERE @child_id IN (SELECT id FROM #roleNodes) ----- EMS 2.84_01, check if creator roles can access child nodes 
					AND (SELECT COUNT(*) FROM roleAccess WHERE role_id=id AND node_id=@node_id)>0 -- EMS 2.88 
					
		END	
		FETCH NEXT FROM cur INTO @child_id               
    END
    CLOSE cur                                          
    DEALLOCATE cur                                 
COMMIT TRAN

	DROP TABLE #x
	DROP TABLE #a
	DROP TABLE #b
	DROP TABLE #creatorRoles
	DROP TABLE #roleNodes

	SELECT id=0
	RETURN 0

ERR:
    CLOSE cur                                          
    DEALLOCATE cur
    DROP TABLE #creatorRoles
    DROP TABLE #roleNodes 
ROLLBACK TRAN

ERR1:
	DROP TABLE #x
	DROP TABLE #a
	DROP TABLE #b
	
ERR2:
	SELECT id=-1
	RETURN -1

GO



----- EMS 2.76_01, modify procedure 'treeInsert', rename to 'addTree'
----- EMS 2.81_01, modify procedure 'addTree', remove acl
----- EMS 2.81_01, modify procedure 'addTree', new tree default allowed for creator roles and system roles administrator/operator/user
----- EMS 2.90_01, modify procedure 'addTree', change name length 100 to 768. UI length 128, DB needs 768.
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[addTree]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[addTree]
GO

CREATE PROCEDURE [dbo].[addTree]
	@work_name varchar(50), 
	@name      varchar(768), 
	@type      tinyint

AS 
DECLARE 
	@client_id int, 
	@tree_id   int,
	@node_id   int 
	-- @acl       tinyint

BEGIN TRAN
	-- get worker info 
	SELECT @client_id=id FROM client WHERE name=@work_name 
	IF @@ERROR<>0 GOTO ERR

	-- add node, user node id from 1000
	SELECT @node_id=ISNULL(MAX(id),1000)+1 FROM nodes WHERE id>1000	
	
	-- EMSv281, table 'nodes' has no column 'acl'
	INSERT nodes(id, name, client_id, type_id) 
		VALUES(@node_id, @name, @client_id, 1)
	IF @@ERROR<>0 GOTO ERR
	
	-- default allowed for system roles administrator/operator/user
	INSERT INTO roleAccess SELECT id,@node_id FROM userRole WHERE id<4
	
	-- default allowed for creator roles 
	INSERT INTO roleAccess SELECT id,@node_id FROM [dbo].[fn_getRolesByUserName](@work_name) WHERE id>3 

	-- add tree
	INSERT trees(node_id, repository, type) 
		VALUES(@node_id, 0, @type)
	IF @@ERROR<>0 GOTO ERR

	-- add treelink to map tree_id and node_id
	SELECT @tree_id=id FROM trees WHERE node_id=@node_id
	
	INSERT treelinks(tree_id, parent_id, child_id, idx, lvl)
		VALUES(@tree_id, -1, @node_id, 0, 0)
	IF @@ERROR<>0 GOTO ERR

	--	update client default tree
	UPDATE client SET default_tree=@tree_id WHERE name=@work_name
	IF @@ERROR<>0 GOTO ERR
	
	-- add topology location
	EXEC addTopologyLocation @tree_id, @node_id
	IF @@ERROR<>0 GOTO ERR
	
COMMIT TRAN
	SELECT dBId=@node_id, treeId=@tree_id, name=@name, typeId=1
	
	RETURN 0	

ERR:
ROLLBACK TRAN

	RETURN -1
GO

----- EMS 2.85_01, modify table 'trees', set type as public if not Product Tree
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[trees]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
	UPDATE trees SET type=1 WHERE id>1 AND type=0 
END
GO

----- EMS 2.85_01, add procedure 'getTreeCreator'
IF EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[getTreeCreator]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[getTreeCreator]
GO

CREATE PROCEDURE [dbo].[getTreeCreator]
	@rootId  int

AS
	SELECT c.name FROM client c, nodes n
	WHERE n.id=@rootId AND n.client_id=c.id 
GO

----- EMS 2.88_01, add table 'clientACL'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[clientACL]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[clientACL](
	[client_id] [int] NOT NULL,
	[ip] varchar(64) NOT NULL,
	[mac] varchar(32) NOT NULL,
    CONSTRAINT [PK_clientACL] PRIMARY KEY CLUSTERED 
    (
	    [client_id] ASC,
	    [ip] ASC,
	    [mac] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]     
    
    ALTER TABLE [dbo].[clientACL]  WITH CHECK ADD  CONSTRAINT [FK_clientACL_client] FOREIGN KEY ([client_id]) 
    REFERENCES [dbo].[client] ([id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
    
    ALTER TABLE [dbo].[clientACL] CHECK CONSTRAINT [FK_clientACL_client] 
END
GO

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getClientACL]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getClientACL]
GO

CREATE PROCEDURE [dbo].[getClientACL]
	@orderCol varchar(100),
	@orderDir varchar(100)
AS
	IF OBJECT_ID(N'[tempdb].[dbo].[#order]') IS NOT NULL
		DROP TABLE #order

	CREATE TABLE #order (
		name  varchar(100),
		ip    varchar(64),
		mac   varchar(32)
	)
	
	INSERT INTO #order 
	SELECT c.name, ca.ip, ca.mac  
	FROM client c, clientACL ca 
	WHERE ca.client_id=c.id
	
	-- order by statement
	EXEC('SELECT * FROM #order ORDER by ['+@orderCol+'] '+@orderDir)
	DROP TABLE #order
GO

----- EMS 2.88_01, add procedure 'addClientACL'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[addClientACL]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[addClientACL]
GO

CREATE PROCEDURE [dbo].[addClientACL]
	@name  varchar(50),
	@ip	   varchar(64),
	@mac   varchar(32)
AS	
	INSERT INTO clientACL 
	VALUES ((SELECT id FROM client WHERE name=@name), @ip, @mac)
	
	IF @@error<>0 
		GOTO ERR

ERR:
RETURN -1

GO

----- EMS 2.88_01, add procedure 'editClientACL'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[editClientACL]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[editClientACL]
GO

CREATE PROCEDURE [dbo].[editClientACL]
	@name   varchar(50),
	@oldIp	varchar(64),
	@oldMac varchar(32),
	@newIp	varchar(64),
	@newMac varchar(32)
AS	
	UPDATE clientACL 
	SET ip=@newIp, mac=@newMac 
	WHERE client_id=(SELECT id FROM client WHERE name=@name) 
	AND ip=@oldIp AND mac=@oldMac 
GO

----- EMS 2.88_01, add procedure 'deleteClientACL'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[deleteClientACL]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[deleteClientACL]
GO

CREATE PROCEDURE [dbo].[deleteClientACL]
	@name varchar(50),
	@ip	  varchar(64),
	@mac  varchar(32)
AS	
	DELETE FROM clientACL  
	WHERE client_id=(SELECT id FROM client WHERE name=@name) 
	AND ip=@ip AND mac=@mac
GO

----- EMS 2.88_01, add procedure 'deleteAllClientACL'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[deleteAllClientACL]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[deleteAllClientACL]
GO

CREATE PROCEDURE [dbo].[deleteAllClientACL]
AS	
	DELETE FROM clientACL  
GO

----- EMS 2.88_01, add table 'clientActionClassify'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[clientActionClassify]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[clientActionClassify](
		[id]             [int] NOT NULL,
	    [classification] [varchar](128) NOT NULL,
    CONSTRAINT [PK_clientActionClassify] PRIMARY KEY CLUSTERED 
    (
	    [id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY] 
END
GO

----- EMS 2.88_01, add table 'clientActionCode'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[clientActionCode]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[clientActionCode](
		[id]     [int] NOT NULL,
	    [action] [varchar](128) NOT NULL,
    CONSTRAINT [PK_clientActionCode] PRIMARY KEY CLUSTERED 
    (
	    [id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY] 
END
GO

----- EMS 2.88_01, add table 'clientActionContentCode'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[clientActionContentCode]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[clientActionContentCode](
		[id]   [int] NOT NULL,
	    [name] [varchar](32) NOT NULL,
    CONSTRAINT [PK_clientActionContentCode] PRIMARY KEY CLUSTERED 
    (
	    [id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY] 
END
GO

----- EMS 2.88_01, add table 'clientActionLog'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[clientActionLog]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[clientActionLog](
		[id]          [int] IDENTITY(1,1) NOT NULL,
	    [time]        [datetime] NOT NULL,
	    [client_id]   [int] NOT NULL,
	    [classify_id] [int] NOT NULL,
	    [action_id]   [int] NOT NULL,
	    [content]     [varchar](128) NOT NULL,
    CONSTRAINT [PK_clientActionLog] PRIMARY KEY CLUSTERED 
    (
	    [id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY]     
        
    ALTER TABLE [dbo].[clientActionLog]  WITH CHECK ADD  CONSTRAINT [FK_clientActionLog_client] FOREIGN KEY ([client_id]) 
    REFERENCES [dbo].[client] ([id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
    
    ALTER TABLE [dbo].[clientActionLog] CHECK CONSTRAINT [FK_clientActionLog_client] 
    
    ALTER TABLE [dbo].[clientActionLog]  WITH CHECK ADD  CONSTRAINT [FK_clientActionLog_clientActionClassify] FOREIGN KEY ([classify_id]) 
    REFERENCES [dbo].[clientActionClassify] ([id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
    
    ALTER TABLE [dbo].[clientActionLog] CHECK CONSTRAINT [FK_clientActionLog_clientActionClassify] 
    
    ALTER TABLE [dbo].[clientActionLog]  WITH CHECK ADD  CONSTRAINT [FK_clientActionLog_clientActionCode] FOREIGN KEY ([action_id]) 
    REFERENCES [dbo].[clientActionCode] ([id])
    ON UPDATE CASCADE
    ON DELETE CASCADE
    
    ALTER TABLE [dbo].[clientActionLog] CHECK CONSTRAINT [FK_clientActionLog_clientActionCode]
    
    -- insert action classification
    INSERT INTO clientActionClassify VALUES (1,'Login')
    INSERT INTO clientActionClassify VALUES (2,'Logout')
	INSERT INTO clientActionClassify VALUES (3,'By Role Function System')
	INSERT INTO clientActionClassify VALUES (4,'By Role Function Network')
	INSERT INTO clientActionClassify VALUES (5,'By Role Function Device')
	INSERT INTO clientActionClassify VALUES (6,'By Role Function Alarm')
	
	-- insert action code
	-- login
	INSERT INTO clientActionCode VALUES (101,'Client Login')
	INSERT INTO clientActionCode VALUES (102,'Login Failed, Wrong Username or Password')
	INSERT INTO clientActionCode VALUES (103,'Login Failed, ACL Match Failed')
	
	-- logout
	INSERT INTO clientActionCode VALUES (201,'Client Logout')
	INSERT INTO clientActionCode VALUES (202,'Idle Logout')
	INSERT INTO clientActionCode VALUES (203,'Loss Connect')
	INSERT INTO clientActionCode VALUES (204,'Force Logout, ACL Match Failed')
	
	-- by role function system
	INSERT INTO clientActionCode VALUES (301,'Edit Inventory')
    INSERT INTO clientActionCode VALUES (302,'Delete Inventory')
    INSERT INTO clientActionCode VALUES (303,'Check Duplicated SN')
    INSERT INTO clientActionCode VALUES (304,'PM Setting')
    INSERT INTO clientActionCode VALUES (305,'Enable Device PM')
    INSERT INTO clientActionCode VALUES (306,'Disable Device PM')
    
    -- by role function network
    INSERT INTO clientActionCode VALUES (401,'Add Tree') 
    INSERT INTO clientActionCode VALUES (402,'Add Node') 
    INSERT INTO clientActionCode VALUES (403,'Delete Node') 
    INSERT INTO clientActionCode VALUES (404,'Move Node Up') 
    INSERT INTO clientActionCode VALUES (405,'Move Node Down') 
    INSERT INTO clientActionCode VALUES (406,'Edit Name') 
    INSERT INTO clientActionCode VALUES (407,'Edit Role Access') 
    INSERT INTO clientActionCode VALUES (408,'Edit Alias') 
    INSERT INTO clientActionCode VALUES (409,'Topology Add Device Link') 
    INSERT INTO clientActionCode VALUES (410,'Topology Add Equip Link') 
    INSERT INTO clientActionCode VALUES (411,'Topology Edit Device Link') 
    INSERT INTO clientActionCode VALUES (412,'Topology Edit Equip Link') 
    INSERT INTO clientActionCode VALUES (413,'Topology Delete Device Link') 
    INSERT INTO clientActionCode VALUES (414,'Topology Delete Equip Link') 
    INSERT INTO clientActionCode VALUES (415,'Topology Map Setting') 
    INSERT INTO clientActionCode VALUES (416,'Topology Add Image') 
    INSERT INTO clientActionCode VALUES (417,'Topology Delete Image') 
    INSERT INTO clientActionCode VALUES (418,'Topology Import Image') 
    INSERT INTO clientActionCode VALUES (419,'Topology Map Scale') 
    INSERT INTO clientActionCode VALUES (420,'Topology Add Node') 
    INSERT INTO clientActionCode VALUES (421,'Topology Delete Node') 
    INSERT INTO clientActionCode VALUES (422,'Topology Drag Location Node')
    INSERT INTO clientActionCode VALUES (423,'Topology Drag Device Node') 
    INSERT INTO clientActionCode VALUES (424,'Topology Drag Equip Node') 
    INSERT INTO clientActionCode VALUES (425,'Topology Location Node Icon')
    INSERT INTO clientActionCode VALUES (426,'Topology Device Node Icon') 
    INSERT INTO clientActionCode VALUES (427,'Topology Equip Node Icon') 
    
    -- by role function device
    INSERT INTO clientActionCode VALUES (501,'Configure Parameter') 
    INSERT INTO clientActionCode VALUES (502,'Upgrade') 
    INSERT INTO clientActionCode VALUES (503,'Backup Parameter') 
    INSERT INTO clientActionCode VALUES (504,'Restore Parameter') 
    INSERT INTO clientActionCode VALUES (505,'Copy Parameter') 
    
    -- by role function alarm
    INSERT INTO clientActionCode VALUES (601,'Ack Alarm') 
    INSERT INTO clientActionCode VALUES (602,'Ack Trap')
    INSERT INTO clientActionCode VALUES (603,'Edit Device Alarm')
    INSERT INTO clientActionCode VALUES (604,'Edit Template Alarm')
    
    -- insert message code
    INSERT INTO clientActionContentCode VALUES (1,'Node')
    INSERT INTO clientActionContentCode VALUES (2,'Location')
    INSERT INTO clientActionContentCode VALUES (3,'Topology Device Link')
    INSERT INTO clientActionContentCode VALUES (4,'Topology Equip Link')
    INSERT INTO clientActionContentCode VALUES (5,'Alarm Log')
    INSERT INTO clientActionContentCode VALUES (6,'Trap Log')
    INSERT INTO clientActionContentCode VALUES (7,'Template Alarm')
    INSERT INTO clientActionContentCode VALUES (8,'Interval Minutes')
    INSERT INTO clientActionContentCode VALUES (9,'Parent')
    INSERT INTO clientActionContentCode VALUES (10,'Child')
    INSERT INTO clientActionContentCode VALUES (11,'Tree')
    INSERT INTO clientActionContentCode VALUES (12,'Alias')
    INSERT INTO clientActionContentCode VALUES (13,'Map Scale')
    INSERT INTO clientActionContentCode VALUES (14,'Map Image')
    INSERT INTO clientActionContentCode VALUES (15,'Position X')
    INSERT INTO clientActionContentCode VALUES (16,'Position Y')
    INSERT INTO clientActionContentCode VALUES (17,'Width')
    INSERT INTO clientActionContentCode VALUES (18,'Height')
    INSERT INTO clientActionContentCode VALUES (19,'Alarm Model')
END
GO

----- EMS 2.88_01, remove table 'clientAction', 'clientlog', 'clientlogact'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[clientAction]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
	IF OBJECT_ID(N'[tempdb].[dbo].[#order]') IS NOT NULL
		DROP TABLE #order

	CREATE TABLE #order (
		[time]        datetime,
		[client_id]   int,
	    [classify_id] int,
	    [action_id]   int,
	    [content]     varchar(128)
	)
	
	-- old table 'clientAction'
	-- by role function Device, classification id=5, agction id=501, content code=1
	INSERT INTO #order 
	SELECT [timestamp], [client_id], 5, 501, '1:'+CAST([agent_id] AS VARCHAR)+','+[action] AS msg 
	FROM clientAction  
	
	-- old table 'clientlog'
	-- login/logout, classification id=1/2, action id=101/201
	INSERT INTO #order 
	SELECT [timestamp], [client_id], 1, 101, [client_ip] 
	FROM clientlog 
	WHERE code=0 
	
	INSERT INTO #order 
	SELECT [timestamp], [client_id], 2, 201, [client_ip] 
	FROM clientlog  
	WHERE code=1 
	
	-- move data to new table 'clientActionLog'
	INSERT INTO clientActionLog ([time],[client_id],[classify_id],[action_id],[content])
	SELECT * FROM #order ORDER BY [time] 
	
	DROP TABLE #order 
	DROP TABLE clientAction 
	DROP TABLE clientlog 
	DROP TABLE clientlogact 

END
GO

----- EMS 2.88_01, remove procedure 'admin_clientlog_clear'
----- EMS 2.88_01, remove procedure 'admin_clientaction_clear'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_clientlog_clear]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_clientlog_clear]
GO
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[admin_clientaction_clear]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[admin_clientaction_clear]
GO

----- EMS 2.88_01, to avoid clientActionLog content parse error, repalce (space,comma,colon,brackets,quote) with '_'
----- EMS 2.88_01, modify table 'alias' column 'name', repalce (space,comma,colon,brackets,quote) with '_' 
----- EMS 2.88_01, modify table 'nodes' column 'name', id>1000, repalce (space,comma,colon,brackets,quote) with '_' 
----- EMS 2.88_01, modify table 'topologyEquip' column 'name', repalce (space,comma,colon,brackets,quote) with '_'  
----- EMS 2.88_01, modify table 'topologyEquipLink' column 'name2', repalce (space,comma,colon,brackets,quote) with '_'  
DECLARE @nodeId int, @rackId int, @siteId int, @index int, @name varchar(256), @new varchar(256), @tmp varchar(256), @i int 
DECLARE cur CURSOR FOR (SELECT node_id,rack_id,site_id,idx,name FROM alias)   
OPEN cur                                                                                         
FETCH NEXT FROM cur INTO @nodeId,@rackId,@siteId,@index,@name                     
WHILE @@FETCH_STATUS=0                         
BEGIN
	IF ([dbo].[fn_isHasIllegalChar](@name))=1
	BEGIN
		SET @i = 1
		SET @new = [dbo].[fn_rmvIllegalChar](@name)
		SET @tmp = @new 
		WHILE((SELECT TOP(1) name FROM alias WHERE name=@tmp) IS NOT NULL)
		BEGIN		
			SET @tmp = @new + '-' +CAST(@i AS varchar) 
			SET @i = @i+1
		END
	
		UPDATE alias SET name=@tmp WHERE node_id=@nodeId AND rack_id=@rackId AND site_id=@siteId AND idx=@index 
	END 
	
	FETCH NEXT FROM cur INTO @nodeId,@rackId,@siteId,@index,@name 
END  
CLOSE cur  
DEALLOCATE cur 

GO

DECLARE @id int, @name varchar(256), @new varchar(256), @tmp varchar(256), @i int 
DECLARE cur CURSOR FOR (SELECT id,name FROM nodes WHERE id>1000)   
OPEN cur                                                                                         
FETCH NEXT FROM cur INTO @id,@name                     
WHILE @@FETCH_STATUS=0                         
BEGIN
	IF ([dbo].[fn_isHasIllegalChar](@name))=1
	BEGIN
		SET @i = 1
		SET @new = [dbo].[fn_rmvIllegalChar](@name)
		SET @tmp = @new 
		WHILE((SELECT TOP(1) name FROM nodes WHERE name=@tmp AND id>1000) IS NOT NULL)
		BEGIN		
			SET @tmp = @new + '-' +CAST(@i AS varchar) 
			SET @i = @i+1
		END
	
		UPDATE nodes SET name=@tmp WHERE id=@id 
	END 
	
	FETCH NEXT FROM cur INTO @id,@name  
END  
CLOSE cur  
DEALLOCATE cur  

GO

DECLARE @treeId int, @nodeId int, @name varchar(256), @new varchar(256), @tmp varchar(256), @i int 
DECLARE cur CURSOR FOR (SELECT tree_id,node_id,name FROM topologyEquip)   
OPEN cur                                                                                         
FETCH NEXT FROM cur INTO @treeId,@nodeId,@name                     
WHILE @@FETCH_STATUS=0                         
BEGIN
	IF ([dbo].[fn_isHasIllegalChar](@name))=1
	BEGIN
		SET @i = 1
		SET @new = [dbo].[fn_rmvIllegalChar](@name)
		SET @tmp = @new 
		WHILE((SELECT TOP(1) name FROM topologyEquip WHERE name=@tmp) IS NOT NULL)
		BEGIN		
			SET @tmp = @new + '-' +CAST(@i AS varchar) 
			SET @i = @i+1
		END
	
		UPDATE topologyEquip SET name=@tmp WHERE tree_id=@treeId AND node_id=@nodeId AND name=@name 
		UPDATE topologyEquipLink SET name2=@tmp WHERE tree_id=@treeId AND node_id2=@nodeId AND name2=@name 
	END 
	
	FETCH NEXT FROM cur INTO @treeId,@nodeId,@name  
END 
CLOSE cur 
DEALLOCATE cur 

GO

----- EMS 2.88_01, add procedure 'getAgentIds'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getAgentIds]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getAgentIds]
GO

CREATE PROCEDURE [dbo].[getAgentIds]
@name varchar(100) 
AS	
	SELECT id FROM nodes WHERE id>1000 AND id IN (SELECT id FROM [dbo].[fn_getAllowedNodesByUserName](@name)) 
GO


----- EMS 2.90_01, add table 'timeSynchornizer'
IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[timeSynchornizer]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    CREATE TABLE [dbo].[timeSynchornizer](
		[id]     [int] NOT NULL,
	    [name]   [varchar](128) NOT NULL,
    CONSTRAINT [PK_timeSynchornizer] PRIMARY KEY CLUSTERED 
    (
	    [id] ASC
    )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
    ) ON [PRIMARY] 
    
    INSERT INTO timeSynchornizer VALUES (0,'disable')
    INSERT INTO timeSynchornizer VALUES (1,'sync by NTP server')
    INSERT INTO timeSynchornizer VALUES (2,'sync by EMS server')
END
GO

----- EMS 2.90_01, add procedure 'getAgentTimeSyncer'
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[getAgentTimeSyncer]') AND OBJECTPROPERTY(id, N'IsProcedure')=1 )
	DROP PROCEDURE [dbo].[getAgentTimeSyncer]
GO

CREATE PROCEDURE [dbo].[getAgentTimeSyncer]
@name varchar(100)
AS	
	SELECT id, syncTime 
	FROM agent 
	WHERE id IN (SELECT id FROM [dbo].[fn_getAllowedNodesByUserName](@name))
	ORDER BY ip_address
GO

----- EMS 2.90_01, add procedure 'editAgentTimeSyncer'
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id=OBJECT_ID(N'[dbo].[editAgentTimeSyncer]') AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[editAgentTimeSyncer]
GO

CREATE PROCEDURE [dbo].[editAgentTimeSyncer] 
	@id   int,
	@type int
	
AS

	UPDATE agent
		SET syncTime=@type WHERE id=@id

GO


----- EMS 2.90_01, modify table 'nodes', change 'name' length 100 to 768. UI length 128, DB needs 768.
----- EMS 2.90_01, modify table 'alias', change 'name' length 200 to 768. UI length 128, DB needs 768.
----- EMS 2.90_01, modify table 'inventoryListByServer', change 'alias' length 128 to 768. UI length 128, DB needs 768.

IF EXISTS (SELECT * FROM syscolumns WHERE name='name' and id=OBJECT_ID('nodes'))
BEGIN	
	IF (select CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='nodes' and COLUMN_NAME='name' ) < 768 	
	BEGIN 
		ALTER TABLE nodes ALTER COLUMN [name] VARCHAR(768) 
	END
END

IF EXISTS (SELECT * FROM syscolumns WHERE name='name' and id=OBJECT_ID('alias'))
BEGIN	
	IF (select CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='alias' and COLUMN_NAME='name' ) < 768 	
	BEGIN 
		ALTER TABLE alias ALTER COLUMN [name] VARCHAR(768) 
	END
END

IF EXISTS (SELECT * FROM syscolumns WHERE name='alias' and id=OBJECT_ID('inventoryListByServer'))
BEGIN	
	IF (select CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='inventoryListByServer' and COLUMN_NAME='alias' ) < 768 	
	BEGIN 
		ALTER TABLE inventoryListByServer ALTER COLUMN [alias] VARCHAR(768) 
	END
END
GO

----- EMS 2.97_01, modify table 'userRole', change 'name' and 'description' length to 768. UI length 128, DB needs 768.
IF EXISTS (SELECT * FROM syscolumns WHERE name='name' and id=OBJECT_ID('userRole'))
BEGIN	
	IF (select CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='userRole' and COLUMN_NAME='name' ) < 768 	
	BEGIN 
		ALTER TABLE userRole ALTER COLUMN [name] VARCHAR(768) 
	END
END

IF EXISTS (SELECT * FROM syscolumns WHERE name='description' and id=OBJECT_ID('userRole'))
BEGIN		
	IF (select CHARACTER_MAXIMUM_LENGTH from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME='userRole' and COLUMN_NAME='description' ) < 768 	
	BEGIN 
		ALTER TABLE userRole ALTER COLUMN [description] VARCHAR(768) 
	END
END




----- EMS 2.92_01, modify table 'alarmTemplate', add FRM220A template type 56,57
----- EMS 2.100_01, modify table 'alarmTemplate', add NMC-R4 template type 65
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[alarmTemplate]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
    IF NOT EXISTS (SELECT * FROM [dbo].[alarmTemplate] WHERE [id]='41' AND [type]='56')
        INSERT INTO alarmTemplate VALUES(41, 0, 56, 1, 4, 1, '') -- ALARM_CPU_TEMPERATURE_ABNORMAL(56), SEVERITY_MINOR(4)

    IF NOT EXISTS (SELECT * FROM [dbo].[alarmTemplate] WHERE [id]='41' AND [type]='57')
        INSERT INTO alarmTemplate VALUES(41, 0, 57, 1, 4, 1, '') -- ALARM_BOARD_TEMPERATURE_ABNORMAL(57), SEVERITY_MINOR(4)

    IF NOT EXISTS (SELECT * FROM [dbo].[alarmTemplate] WHERE [id]='1048' AND [type]='65')
    BEGIN
        DECLARE @cnt INT
        SET @cnt = 1
	    WHILE (@cnt <= 8)
	    BEGIN		
            INSERT INTO alarmTemplate VALUES(1048,0,65, @cnt, 5,1,'')  -- ALARM_CARD_UNPLUG(65), SEVERITY_WARNING(5)
        
            SET @cnt = @cnt + 1
        END   
    END
END
GO

----- EMS 2.93_01, modify table 'clientACL', add empty ip/mac for users not in white list
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[clientACL]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
	INSERT INTO clientACL 
	SELECT id,'','' FROM client 
	WHERE id NOT IN (SELECT client_id FROM clientACL)
END
GO

----- EMS 2.94_01, modify table 'timeSynchornizer', add rows disable/ntp/ems
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id=OBJECT_ID(N'[dbo].[timeSynchornizer]') AND OBJECTPROPERTY(id, N'IsUserTable')=1 )
BEGIN
	IF NOT EXISTS (SELECT * FROM [dbo].[timeSynchornizer] WHERE [id]='0')
		INSERT INTO timeSynchornizer VALUES(0, 'disable')	
	
	IF NOT EXISTS (SELECT * FROM [dbo].[timeSynchornizer] WHERE [id]='1')
		INSERT INTO timeSynchornizer VALUES(1, 'sync. with NTP server')	

	IF NOT EXISTS (SELECT * FROM [dbo].[timeSynchornizer] WHERE [id]='2')
		INSERT INTO timeSynchornizer VALUES(2, 'sync. with EMS server')	
END
GO

----- EMS 2.99_01, add new alarm template NMC-R3 line card Eoe1/GS
----- EMS 2.99_01, add new alarm template for NMC-R3 line card OPS51
DECLARE @cnt INT  -- loop counter
DECLARE @dvc INT  -- device type or card Id
DECLARE @sid INT
DECLARE @ena INT
	    
SET @sid = 0  -- 0 for local, not used so far (2014-0807), no model needs another template for remtoe. New template may need it some day.
SET @ena = 1  -- default 1 to enable alarm
    
----- MODEL_EOE1GS(1052)
SET @dvc = 1052

IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,3,  1, 5,@ena,'')    -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,13, 1, 3,@ena,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,12, 1, 4,@ena,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,14, 1, 4,@ena,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)		
	
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,58, 1, 7,@ena,'') -- ALARM_LOOPBACK_TEST(58), SEVERITY_TESTING(7)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,59, 1, 7,@ena,'') -- ALARM_BERT_TEST(59), SEVERITY_TESTING(7)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,60, 1, 7,@ena,'') -- ALARM_BERT_TEST_HAS_ERROR(60), SEVERITY_TESTING(7)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,63, 1, 5,@ena,'') -- ALARM_E1_LOS(63), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,64, 1, 5,@ena,'') -- ALARM_E1_LOF(64), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,28, 1, 5,@ena,'') -- ALARM_E1_AIS_ON(28), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,29, 1, 5,@ena,'') -- ALARM_E1_RAI_ON(29), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,61, 1, 5,@ena,'') -- ALARM_E1_CRC_ON(61), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,62, 1, 5,@ena,'') -- ALARM_E1_BPV_ON(62), SEVERITY_WARNING(5)
END

----- MODEL_OPS51(1053)
SET @dvc = 1053

IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN    
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,53, 1, 3,@ena,'')  -- ALARM_WORKPATH_SIGLOSS(53), SEVERITY_MAJOR(3)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,54, 1, 5,@ena,'')  -- ALARM_PRI_CHAN_SIGLOSS(54), SEVERITY_WARNING(5)
	INSERT INTO alarmTemplate VALUES(@dvc,@sid,55, 1, 5,@ena,'')  -- ALARM_SEC_CHAN_SIGLOSS(55), SEVERITY_WARNING(5)			            	
END

----- CARD_OAB15(1055)
SET @dvc = 1055

IF( (SELECT COUNT(*) FROM alarmTemplate WHERE id=@dvc) = 0)
BEGIN
	INSERT INTO alarmTemplate VALUES(@dvc, @sid,  9, 1, 4, 1, '')  -- ALARM_ALARM_ON(9), SEVERITY_MINOR(4)
	INSERT INTO alarmTemplate VALUES(@dvc, @sid, 66, 1, 4, 1, '')  -- ALARM_PUMP_INACTIVE(66), SEVERITY_MINOR(4)
END
GO

----- EMS 2.101, table 'alarmTemplate', add id 1055 FRM220-OAB15 template.
IF NOT EXISTS (SELECT * FROM [dbo].[alarmTemplate] WHERE id=1055)
BEGIN
	INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(1055, 0,  9, 1, 4, 1,'')  -- ALARM_ALARM_ON(9), SEVERITY_MINOR(4)
	INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(1055, 0, 66, 1, 4, 1,'')  -- ALARM_PUMP_INACTIVE(66), SEVERITY_MINOR(4)
END
GO

----- EMS 2.102, table 'alarmTemplate', add IGS-1608SM-8PH
IF NOT EXISTS (SELECT * FROM [dbo].[alarmTemplate] WHERE id=96)
BEGIN
    DECLARE @i INT
    
    SET @i=1
    WHILE (@i <= 2)   
    BEGIN
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(96, 0, 1, @i, 4, 1,'')  -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
        SET @i=@i+1
    END
    
    INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(96, 0, 4, 1, 4, 1,'')  -- ALARM_FAULT_ON(4), SEVERITY_MINOR(4)  
    
    SET @i=1
    WHILE (@i <= 16)   
    BEGIN
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(96, 0, 2, @i, 5, 1,'') -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
        SET @i=@i+1
    END

    SET @i=1
    WHILE (@i <= 8)   
    BEGIN
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(96, 0, 3, @i, 5, 1,'')     -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(96, 0, 12, @i, 4, 1,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(96, 0, 13, @i, 3, 1,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(96, 0, 14, @i, 4, 1,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)
        SET @i=@i+1
    END

    SET @i=1
    WHILE (@i <= 5)   
    BEGIN
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(96, 0, 7, @i, 4, 1,'')  -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)
        SET @i=@i+1
    END
    
    SET @i=1
    WHILE (@i <= 8)   
    BEGIN
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(96, 0, 5, @i, 3, 1,'') -- ALARM_POEBUDGET_EXCEED(5), SEVERITY_MAJOR(3)  
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(96, 0, 6, @i, 3, 1,'') -- ALARM_POEPD_OVERLOAD(6), SEVERITY_MAJOR(3) 
        SET @i=@i+1
    END
END
GO

----- EMS 2.102, table 'alarmTemplate', add IFS-1608GSM-8PH
IF NOT EXISTS (SELECT * FROM [dbo].[alarmTemplate] WHERE id=97)
BEGIN
    DECLARE @i INT
    
    SET @i=1
    WHILE (@i <= 2)   
    BEGIN
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(97, 0, 1, @i, 4, 1,'')  -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
        SET @i=@i+1
    END
    
    INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(97, 0, 4, 1, 4, 1,'')  -- ALARM_FAULT_ON(4), SEVERITY_MINOR(4)  
    
    SET @i=1
    WHILE (@i <= 16)   
    BEGIN
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(97, 0, 2, @i, 5, 1,'') -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
        SET @i=@i+1
    END

    SET @i=1
    WHILE (@i <= 8)   
    BEGIN
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(97, 0, 3, @i, 5, 1,'')     -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(97, 0, 12, @i, 4, 1,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(97, 0, 13, @i, 3, 1,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(97, 0, 14, @i, 4, 1,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)
        SET @i=@i+1
    END

    SET @i=1
    WHILE (@i <= 5)   
    BEGIN
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(97, 0, 7, @i, 4, 1,'')  -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)
        SET @i=@i+1
    END
    
    SET @i=1
    WHILE (@i <= 8)   
    BEGIN
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(97, 0, 5, @i, 3, 1,'') -- ALARM_POEBUDGET_EXCEED(5), SEVERITY_MAJOR(3)  
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(97, 0, 6, @i, 3, 1,'') -- ALARM_POEPD_OVERLOAD(6), SEVERITY_MAJOR(3) 
        SET @i=@i+1
    END
END
GO

----- EMS 2.102, table 'alarmTemplate', add IGS-1608SM-SE
IF NOT EXISTS (SELECT * FROM [dbo].[alarmTemplate] WHERE id=98)
BEGIN
    DECLARE @i INT
    
    SET @i=1
    WHILE (@i <= 2)   
    BEGIN
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(98, 0, 1, @i, 4, 1,'')  -- ALARM_POWER_OFF(1), SEVERITY_MINOR(4)
        SET @i=@i+1
    END
    
    INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(98, 0, 4, 1, 4, 1,'')  -- ALARM_FAULT_ON(4), SEVERITY_MINOR(4)  
    
    SET @i=1
    WHILE (@i <= 16)   
    BEGIN
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(98, 0, 2, @i, 5, 1,'') -- ALARM_UTPLINK_DOWN(2), SEVERITY_WARNING(5)
        SET @i=@i+1
    END

    SET @i=1
    WHILE (@i <= 8)   
    BEGIN
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(98, 0, 3, @i, 5, 1,'')     -- ALARM_FIBERLINK_DOWN(3), SEVERITY_WARNING(5)
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(98, 0, 12, @i, 4, 1,'-30') -- ALARM_FIBER_RX_POWER_LOW(12), SEVERITY_MINOR(4)
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(98, 0, 13, @i, 3, 1,'')    -- ALARM_FIBER_RX_POWER_ERROR(13), SEVERITY_MAJOR(3)
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(98, 0, 14, @i, 4, 1,'80')  -- ALARM_FIBER_TEMPERATURE_ABNORMAL(14), SEVERITY_MINOR(4)
        SET @i=@i+1
    END

    SET @i=1
    WHILE (@i <= 5)   
    BEGIN
        INSERT INTO alarmTemplate (id, side, type, idx, severity, enable, param) VALUES(98, 0, 7, @i, 4, 1,'')  -- ALARM_RING_FAULT(7), SEVERITY_MINOR(4)
        SET @i=@i+1
    END
END
GO



-----------------------------------------------------------------------------------------------
----- procedure 'insertToTemplate'
----- procedure 'insertToBatch'
----- procedure 'insertAgentCSJT'
----- procedure 'insertAgent10'
----- procedure 'removeTemplate'
----- procedure 'removeFromTemplate'
----- procedure 'admin_agentNodeInsert10'
----- procedure 'getTemplates'
----- procedure 'getBatches'
----- procedure 'get_Worker'
----- procedure 'createTemplate'
----- procedure 'createBatch'
-----
----- 2015-0320 
----- The above procedures are not used in source code (EMSv281), but still contain acl inside.
-----------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------
