<?php

$startTime = microtime(true);

require "_trinity.php";
MySTART();

define("USE_CONDITIONS", !! MyVAL("SHOW TABLES LIKE 'conditions'"));
define("USE_DBSCRIPTS", !! MyVAL("SHOW TABLES LIKE 'dbscripts_on_%'"));
define("FIRST_RUN", MyVAL("SELECT COUNT(*) FROM creature_template WHERE dmg_multiplier!=1") < 1000);

$creature_classic_rare = /* + marks RareElite */ <<<EOT
"7:XT", "Accursed Slitherblade", "Achellios the Banished", +"Aean Swiftriver", "Akkrilus", "Akubar the Seer", "Alshirr Banebreath", +"Ambassador Bloodrage", +"Anathemus", "Antilos", "Antilus the Soarer", "Apothecary Falthis", "Araga", "Arash-ethis", +"Azshir the Sleepless", +"Azurous", "Azzere the Skyblade", +"Bannok Grimaxe", "Barnabus", "Baron Bloodbane", "Bayne", "Big Samras", "Bjarn", "Blackmoss the Fetid", +"Blind Hunter", "Bloodroar the Stalker", +"Boahn", "Boss Galgosh", "Boulderheart", "Brack", "Brainwashed Noble", "Branch Snapper", +"Brimgore", "Broken Tooth", "Brokespear", +"Brontus", +"Brother Ravenoak", +"Bruegal Ironknuckle", "Burgle Eye", +"Burning Felguard", +"Captain Flat Tusk", +"Captain Gerogg Hammertoe", "Carnivous the Breaker", "Chatter", "Clack the Reaver", "Clutchmother Zavas", "Commander Felstrom", "Cranky Benj", "Creepthess", "Crusty", +"Crystal Fang", "Cursed Centaur", "Cyclok the Mad", "Dalaran Spellscribe", +"Darbel Montrose", +"Dark Iron Ambassador", "Darkmist Widow", "Darkslayer Mordenthal", "Dart", "Death Flayer", "Death Howl", "Deatheye", "Deathmaw", "Deathspeaker Selendre", +"Deathsworn Captain", "Deeb", +"Dessecus", +"Deviate Faerie Dragon", "Diamond Head", "Digger Flameforge", +"Digmaster Shovelphlange", "Dishu", "Dragonmaw Battlemaster", "Dreadscorn", "Dreadwhisper", "Drogoth the Roamer", "Duggan Wildhammer", "Duskstalker", +"Dustwraith", +"Earthcaller Halmgar", "Eck'alom", "Edan the Howler", +"Elder Mystic Razorsnout", +"Emogg the Crusher", "Enforcer Emilgund", "Engineer Whirleygig", +"Fallen Champion", "Farmer Solliden", "Faulty War Golem", "Fedfennel", "Fellicent's Shade", +"Felweaver Scornn", "Fenros", "Fingat", "Firecaller Radison", "Flagglemurk the Cruel", "Foe Reaper 4000", "Foreman Grills", +"Foreman Jerris", "Foreman Marcrid", +"Foreman Rigger", +"Foulbelly", "Foulmane", "Fury Shelda", "Garneg Charskull", "Gatekeeper Rageroar", +"General Colbatann", "General Fangferror", "Geolord Mottle", "Geomancer Flintdagger", "Geopriest Gukk'rok", +"Gesharahan", +"Ghok Bashguud", "Ghost Howl", "Gibblesnik", "Gibblewilt", "Giggler", "Gilmorian", "Gish the Unmoving", "Gluggle", "Gnarl Leafbrother", "Gnawbone", +"Goraluk Anvilcrack", "Gorefang", "Gorgon'och", "Gosh-Haldir", "Gravis Slipknot", "Great Father Arctikus", "Greater Firebird", "Gretheer", "Grimmaw", +"Grimungous", "Grizlak", "Grizzle Snowpaw", "Grubthor", +"Gruff", "Gruff Swiftbite", "Gruklash", "Grunter", "Gug Fatcandle", "Haarka the Ravenous", +"Hagg Taurenbane", "Hahk'Zor", "Hammerspine", +"Hannah Bladeleaf", "Harb Foulmountain", "Hayoc", +"Hearthsinger Forresten", +"Heartrazor", "Hed'mush the Rotting", "Heggin Stonewhisker", +"Hematos", +"High General Abbendis", +"High Priestess Hai'watna", +"Highlord Mastrogonde", "Hissperak", +"Humar the Pridelord", "Huricanian", +"Immolatus", "Ironback", +"Ironeye the Invincible", +"Ironspine", "Jade", "Jalinde Summerdrake", +"Jed Runewatcher", "Jimmy the Bleeder", +"Jin'Zallah the Sandbringer", +"Kashoch the Reaver", "Kaskk", "Kazon", +"King Mosh", "Kovork", "Kregg Keelhaul", "Krellack", "Krethis Shadowspinner", "Kurmokk", +"Lady Hederine", "Lady Moongazer", "Lady Sesspira", "Lady Szallah", "Lady Vespia", "Lady Vespira", "Lady Zephris", +"Lapress", "Large Loch Crocolisk", "Leech Widow", "Leprithus", "Licillin", "Lo'Grosh", "Lord Angler", +"Lord Captain Wyrmak", "Lord Condar", "Lord Darkscythe", +"Lord Hel'nurath", "Lord Malathrom", "Lord Maldazzar", "Lord Sakrasis", "Lord Sinslayer", "Lost One Chieftain", "Lost One Cook", "Lost Soul", "Lupos", "Ma'ruk Wyrmscale", "Magister Hawkhelm", "Magosh", "Magronos the Unyielding", "Malfunctioning Reaver", "Malgin Barleybrew", +"Marcus Bel", "Marina DeSirrus", "Marisa du'Paige", "Master Digger", "Master Feardred", "Mazzranache", +"Meshlok the Harvester", "Mezzir the Howler", +"Miner Johnson", "Mirelow", "Mist Howler", +"Mith'rethis the Enchanter", "Mojo the Twisted", "Molok the Crusher", "Molt Thorn", "Mongress", +"Monnos the Elder", "Morgaine the Sly", "Morick Darkbrew", "Mosh'Ogg Butcher", "Mother Fang", "Muad", "Mugglefin", "Murderous Blisterpaw", +"Mushgog", +"Nal'taszar", "Naraxis", "Narg the Taskmaster", +"Narillasanz", "Nefaru", +"Nerubian Overseer", "Nimar the Slayer", "Oakpaw", "Old Cliff Jumper", "Old Grizzlegut", "Old Vicejaw", "Olm the Wise", "Omgorn the Lost", "Oozeworm", +"Panzor the Invincible", "Pridewing Patriarch", "Prince Kellen", "Prince Nazjak", "Prince Raze", +"Putridius", +"Pyromancer Loregrain", "Qirot", "Ragepaw", "Ragglesnout", "Rak'shiri", "Ranger Lord Hawkspear", "Rathorian", "Ravage", "Ravasaur Matriarch", "Ravenclaw Regent", "Razormaw Matriarch", "Razortalon", "Rekk'tilac", "Ressan the Needler", "Retherokk the Berserker", +"Rex Ashil", "Ribchaser", "Rippa", "Ripscale", "Ro'Bark", +"Rocklance", "Rohh the Silent", "Roloch", "Rorgish Jowl", "Rot Hide Bruiser", "Rumbler", +"Ruul Onestone", +"Sandarr Dunereaver", "Scald", "Scale Belly", +"Scalebeard", "Scargil", +"Scarlet Executioner", +"Scarlet High Clerist", +"Scarlet Interrogator", "Scarlet Judge", "Scarlet Smith", +"Scarshield Quartermaster", "Seeker Aqualon", +"Sentinel Amarassan", "Sergeant Brashclaw", +"Setis", "Sewer Beast", "Shadowclaw", "Shadowforge Commander", "Shanda the Spinner", "Shleipnarr", +"Siege Golem", "Silithid Harvester", "Silithid Ravager", "Singer", +"Sister Hatelash", +"Sister Rathtalon", +"Sister Riven", +"Skarr the Unbreakable", "Skhowl", +"Skul", "Slark", "Slave Master Blackheart", "Sludge Beast", "Sludginn", "Smoldar", "Snagglespear", "Snarler", "Snarlflare", "Snarlmane", "Snort the Heckler", "Soriid the Devourer", +"Sorrow Wing", +"Spirestone Battle Lord", +"Spirestone Butcher", +"Spirestone Lord Magus", "Spiteflayer", "Squiddic", "Sri'skulk", "Stone Fury", "Stonearm", +"Stonespine", "Strider Clutchmother", +"Swiftmane", +"Swinegart Spearhide", +"Takk the Leaper", +"Tamra Stormpike", +"Taskmaster Whipfang", "Terrorspark", "Terrowulf Packlord", "Thauris Balgarr", "The Behemoth", "The Evalcharr", "The Husk", "The Ongar", "The Rake", +"The Razza", "The Reak", "The Rot", "The Unknown Soldier", +"Thora Feathermoon", "Threggil", "Thunderstomp", "Thuros Lightfingers", "Timber", "Tormented Spirit", "Trigore the Lasher", +"Tsu'zee", "Twilight Lord Everun", "Uhk'loc", "Ursol'lok", "Uruson", "Varo'then's Ghost", "Vengeful Ancient", +"Verek", "Verifonix", "Veyzhak the Cannibal", +"Vile Sting", +"Volchan", "Vultros", "War Golem", +"Warder Stilgiss", +"Warleader Krazzilak", "Warlord Kolkanis", "Warlord Thresh'jin", "Watch Commander Zalaphil", "Witherheart the Stalker", "Zalas Witherbark", +"Zaricotl", "Zekkis", +"Zerillis", +"Zora", "Zul'arek Hatefowler", "Zul'Brin Warpbranch"
EOT;

// Список совпадает с объединением перечислений номеров карт подземелий в TweakCreatureDmgHP()
$InstancedMaps = "33,34,36,43,47,48,70,90,109,129,189,209,229,230,249,269,289,309,329,349,389,409,429,469,509,531,532,533,534,540,542,543,544,545,546,547,548,550,552,553,554,555,556,557,558,560,564,565,568,574,575,576,578,580,585,595,599,600,601,602,603,604,608,615,616,619,624,631,632,649,650,658,668,724";


///////////////////////// HELPER FUNCTIONS

function IsNotRepack($rpname)
{
  return $GLOBALS['repack'] != "" and $GLOBALS['repack'] != $rpname;
}

function PrintHeader($fnname)
{
  global $count; $count = null;
  static $sections = 0;
  if ($sections++ != 0) echo "\n";
  echo ":::::: $fnname()\n";
}

function Logs($format, $arg1=null, $arg2=null, $arg3=null)
{
  global $count, $countTotal;
  if ($arg1 === null)
     $arg1 = $count !== null ? $count : mysql_affected_rows();
  printf(" ■ $format\n", $arg1, $arg2, $arg3);
  $countTotal += @$arg1;
  $count = null;
  // Сбрасывать через unset($count) нельзя, т.к. рвётся связь между глобальной
  // переменной и той, что объявлена через global $count внутри функций
  // Значение null считается за 0 в числовых операциях (no error/warning)
}


function RetrieveArmorLimits()
{
$armorLimits = array();

$res = MyOP("SELECT InventoryType, ItemLevel, MIN(armor) AS MinArmor FROM item_template WHERE InventoryType IN (1,3,5,6,7,8,9,10) AND class=4 AND IF(ItemLevel<40, subclass=3, subclass=4) GROUP BY InventoryType, ItemLevel");

while($calc = mysql_fetch_object($res))
  $armorLimits[$calc->InventoryType][$calc->ItemLevel] = $calc->MinArmor;

$res = MyOP("SELECT InventoryType, ItemLevel, MAX(subclass) AS MaxSC, COUNT(subclass) AS BadCount FROM item_template WHERE InventoryType IN (1,3,5,6,7,8,9,10) AND class=4 AND subclass IN (1,2,3,4) AND armor>=2 GROUP BY InventoryType, ItemLevel");

while($calc = mysql_fetch_object($res))
  if ($calc->ItemLevel < 40 ? $calc->MaxSC < 3 : $calc->MaxSC < 4)
      $armorLimits[$calc->InventoryType][$calc->ItemLevel] = -max($calc->BadCount,1);

$MaxIL = 92;
$nGroups = 0; $nPonded = 0;
$myCase = "CASE InventoryType";

foreach(array(1,3,5,6,7,8,9,10,20) as $inv) {
  $myCase .= "\nWHEN $inv then CASE ItemLevel";
  for($IL = 1; $IL <= $MaxIL; $IL++) {
    $lim = @$armorLimits[$inv == 20 ? 5 : $inv][$IL];
    if ($lim === null)  continue;
    if ($lim >= 0)
        $myCase .= " WHEN $IL then $lim";
    else {
        for($l = $IL; $l <= $MaxIL; $l++) {
            $upLim = @$armorLimits[$inv == 20 ? 5 : $inv][$l];
            if ($upLim === null or $upLim < 0) continue;
            $myCase .= " WHen $IL then ". max($upLim - ($l - $IL), 0);
            break;
        }
        //global $item_invslot; echo " ! NO Mail/Plate ($inv)$item_invslot[$inv] IL $IL {", -$lim, "}", ($l < $MaxIL ? " -- use [+".($l - $IL)."]" : ""), "\n";
        ++$nPonded;
    }
    ++$nGroups;
  }
  $myCase .= " ELSE 99999 END";
}
$myCase .= "\nELSE 99999 END\n";

//printf(" ! Armor Limits retrieved: %d groups, %d ponded\n", $nGroups, $nPonded);
return $myCase;
}



///////////////////////// BUNDLE FUNCTIONS

function FixGeneral()
{
global $count; PrintHeader(__FUNCTION__);

if (FIRST_RUN)
{
MyOP("UPDATE creature_template SET mindmg=FLOOR(mindmg*dmg_multiplier), maxdmg=FLOOR(maxdmg*dmg_multiplier), dmg_multiplier=1.0 WHERE dmg_multiplier!=1");
Logs("Got rid of dmg_multiplier!=1 in creature_template TABLE: %d creatures");

$count = MyRUN("
SET @GUID=(SELECT (MAX(guid) DIV 1000000 + 1)*1000000 FROM creature);
INSERT creature SET guid=@GUID, id=10685, map=1, position_x=16247, position_y=16383, position_z=47.12, orientation=4.62, spawntimesecs=180, spawndist=15, curhealth=14, curmana=0, MovementType=1; -- Swine
");
Logs("Add a critter (GM Island) to set stable starting value for new GUIDs dynamically added into `creature` table: %d creatures" );
}

MyOP("UPDATE areatrigger_teleport SET target_map=0, target_position_x=-7515.64, target_position_y=-1045.3, target_position_z=182.3, target_orientation=0.6 WHERE id=2890");
Logs("Fix/change Molten Core exit destination from BRD, Molten Bridge to Blackrock Mountain, near Lothos Riftwalker");


MyOP("UPDATE areatrigger_teleport SET target_position_x=-7556.231445, target_position_y=-1317.583008, target_position_z=258.035492, target_orientation=1.2 WHERE name='Blackrock Spire - Fall out' AND target_map=0");
Logs("Fix/change LBRS fall out teleport destination: %d locations");


$count = MyRUN("
UPDATE instance_template SET parent=230 WHERE map=409; -- BRD leads to MC
UPDATE instance_template SET parent=229 WHERE map=469; -- BRS leads to BWL
");
Logs("Fix/ghosts of players killed in Molten Core and BWL can return through BRD and BRS: %d instances" );


MyOP("UPDATE spell_affect SET SpellFamilyMask=SpellFamilyMask|512|33554432 WHERE entry IN (20101,20102,20103,20104,20105)");
Logs("Fix talent Paladin:Benediction, 5 ranks, to affect Seal of the Crusader and Seal of Command: %d spells");

$count = MyRUN("
UPDATE spell_affect SET SpellFamilyMask=0x1007F100E3FEFF WHERE entry=16870 AND SpellFamilyMask=0x1007F100E3FF04; -- from Omen of Clarity (Druid)
-- INSERT IGNORE spell_affect SET entry=16246, SpellFamilyMask=0x90100003; -- from Elemental Focus (Shaman) - избыточно, есть в DBC
");
Logs("Fix sets of spells affected by Clearcasting from Omen of Clarity (Druid): %d rows" );

$count = MyRUN("
REPLACE spell_proc_event SET entry=19228, SpellFamilyName=9, SpellFamilyMask0=64,  SpellFamilyMask1=64,  SpellFamilyMask2=64; -- Improved Wing Clip
REPLACE spell_proc_event SET entry=19407, SpellFamilyName=9, SpellFamilyMask0=512, SpellFamilyMask1=512, SpellFamilyMask2=512; -- Improved Concussive Shot
");
Logs("Fix talents Improved Wing Clip and Improved Concussive Shot to proc properly (not stun player): %d rows" );

/*
MyOP("UPDATE spell_chain SET rank=spell_id-20287+2, prev_spell=IF(prev_spell=20154,21084,prev_spell), first_spell=21084 WHERE first_spell IN (20154,21084) AND (spell_id BETWEEN 20287 AND 20293)");
Logs("Fix ranks in `Seal of Righteousness` chain (two Rank 1 instances are w/o and with Judgement): %d rows");
// Меняя spell_chain нельзя избавиться от 20154 в Spellbook'е: проблема в существовании невидимого skill'а "Holy", с которым, согласно SkillLineAbility.dbc, связан spell 20154, который должен игнорироваться при наличии 21084, чего ядро не делает
*/

$count = MyRUN("
UPDATE game_event_creature SET event=34 WHERE  guid IN (54687, 54688); -- move NPCs Jang and Fishbot 5000 to Fishing Extravaganza Turn-in event
UPDATE game_event_creature SET event=15 WHERE  guid=105970; -- move NPC Riggle Bassbait to Fishing Extravaganza event
");
Logs("Fix Fishing Extravaganza NPCs' schedules: %d creatures" );

}


function FixGameobjects()
{
global $count; PrintHeader(__FUNCTION__);

MyOP("INSERT IGNORE gameobject (guid, id, map, position_x, position_y, position_z, orientation, rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state) VALUES (632457, 181056, 0, 3157.28, -3743.47, 236.951, 2.76712, 0, 0, 0.982523, 0.186143, 25, 100, 1)");
Logs("Fix Naxxramas over Eastern Plaguelands: %d gameobjects");

MyOP("INSERT IGNORE gameobject (guid, id, map, position_x, position_y, position_z, orientation, rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state) VALUES (94154, 141979, 70, 153.39, 289.091, -52.2262, 2.68781, 0, 0, 0, 0, -14400, 255, 1)");
Logs("Fix Uldaman missing Chest: %d gameobjects");

MyOP("DELETE FROM gameobject WHERE guid=7569 AND id=186451"); // .go -3961.46 -4983.74 2.52258 1
Logs("Fix/remove Cauldron floating in air over the sea (Theramore): %d gameobjects");

MyOP("UPDATE gameobject_template SET data2=5 WHERE entry=103661 AND data2=0; -- set radius 5 for Witherbark Totem Bundle TRAP");
Logs("Fix radius of Witherbark Totem Bundle TRAP: %d gameobjects");

MyOP("UPDATE gameobject SET spawntimesecs=180 WHERE id=1765 AND spawntimesecs < 180; -- was 2 sec");
Logs("Fix respawn time of Worn Wooden Chest (3 min): %d objects");

// Есть два шаблона Bubbly Fissure: годный, представленный одним экземляром в
// The Stagnant Oasis и негодный, представленный 13 экземплярами,
// для которых и заменяем номер шаблона, см. http://www.wowhead.com/object=179491/waterlogged-footlocker
MyOP("UPDATE gameobject SET id=180057 WHERE id=177524");
Logs("Fix underwater Bubbly Fissures to restore Breath: %d gameobjects");

$count = MyVAL("SELECT guid FROM gameobject WHERE id >= 181560 AND id <= 181567") !== null ? 0 :
MyRUN("
INSERT IGNORE gameobject (guid, id, map, position_x, position_y, position_z, orientation, rotation0, rotation1, rotation2, rotation3, spawntimesecs, animprogress, state) VALUES
 (39794, 181561, 1, 1916.99, -2033.11, 103.89, 2.76462, 0, 0, 0.982289, 0.187372, 600, 100, 1),   -- Flame of Ashenvale
 (39795, 181560, 1, -914.339, -3347.22, 94.7678, 1.81427, 0, 0, 0.787742, 0.616005, 600, 100, 1), -- Flame of the Barrens
 (39796, 181563, 1, 4364.96, 229.192, 53.5103, 5.93761, 0, 0, 0.171929, -0.985109, 600, 100, 1),  -- Flame of Darkshore
 (39797, 181562, 1, 636.417, 336.333, 52.0252, 3.31442, 0, 0, 0.996269, -0.0863062, 600, 100, 1), -- Flame of Stonetalon
 (55203, 181564, 0, -281.426, 1171.33, 63.6401, 5.26475, 0, 0, 0.487494, -0.873126, 600, 100, 1), -- Flame of Silverpine
 (55204, 181565, 0, -11277, 1853.95, 40.1741, 5.94853, 0, 0, 0.166548, -0.986033, 600, 100, 1),   -- Flame of Westfall
 (55205, 181566, 0, -345.467, -668.955, 55.2845, 3.07144, 0, 0, 0.999385, 0.0350691, 600, 100, 1),-- Flame of Hillsbrad
 (55206, 181567, 0, -2622.55, -2504.01, 82.8143, 3.15764, 0, 0, 0.999968, -0.00802358, 600, 100, 1); -- Flame of the Wetlands
","
INSERT IGNORE game_event_gameobject (guid,event) VALUES (39794,1),(39795,1),(39796,1),(39797,1),(55203,1),(55204,1),(55205,1),(55206,1);
"
);
Logs("Fix/add missing Midsummer green bonfire gameobjects: %d rows" );


MyOP("UPDATE gameobject_template SET flags=flags&~16 WHERE entry IN (141812,141857,141858,141859)");
Logs("Fix/make every Stone of Binding GO targetable/usable while on related quest (Blasted Lands): %d gameobjects");

MyOP("UPDATE gameobject_loot_template SET ChanceOrQuestChance=100,mincountOrRef=1,maxcount=1 WHERE item IN (11751,11752,11753) AND ChanceOrQuestChance<0");
Logs("Fix/non-quest drop status for reagents from Dark Coffer (items without Quest Item tag): %d loots");

MyOP("UPDATE gameobject SET spawntimesecs=60*60*24*7 WHERE id IN (160845,161495, 160836)");
Logs("Fix/make Dark Coffer, Secref Safe, Relic Coffer GOs (BRD) not respawnable: %d guids");

/*
MyOP("UPDATE gameobject_template SET flags=flags|0x10 WHERE entry=170558 AND type=0; -- GO_FLAG_NO_INTERACT");
Logs("Fix/disable open The Lyceum doors without passing Summoner's Tomb (BRD): %d gameobjects");
*/
MyOP("UPDATE gameobject_template SET flags=flags|2 WHERE entry=170558 AND type=0");
Logs("Fix/lock The Lyceum doors (BRD) which require Shadowforge Key: %d gameobjects");


MyOP("INSERT IGNORE gameobject SET guid=90200, id=179437, map=30, position_x=618.748, position_y=-52.1126, position_z=42.1122, orientation=-0.0698131");
Logs("Fix/add `WANTED: Orcs!` poster (Alterac Valley): %d gameobjects");

MyOP("INSERT IGNORE creature_involvedrelation SET id=13447, quest=7402");
Logs("Fix quest `WANTED: Orcs!` ender Noreg Stormpike (Alterac Valley): %d rows");


MyOP("UPDATE gameobject_template SET type=8, faction=0, flags=4, data0=1083, data1=10, data3=0 WHERE entry=178224 AND data0!=1083; -- Dire Pool");
Logs("Fix Dire Pool to be correct focus for Quest item (Feralas): %d gameobjects");


MyOP("UPDATE gameobject SET state=0 WHERE guid=43195 AND id=177370");
Logs("Fix/open by default the door to Ras Frostwhiper (Scholomance): %d guids");


MyOP("UPDATE gameobject_template SET faction=1375, flags=32/*NoDespawn*/ WHERE entry IN (175380,175379,175381)");
Logs("Fix/make inaccessible to players doors of 3 Zuggurats (Stratholme): %d gameobjects");


/*
if (MyVAL("SELECT guid FROM pool_gameobject JOIN gameobject USING(guid) WHERE id IN (176224,176304,176307,176308,176309)") !== null)
    $count = 0;
else {
$crates = array();
$res = MYOP("SELECT * FROM gameobject WHERE id IN (176224,176304,176307,176308,176309) GROUP BY position_x ORDER BY position_x");
while($obj = mysql_fetch_object($res))  $crates[] = $obj;

$count = MyRUN("DELETE FROM gameobject WHERE id IN (176224,176304,176307,176308,176309)");
foreach($crates AS $loc) {
  $t = "map=$loc->map, position_x=$loc->position_x, position_y=$loc->position_y, position_z=$loc->position_z, orientation=$loc->orientation, rotation0=$loc->rotation0, rotation1=$loc->rotation1, rotation2=$loc->rotation2, rotation3=$loc->rotation3, spawntimesecs=60*60*24*7, animprogress=100, state=1";
  $count += MyRUN("
    SET @POOL=(SELECT MAX(entry) FROM pool_template)+1;
    INSERT pool_template SET entry=@POOL, max_limit=1, description='';
    INSERT gameobject SET id=176224, $t;
    INSERT pool_gameobject SET guid=LAST_INSERT_ID(), pool_entry=@POOL, chance=20, description='';
    INSERT gameobject SET id=176304, $t;
    INSERT pool_gameobject SET guid=LAST_INSERT_ID(), pool_entry=@POOL, chance=80, description='';
  ");
}
unset($crates);
} // увы, логика ядра пока такова, что при перезагрузке кол-во создаваемых объектов pool'а не уменьшается на число находящихся в ожидании восстановления
Logs("Pool Supply Crate gameobjects (Stratholme): %d rows" );
*/

$count = MyRUN("
UPDATE gameobject_template SET data9=58 WHERE entry=176224;
UPDATE gameobject_template SET data3=1, data7=0, data9=58, ScriptName='go_supply_crate' WHERE entry IN (176304,176307,176308,176309);
");
Logs("Attach SD2 script for trapped Supply Crates (Stratholme): %d rows" );


MyOP("UPDATE gameobject_template SET flags=32, faction=114 WHERE entry=175947 AND flags=0 AND faction=0");
Logs("Fix/make unclickable one of the doors from Spire Throne to The Rookery (UBRS): %d gameobjects");


MyOP("UPDATE gameobject SET position_z=CASE guid WHEN 42907 THEN 91.5 WHEN 42910 THEN 91.8 ELSE 92 END  WHERE id=177272 AND map=0 AND ABS(position_z-92)<1");
Logs("Hide Moonwell notifiers under surface (Stormwind): %d gameobjects");

MyOP("UPDATE gameobject SET spawntimesecs=20*24*3600 WHERE id IN (SELECT entry FROM gameobject_template WHERE name IN ('Gong of Bethekk'/*, 'Brazier of Madness'*/)) AND spawntimesecs > 0");
// Brazier of Madness не обрабатывается в SD2, он изменяет состояние, despawn не происходит и после перезагрузки можно вызывать снова; впрочем, на это нужно расходовать зелье
Logs("Fix/disable respawn of some objects in instances, make them usable only once (ZG): %d gameobjects");

}


function FixGameobjectAllocation()
// В какой-то степени это Tweak, а не Fix, т.к. кол-во ресурсов настраивается
// под одного игрока, т.е. их немного. Впрочем, если времена восстановления
// оставлены стандартные, то нормально и для нескольких игроков
{
global $count; PrintHeader(__FUNCTION__);

if (! FIRST_RUN) return;

$count = MyRUN("
DELETE FROM gameobject WHERE guid=32304  AND id=142145 AND position_z < 10; -- Blasted Lands: Gromsblood
DELETE FROM gameobject WHERE guid=120653 AND id=2040   AND position_z <116; -- Feralas: Mithril
DELETE FROM pool_gameobject WHERE (SELECT guid FROM gameobject WHERE guid=pool_gameobject.guid) IS NULL;
");
Logs("Remove underground gameobjects {2} and clean pool_gameobject: %d rows" );


// Группирование ресурсов: часть ресурсов не группирована, вследствие
// чего - ресурсов огромное количество; но и там, где они распределены -
// распределены плохо (в некоторых шахтах систематически нет руды,
// в некоторых частях карты ничего нет и т.п.)

CreateObjectPools("Herbs", "gameobject", 700, 380, true, 'AmountOfResourcesLow', <<<EOT
"Peacebloom", "Silverleaf", "Earthroot", "Mageroyal", "Swiftthistle", "Bloodthistle", "Briarthorn", "Stranglekelp", "Bruiseweed", "Wild Steelbloom", "Grave Moss", "Kingsblood", "Liferoot", "Fadeleaf", "Goldthorn", "Khadgar's Whisker", "Wintersbite", "Firebloom", "Purple Lotus", "Arthas' Tears", "Sungrass", "Blindweed", "Ghost Mushroom", "Gromsblood", "Golden Sansam", "Dreamfoil", "Mountain Silversage", "Plaguebloom", "Icecap",
"Bloodpetal Sprout"
EOT
);

CreateObjectPools("Black Lotus", "gameobject", 6000, 9000, true, 'Amount1', <<<EOT
"Black Lotus"
EOT
);


MyOP("
INSERT IGNORE gameobject (id,map,position_x,position_y,position_z,orientation,rotation0,rotation1,rotation2,rotation3,spawntimesecs,animprogress,state) VALUES
(176214, 0, 2192.74, -4479.21,  87.66,   3.03687, 0, 0, 0.99863,   0.052336, 900, 100, 1),
(176214, 0, 2888.38, -4086.29, 101.381, -2.19912, 0, 0, 0.891007, -0.453990, 900, 100, 1);
");
Logs("Fix/add 2 missing Blood of Heroes trap GOs (EPL): %d gameobjects");

// Есть два объекта с названием "Blood of Heroes" - lootable и невидимый trap на тех же координатах
CreateObjectPools("Blood of Heroes", "gameobject", 6000, 9000, true, create_function('$n,$rndseed', 'return 2;'), "(entry = 176213)");


MyOP("INSERT IGNORE gameobject SET id=12653, map=1, position_x=7395.53, position_y=-782.86, position_z=7.90, spawntimesecs=7200");
Logs("Fix/add missing Cat Figurine trap GO (Darkshore): %d gameobjects");

// Есть три вида объектов с названием "Cat Figurine" - 3 простых lootable, 1 lootable->trap и 1 связанный с ним невидимый trap (должен быть на тех же координатах и именно его spawntimesecs определяет время возрожления lootable GO)
// Вызвать Ghost Saber можно в единственном месте из 4-х. Если фигурки там нет, надо брать собирать фигурки котов в других местах пока не появится нужная (через несколько минут)
CreateObjectPools("Cat Figurine", "gameobject", 6000, 9000, true, create_function('$n,$rndseed', 'return 2;'), "(entry IN (13359, 13873))");

/*
CreateObjectPools("Corrupted Felwood Herbs", "gameobject", 700, 400, true,  'AmountHalve', <<<EOT
"Corrupted Songflower", "Corrupted Windblossom", "Corrupted Night Dragon", "Corrupted Whipper Root"
EOT
); // всего ~30 штук
*/

CreateObjectPools("Minerals", "gameobject", 700, 380, true, 'AmountOfResourcesLow', <<<EOT
"Copper Vein", "Tin Vein", "Silver Vein", "Iron Deposit", "Gold Vein", "Mithril Deposit", "Ooze Covered Mithril Deposit", "Small Thorium Vein", "Rich Thorium Vein", "Ooze Covered Thorium Vein", "Ooze Covered Rich Thorium Vein", "Truesilver Deposit", "Ooze Covered Truesilver Deposit", "Dark Iron Deposit"
EOT
); // "Hakkari Thorium Vein", "Ooze Covered Gold Vein", "Ooze Covered Silver Vein"


CreateObjectPools("Quest Resources", "gameobject", 500, 400, true, 'AmountOfResources', <<<EOT
"Blue Power Crystal", "Green Power Crystal", "Red Power Crystal", "Yellow Power Crystal",
"Mathystra Relic",
"Cactus Apple", "Gnomish Toolbox", "Gloom Weed", "Doom Weed", "Lesser Bloodstone Deposit", "Taillasher Eggs",
"Spire Spider Egg"
EOT
); // см. также Increase respawn time of resources and quest GO
// не найти было Lesser Bloodstone Deposit, а кристаллов в Un'goro было слишком много
// "Shellfish Trap" нельзя так просто ставить в pool - есть 2 с одинаковым названием, непонятно как соотносятся


CreateObjectPools("Shipwreck Pools", "gameobject", 1700, 3000, true, 'Amount1', <<<EOT
"Floating Debris", "Floating Wreckage", "Schooner Wreckage Pool", "Waterlogged Wreckage Pool"
EOT
);

CreateObjectPools("Snowdrifts", "gameobject", 700, 700, true, 'AmountOfResources', <<<EOT
"Holiday Snow"
EOT
); // "Hardpacked Snowdrift" уже включён в pool_gameobject_template


CreateObjectPools("Silithyst Geysers", "gameobject", 6000, 3000, true, 'AmountHalve', <<<EOT
"Silithyst Geyser"
EOT
);

CreateObjectPools("Frozen Runes", "gameobject", 9000, 9000, true,
create_function('$n,$rndseed', 'return max(1, round($n/3));'), <<<EOT
"Frozen Rune"
EOT
);

// Gahz'ridian 30/{67}, Wildkin Feather 15/{69}, Pupellyverbos Port 12/{32} (Hinterlands), Sundried Driftwood 8/{21} и некоторые другие стоило бы поместить в pool_gameobject_template
// Для Jinxed Hoodoo Pile в ZG и незачем и нельзя так просто создавать pool, т.к. есть lootable GO с таким названием и соответствующий ему non-lootable с таким же названием

foreach(array("Firefin Snapper School", "Greater Sagefish School", "Oily Blackmouth School", "Sagefish School", "Stonescale Eel Swarm")
        as $school)
CreateObjectPools("Fishing Pools - $school", "gameobject", 1500, 3000, true, 'AmountOfFishings', <<<EOT
"$school"
EOT
);


$count = MyRUN("
DELETE FROM gameobject WHERE id IN (179526,179532,179533) AND map=429; -- only 179528 is lootable gameobject
DELETE FROM creature WHERE id=14366 AND map=429; -- Warpwood Spores
");
Logs("Remove non-working Warpwood Pod trap objects and creatures (Dire Maul): %d rows" );

CreateObjectPools("Warpwood Pods (Dire Maul)", "gameobject", 9000, 9000, true,
 create_function('$n,$rndseed', 'return max(1, round($n/5));'), <<<EOT
 "Warpwood Pod"
EOT
);


// Группирование альтернативных вариантов NPC
CreateObjectPools("Midsummer Celebrants", "creature", 2, 10, false, 'Amount1', <<<EOT
"Midsummer Celebrant"
EOT
);

}


function FixQuests()
{
global $count; PrintHeader(__FUNCTION__);


MyOP("UPDATE quest_template SET Method=0, QuestFlags=QuestFlags&~256 WHERE entry=3861");
Logs("Fix Cluck! quest (Westfall): %d quests");

MyOP("UPDATE quest_template SET SpecialFlags=0 WHERE entry=2358 LIMIT 1"); // `RewMoneyMaxLevel`=1050 for 1750 XP
Logs("Fix Rogue quest \"Horns of Nez'ra\" (Redridge Mountains): %d quests");

MyOP("UPDATE quest_template SET MinLevel=15 WHERE MinLevel>15 AND entry IN (3369,3370)"); // AND MinLevel=23
Logs("Set MinLevel 15 for Barrens quests \"In Nightmares\": %d quests");


$count = MyRUN("
UPDATE quest_template SET MinLevel=20 WHERE MinLevel>20 AND entry IN (95,230,262,265,266,268,453,323);
UPDATE quest_template SET MinLevel=21 WHERE MinLevel>21 AND entry IN (269);
UPDATE quest_template SET MinLevel=22 WHERE MinLevel>22 AND entry IN (270,321);
UPDATE quest_template SET MinLevel=23 WHERE MinLevel>23 AND entry IN (322,324);
UPDATE quest_template SET MinLevel=21 WHERE MinLevel>21 AND entry IN (325,55);
");
Logs("Set MinLevel for Duskwood Sven Yorgen/Morbent Fel quest chain: %d quests" );


MyOP("UPDATE quest_template SET MinLevel=18 WHERE MinLevel>18 AND entry IN (56,57,58)");
Logs("Set MinLevel 18 for \"The Night Watch\" quest chain: %d quests");


MyOP("UPDATE quest_template SET MinLevel=9 WHERE MinLevel=17 AND entry=256");
Logs("Set MinLevel 9 for Loch Modan quest \"WANTED: Chok'sul\": %d quests");


$count = MyRUN("
UPDATE quest_template SET MinLevel= 1 WHERE MinLevel> 1 AND entry IN (7881,7889,7894,7899);
UPDATE quest_template SET MinLevel=10 WHERE MinLevel>10 AND entry IN (7882,7890,7895,7900, 7905,7926);
UPDATE quest_template SET MinLevel=20 WHERE MinLevel>20 AND entry IN (7883,7891,7896,7901);
UPDATE quest_template SET MinLevel=30 WHERE MinLevel>30 AND entry IN (7884,7892,7897,7902);
UPDATE quest_template SET MinLevel=40 WHERE MinLevel>40 AND entry IN (7885,7893,7898,7903,7939,7941,7942,7943,8222,8223);
");
Logs("Fix level requirements for Darkmoon Faire quests: %d quests" );


$count = MyRUN("
UPDATE quest_template SET MinLevel=23 WHERE MinLevel>23 AND entry IN (1046,1045);
UPDATE quest_template SET MinLevel=19 WHERE MinLevel>19 AND entry IN (1030,1029,1055);
UPDATE quest_template SET MinLevel=18 WHERE MinLevel>18 AND entry IN (1028,1027,1026);
");
Logs("Fix level requirements for Raene's Cleansing quest chain: %d quests" );


MyOP("UPDATE quest_template SET RequiredMaxRepValue=2999 WHERE  entry=6701"); // unavailable at Friendly, 100 rep is correct for pre-TBC
Logs("Fix max.reputation restriction for 'Syndicate Emblems' repeatable quest: %d quests");

/*
MyOP("UPDATE quest_template SET PrevQuestId=6681 WHERE  entry=8249");
Logs("Fix PreQuest requirement for 'Junboxes Needed' repeatable quest: %d quests");
*/

$count = MyRUN("
UPDATE quest_template SET ZoneOrSort=3358 WHERE  entry=8438 AND ZoneOrSort=45;
UPDATE quest_template SET ZoneOrSort=3358 WHERE  entry=8384 AND ZoneOrSort=45;
"); // Arathi Highlands -> Arathi Basin для двух BG-заданий (Альянса и Орды)
Logs("Fix Arathi Basin quest category: %d quests" );

MyOP("UPDATE quest_template SET RewRepFaction1=509, RewRepValue1=500 WHERE entry IN (8155,8156,8154,8080,8297)");
Logs("Add proper reputation award for 'Arathi Basin Resources!' quests: %d quests");


MyOP("UPDATE quest_template SET QuestLevel=47 WHERE entry IN (3526,3629,3630,3632,3633,3634,3635,3637,4181)");
Logs("Fix Level for all Gnome Engineering quests (L60 -> L47): %d quests");

MyOP("UPDATE quest_template SET SpecialFlags=SpecialFlags&~1 WHERE entry=3629");
Logs("Fix/remove repeatable flag from one of \"Goblin Engineering\" quests: %d quests");

$count = MyRUN("
DELETE FROM creature_questrelation WHERE id=377 AND quest IN (5630,5632,5633);
UPDATE quest_template SET QuestLevel=10 WHERE entry=5628 AND QuestLevel=20;
"); // удаляемые три задания - вообще невалидны, у них пустой OfferRewardText
Logs("Fix 'Returning Home' quest - remove from Priestess Josetta (Goldshire): %d rows" );


MyOP("UPDATE quest_template SET RewOrReqMoney=2300 WHERE  entry=8194");
Logs("Fix Apprentice Angler quest reward (Jang @ Booty Bay): %d quests");


$count = MyRUN("
UPDATE quest_template SET NextQuestId=0 WHERE  entry=1249;
UPDATE quest_template SET PrevQuestId=1250 WHERE  entry=1264;
");
Logs("Fix Tapoke's quest (was excluded from Missing Diplomat chain): %d quests" );


MyOP("UPDATE quest_template SET MinLevel=31 WHERE entry=1796 AND MinLevel=25");
Logs("Fix/set MinLevel 31 for \"Components for the Enchanted Gold Bloodrobe\" warlock quest: %d quests");


MyOP("DELETE FROM creature_questrelation WHERE quest IN (7886,7887,7888,7921,8266,8267,8268,8269,8289,8292, 8296,7925,7924,7923,7922,8293); -- Ribbons of Sacrifice, Talismans of Merit (patch 1.8.0: replaced by Warsong Gulch Honor Marks), Mark(s) of Honor");
Logs("Fix/remove obsolete Warsong Gulch quests: %d quests");

MyOP("UPDATE quest_template SET SpecialFlags=0 WHERE entry IN (7788,7871,7872,7873,8291, 7789,7874,7875,7876,8294)");
Logs("Fix/remove Repeatable flag from Warsong Gulch quests (also Fix SpecialFlags&2 for q7871,q7872): %d quests");


MyOP("UPDATE quest_template SET SpecialFlags=SpecialFlags&~1 WHERE entry=708");
Logs("Fix/remove Repeatable flag from quest \"The Black Box\": %d quests");

MyOP("UPDATE quest_template SET SpecialFlags=SpecialFlags&~1 WHERE entry=8552");
Logs("Fix/remove Repeatable flag from quest \"The Monogrammed Sash\": %d quests");

MyOP("UPDATE quest_template SET SpecialFlags=SpecialFlags&~1 WHERE entry=5058");
Logs("Fix/remove Repeatable flag from quest \"Mrs. Dalson's Diary\": %d quests");

MyOP("UPDATE quest_template SET SpecialFlags=SpecialFlags&~1 WHERE entry=8314");
Logs("Fix/remove repeatable flag from quest \"Unraveling the Mystery\" (Silithus): %d quests");

MyOP("UPDATE quest_template SET SpecialFlags=SpecialFlags&~1 WHERE entry=7944");
Logs("Fix/remove repeatable flag from quest \"Your Fortune Awaits You...\" (Darkmoon Faire->Wailing Caverns): %d quests");


if (USE_DBSCRIPTS and FIRST_RUN)
{
MyOP("INSERT IGNORE dbscripts_on_go_template_use SET id=177964, delay=1, command=10, datalong=12876, datalong2=60000, data_flags=2, comments='Fathom Stone - Summon Baron Aquanis'");
Logs("Fix Baron Aquanis Summon while on Horde Quest 'Amongst the Ruins': %d dbscripts");
}

$count = MyRUN("
-- Alliance
DELETE FROM creature WHERE guid=86230 AND id=14305; -- remove static version of summonable Human Orphan (Stormwind)
UPDATE quest_template SET PrevQuestId=1468, ExclusiveGroup=-1687, SpecialFlags=SpecialFlags|2 WHERE entry IN (1687,1558,1479); -- Children's Week -> Spooky Lighthouse, The Stonewrought Dam, The Bough of the Eternals
INSERT IGNORE areatrigger_involvedrelation (id, quest) VALUES (3552, 1687), (3548, 1558), (3546, 1479);
UPDATE quest_template SET PrevQuestId=1479, ExclusiveGroup=-558 WHERE entry IN (4822,558); -- You Scream, I Scream..., Jaina's Autograph
UPDATE quest_template SET PrevQuestId=558  WHERE entry=171; -- A Warden of the Alliance
UPDATE creature_questrelation SET id=14305 WHERE quest=171; -- Human Orphan as questgiver (instead of Watcher Callahan)
-- Horde
UPDATE quest_template SET PrevQuestId=172, ExclusiveGroup=-1800, SpecialFlags=SpecialFlags|2 WHERE entry IN (911,910,1800); -- Children's Week -> Gateway to the Frontier, Down at the Docks, Lordaeron Throne Room
INSERT IGNORE areatrigger_involvedrelation (id, quest) VALUES (3549, 911), (3550, 910), (3547, 1800);
UPDATE quest_template SET PrevQuestId=910, ExclusiveGroup=-925 WHERE entry IN (915,925);  -- You Scream, I Scream..., Cairne's Hoofprint
UPDATE quest_template SET PrevQuestId=915  WHERE entry=5502; -- A Warden of the Horde
-- all
UPDATE item_template SET minMoneyLoot=50000, maxMoneyLoot=50000 WHERE entry=23022; -- Curmudgeon's Payoff (entire quest chain reward)
-- UPDATE quest_template SET QuestLevel=0 /* похоже, неправильно трактуется в Quest::XPValue() */ WHERE entry IN (1468,1687,1558,1479,4822,558,171, 172,911,910,1800,915,925,5502);
");
// ! остаётся недоработка, связанная с тем, что условие 'Explore' проверяется вне зависимости от присутствия ребёнка
Logs("Fix Children's Week quest chain and Watcher Callahan: %d rows" );


MyOP("
INSERT IGNORE fishing_loot_template (entry, item, ChanceOrQuestChance) VALUES
  ( 456, 6718, -20), -- Cliffspring River (ID in AreaTable.dbc)
  ( 454, 6718, -20), -- Wildbend River
  ( 448, 6718, -20); -- Grove of the Ancients
");
Logs("Fix quest Electropellers (Fishing, Darkshore): %d loots");

/*
MyOP("UPDATE quest_template SET ReqSpellCast1=9437 WHERE entry=2118; -- quest 'Plagued Lands'");
Logs("Fix quest \"Plagued Lands\": %d quests");
*/

MyOP("DELETE FROM creature_loot_template WHERE item=5076 AND entry=68");
Logs("Fix/remove quest item Shipment of Boots from Stromwind City Guard: %d loots");


$count =
MyRUN("
DELETE FROM creature_questrelation WHERE quest=615 AND id=2500; -- Captain Hecklebury Smotts, quest The Captain's Cutlass
DELETE FROM creature_questrelation WHERE quest=618 AND id=2594; -- Sprogger, quest Facing Negolash
");
Logs("Fix/remove duplicate entries for quests \"The Captain's Cutlass\" and \"Facing Negolash\" (Booty Bay): %d rows" );


MyOP("UPDATE quest_template SET RequiredMaxRepValue=-1, RewRepFaction3=0, RewRepFaction4=0, RewRepFaction5=0, RewRepValue3=0, RewRepValue4=0, RewRepValue5=0 WHERE entry IN (9267,9268,9259,9266)");
Logs("Fix/limit reputation amend quests (Ratchet, Gadgetzan, Booty Bay, Everlook) to Neutral level: %d quests");


$count = MyRUN("","
INSERT IGNORE reputation_spillover_template (faction, faction1,rate_1,rank_1, faction2,rate_2,rank_2, faction3,rate_3,rank_3, faction4,rate_4,rank_4) VALUES
(169, 21,1,7, 369,1,7, 470,1,7, 577,1,7), -- Steamwheedle Cartel
( 67, 68,0.25,7, 76,0.25,7, 81,0.25,7, 530,0.25,7), -- Horde
(469, 47,0.25,7, 54,0.25,7, 69,0.25,7,  72,0.25,7); -- Alliance
");
Logs("Fix/add spillover Reputation templates for Steamwheedle Cartel, Horde, Alliance: %d rows" );
/*
$count = MyRUN("
UPDATE quest_template SET RewRepValue2=RewRepValue2*2/3,RewRepValue3=RewRepValue3*2/3  WHERE RewRepFaction2=21 AND RewRepFaction3=470 AND RewRepValue2=RewRepValue3 AND RewRepValue2=25;
UPDATE quest_template SET RewRepValue1=RewRepValue1*2/5,RewRepValue2=RewRepValue2*2/5,RewRepValue3=RewRepValue3*2/5,RewRepValue4=RewRepValue4*2/5  WHERE RewRepFaction1=21 AND RewRepFaction2=577 AND RewRepFaction3=369 AND RewRepFaction4=470 AND RewRepFaction5=0 AND RewRepValue1=RewRepValue2 AND RewRepValue1=RewRepValue3 AND RewRepValue1=RewRepValue4 AND RewRepValue1 IN (25,50,250,350);
UPDATE quest_template SET RewRepFaction4=470,RewRepValue4=RewRepValue1*2/5, RewRepFaction3=369,RewRepValue3=RewRepValue1*2/5, RewRepFaction2=577,RewRepValue2=RewRepValue1*2/5, RewRepFaction1=21,RewRepValue1=RewRepValue1*2/5  WHERE RewRepFaction1=169 AND RewRepFaction2=0 AND RewRepFaction3=0 AND RewRepFaction4=0;
UPDATE quest_template SET RewRepFaction5=470,RewRepValue5=RewRepValue2*2/5, RewRepFaction4=369,RewRepValue4=RewRepValue2*2/5, RewRepFaction3=577,RewRepValue3=RewRepValue2*2/5, RewRepFaction2=21,RewRepValue2=RewRepValue2*2/5  WHERE RewRepFaction2=169 AND RewRepFaction3=0 AND RewRepFaction4=0 AND RewRepFaction5=0;
");
Logs("Workaround for correct amounts of REP with Steamwheedle Cartel factions: %d quests" );
*/
$count = MyRUN("
UPDATE quest_template SET RewRepValue2=RewRepValue2*2/3,RewRepValue3=RewRepValue3*2/3  WHERE RewRepFaction2=21 AND RewRepFaction3=470 AND RewRepValue2=RewRepValue3 AND RewRepValue2=25;
UPDATE quest_template SET RewRepFaction1=169, RewRepFaction2=0,RewRepValue2=0, RewRepFaction3=0,RewRepValue3=0, RewRepFaction4=0,RewRepValue4=0  WHERE RewRepFaction1=21 AND RewRepFaction2=577 AND RewRepFaction3=369 AND RewRepFaction4=470 AND RewRepFaction5=0 AND RewRepValue1=RewRepValue2 AND RewRepValue1=RewRepValue3 AND RewRepValue1=RewRepValue4 AND RewRepValue1 IN (25,50,250,350);
");
Logs("Fix amounts of REP with Steamwheedle Cartel factions: %d quests" ); // требует правки ядра


MyOP("UPDATE quest_template SET RewRepFaction1=809, RewRepValue1=200 WHERE entry=7483");
Logs("Fix/add Reputation reward for quest `Libram of Rapidity` (Dire Maul): %d quests");


MyOP("UPDATE quest_template SET SpecialFlags=SpecialFlags|1 WHERE entry IN (9228,9222,9224,9225,9227,9221,9223,9226)");
Logs("Fix \"Superior/Epic Armaments of ...\" quests (EPL, Argent Dawn), make them all repeatable: %d quests");


MyOP("UPDATE quest_template SET SpecialFlags=SpecialFlags|2 WHERE entry IN (1560, 4261, 5203)");
Logs("Fix premature completion for a few escort quests: %d quests");


$count = MyRUN("
UPDATE creature_template SET ScriptName='' WHERE entry IN (11192,11191,11193); -- disable NPC trainer SD2 scripts (half-ported from TBC/WotLK)
UPDATE quest_template SET NextQuestId=5306 WHERE entry=5284;
UPDATE quest_template SET NextQuestId=5307 WHERE entry=5302;
UPDATE quest_template SET PrevQuestId=5284, RewSpell=17040, RewSpellCast=17044, RequiredSkillValue=250, CompleteEmote=1 WHERE entry=8869;
UPDATE quest_template SET PrevQuestId=5302, RewSpell=17040, RewSpellCast=17044 WHERE entry=5305;
UPDATE quest_template SET PrevQuestId=5302, RewSpell=17041, RewSpellCast=17043 WHERE entry=5306;
UPDATE quest_template SET PrevQuestId=5284, RewSpell=17039, RewSpellCast=17042 WHERE entry=5307;
-- UPDATE quest_template SET ExclusiveGroup=8869 WHERE entry IN (8869,5305,5306,5307);
");
Logs("Fix Weapon sub-Specialization quests (Everlook): %d rows" );


MyOP("UPDATE quest_template SET SpecialFlags=SpecialFlags|1 WHERE entry IN (7907,7929,7927,7928)");
Logs("Fix \"Darkmoon ... Deck\" quests (Darkmoon Faire), make them repeatable: %d quests");


MyOP("UPDATE quest_template SET RewMoneyMaxLevel=0 WHERE entry=4324");
Logs("Fix/remove XP reward for prequest \"Yuka Screwspigot\": %d quests");


$count = MyRUN("
UPDATE quest_template SET ZoneOrSort=1537 WHERE entry IN (8371,8385) AND ZoneOrSort=-25; -- Category: Ironforge
UPDATE quest_template SET ZoneOrSort=1637 WHERE entry IN (8367,8388) AND ZoneOrSort=-25; -- Category: Orgrimmar
");
Logs("Fix/category for multi-Battleground quests \"Concerted Efforts\" and \"For Great Honor\": %d quests" );


MyOP("UPDATE quest_template SET SpecialFlags=SpecialFlags&~1 WHERE entry IN (7081,7082,7361,7362,7363,7364,7365,7366,7382,7381,7202,7181,7171,7172,7170,7166,7167,7164,7181,7202)");
Logs("Fix/remove Repeatable flag from many Alterac Valley quests: %d quests");


$count = MyRUN("
DELETE FROM creature_questrelation WHERE quest IN (7022,7023) AND id=13429; -- Nardstrum Copperpinch is at Horde side
INSERT IGNORE creature_questrelation (quest,id) VALUES (7022, 13433), (7023, 13435); -- Jinglepocket family is at Alliance side
");
Logs("Fix questgivers for quest `Greatfather Winter is Here`: %d rows" );


MyOP("UPDATE quest_template SET QuestLevel=60, RewOrReqMoney=900/*SDB, quest text implies reward*/ WHERE entry IN (8860,8861) AND (QuestLevel>60 OR RewOrReqMoney=0)");
Logs("Fix level and reward money for quest `New Year Celebrations!` (Winter Veil event): %d quests");


MyOP("DELETE FROM creature_questrelation WHERE quest=7062 AND id=10877");
Logs("Fix/remove Winter Veil quest from Courier Hammerfall (Ironforge): %d rows");


$count = MyRUN("
UPDATE gameobject_template SET flags=flags|4 WHERE entry=176089; -- not lootable while not on related quest
UPDATE quest_template SET ReqItemId1=12812, ReqItemCount1=1 WHERE entry=5103;
UPDATE quest_template SET SrcItemId=12812, SrcItemCount=1 WHERE entry=5124;
");
Logs("Fix quests `Hot Fiery Death` and `Fiery Plate Gauntlets`: %d rows" );


MyOP("UPDATE mail_loot_template SET item=21746 WHERE entry=92 AND item=20469; -- 92 points to MailTemplate.DBC for mail text");
Logs("Fix mail loot for quest Hammershout the Elder (Lunar Festival): %d items");


MyOP("INSERT IGNORE creature_involvedrelation SET id=12126, quest=5944");
Logs("Add scripted Lord Tirion Fordring as ender of quest `In Dreams` (WPL): %d rows");


MyOP("UPDATE quest_template SET RequestItemsText='What news do you bring from the lands of the Stormpikes? How does the battle for Alterac Valley fare?' WHERE entry=8383 AND RequestItemsText IS NULL");
Logs("Fix showing of required items for repeatable version of quest \"Remember Alterac Valley\": %d quests");


if (USE_DBSCRIPTS) {
$count = MyVAL("SELECT id FROM dbscripts_on_go_template_use WHERE id=181071") !== null ? 0 :
MyRUN(
"INSERT IGNORE conditions SET type=1, value1=27861, value2=0; -- Baron's Ultimatum aura",
"INSERT IGNORE conditions SET type=9, value1=8945, value2=1; -- quest Dead man's plea is incomplete",
"SET @cAura := (SELECT condition_entry FROM conditions WHERE type=1 AND value1=27861 AND value2=0);",
"SET @cQuest := (SELECT condition_entry FROM conditions WHERE type=9 AND value1=8945 AND value2=1);",
"
INSERT dbscripts_on_go_template_use (id, delay, command, datalong, datalong2, data_flags, x,y,z,o, comments) VALUES
(181071, 0, 31, 10440, 533, 8, 0,0,0,0, 'stop if Baron Rivendare is alive'),
(181071, 0, 31, 16031, 100, 8, 0,0,0,0, 'stop if Ysida Harmon is already spawned'),
(181071, 0, 34, @cAura, 0, 8, 0,0,0,0, 'stop if no [Barons Ultimatum] aura (removed out of Stratholme)'),
(181071, 0, 34, @cQuest,0, 8, 0,0,0,0, 'stop if not on quest [Dead mans plea]'),
(181071, 1, 10, 16031, 60*60*1000, 0, 4042,-3336,115,3.85, 'spawn Ysida Harmon (long time before despawn corresponds her gossip text)'),
(181071, 1,  8, 16031, 1, 4, 0,0,0,0, 'quest Credit [Ysida Freed]'),
(181071, 1, 15, 27773, 0, 4+8, 0,0,0,0, 'Cast spell 27773 [Ysida Freed - Argent Dawn Reputation]');
");
Logs("Hackfix/allow complete Dead Man's Plea quest after server reload (Stratholme): %d rows" );
}


$count = MyRUN("
UPDATE quest_template SET RequiredRaces=0 WHERE entry=7562;
UPDATE quest_template SET NextQuestId=0, ExclusiveGroup=0 WHERE entry=7564;
UPDATE quest_template SET PrevQuestId=7564, NextQuestId=7624 WHERE entry=7623;
UPDATE quest_template SET NextQuestId=7629, ExclusiveGroup=-7625 WHERE entry=7630;
UPDATE quest_template SET ExclusiveGroup=-7625 WHERE entry=7625;
UPDATE quest_template SET ExclusiveGroup=0 WHERE entry=7629;
UPDATE quest_template SET PrevQuestId=7629 WHERE entry=7631;
"); // Nostalrius
Logs("Fix Warlock epic mount quest chain: %d quests" );


$count = MyRUN("
UPDATE quest_template SET NextQuestInChain=7622 WHERE entry=7621 AND NextQuestId=0 AND NextQuestInChain=0;
UPDATE quest_template SET PrevQuestId=7621 WHERE entry=7622 AND PrevQuestId=0;
");
Logs("Fix Priest epic quest chain (Eris Havenfire, EPL): %d quests" );


MyOP("UPDATE quest_template SET SpecialFlags=SpecialFlags|1 WHERE entry=1193");
Logs("Fix/make repeatable quest \"Broken Trap\" (Dire Maul): %d quests");


MyOP("UPDATE quest_template SET SpecialFlags=SpecialFlags|1 WHERE entry=5122");
Logs("Fix/make repeatable quest \"The Medallion of Faith\" (Stratholme): %d quests");


MyOP("UPDATE quest_template SET SpecialFlags=SpecialFlags|1 WHERE entry IN (/*require Task Briefing NN*/8498,8536,8804,8805,8806,8807,8829, /*Imperial Qiraji ...*/8789,8790, /*category:Anh'Qiraji War Effort*/8493,8495,8500,8512,8514,8516,8518,8521,8523,8525,8529,8533,8543,8546,8550,8581,8583,8589,8591,8601,8605,8608,8610,8612,8614,8616,8846,8847,8848,8849,8850,8851,8852,8853,8854,8855)");
Logs("Fix/make repeatable some Silithus and Anq'Qiraji quests: %d quests");


MyOP("INSERT IGNORE creature_questrelation SET id=14368, quest=7508");
Logs("Fix/assign quest \"The Forging of Quel'Serrar\" to Lorekeeper Lydros: %d quests");


MyOP("UPDATE quest_template SET NextQuestId=0 WHERE entry IN (8962,8963,8964,8965) AND NextQuestInChain<>0");
Logs("Fix accessibility of 4-quest group \"More Components of Importance\" (Dungeon Set 2 quest chain): %d quests");


MyOP("UPDATE quest_template SET PrevQuestId=9033/*Echoes of War*/ WHERE entry IN (9229,9232)");
Logs("Fix PreQuest requirement for 'The Fate of Ramaladni' and 'The Only Song I Know...': %d quests");


MyOP("INSERT IGNORE spell_script_target SET entry=22904, type=0, targetEntry=179561");
Logs("Fix quest \"The Forging of Quel'Serrar\", GO Onyxia Flame Breath => lootable GO Ancient Heated Blade: %d rows");


MyOP("UPDATE quest_template SET RequestItemsText='' WHERE entry IN (8101,8110,8116) AND RequestItemsText='NULL'");
Logs("Fix text of some Zandalar Tribe quests: %d quests");


MyOP("UPDATE quest_template SET PrevQuestId=4735 WHERE entry=5522 AND PrevQuestId=4734");
Logs("Fix previous quest for quest \"Leonid Bartholomew\" (Burning Steppes): %d quests");

}


function FixTooLowMinLevelsOfNextQuestsInChains()
{
global $count; PrintHeader(__FUNCTION__);

$count = 0;
while($count < 10000) {
  MyOP("UPDATE quest_template AS t1 JOIN quest_template AS t2 ON t1.PrevQuestId=t2.entry
        SET t1.MinLevel=t2.MinLevel
        WHERE t1.PrevQuestId != 0  AND  t1.MinLevel < t2.MinLevel
  ");
  $n = mysql_affected_rows();
  if ($n == 0) break;
  $count += $n;
}
Logs("Elevate too low Quest MinLevel if < MinLevel of PreQuest: %d quests" );
}



function FixQuestLoot()
{
global $count; PrintHeader(__FUNCTION__);

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-ChanceOrQuestChance WHERE item=5475 AND groupid=0 AND ChanceOrQuestChance>0");
Logs("Fix quest only drop of Wooden Key (Ashenvale): %d loots");

$count = MyRUN("
UPDATE creature_loot_template SET ChanceOrQuestChance=-ChanceOrQuestChance WHERE item IN (20087,19775) AND ChanceOrQuestChance > 0; -- Wavethrasher Scales, Sealed Azure Bag
UPDATE pickpocketing_loot_template SET ChanceOrQuestChance=-ChanceOrQuestChance WHERE item IN (19775) AND ChanceOrQuestChance > 0; -- Sealed Azure Bag
");
Logs("Fix some Quest Item drops that previously were common drops: %d loots" );


MyOP("UPDATE creature_loot_template AS clt JOIN creature_template ON lootid=clt.entry SET clt.ChanceOrQuestChance=CASE WHEN rank>0 THEN -20 WHEN minlevel>=21 THEN -15 ELSE -10 END  WHERE item=7906 AND ChanceOrQuestChance=-100");
Logs("Fix/lower drop rate of Horns of Nez'ra (Redridge Mountains): %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-1.0 WHERE item=4612 AND entry IN (2725,2726) AND ABS(ChanceOrQuestChance)>=100; -- 1% drop for Black Drake's Heart");
Logs("Fix/lower drop chance for Black Drake's Heart: %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-33 /*PSDB*/ WHERE entry=2791 AND item IN (4518,4519,4520)");
Logs("Fix/lower drop chance for scroll fragments of \"The Lost Fragments\" quest: %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-8 WHERE item=3693 AND ChanceOrQuestChance=-100");
Logs("Fix/lower drop chance for Humbert's Sword (Dun Garok): %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-1 WHERE item=22708 AND groupid=0");
Logs("Fix drop chance of quest item Fate of Ramaladni (Naxxramas): %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-15 WHERE item=3477 AND groupid=0; -- Nostalrius");
Logs("Fix drop chance of quest item Creeper Ichor: %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-25 WHERE item=5026 AND groupid=0; -- Nostalrius");
Logs("Fix drop chance of quest item Fire Tar: %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-25 WHERE item IN (20457,20458,20459) AND groupid=0; -- Nostalrius");
Logs("Fix drop chance of quest item Hive'Ashi/Regal/Zora Silithid Brain: %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-15 WHERE item=4807 AND groupid=0; -- Nostalrius");
Logs("Fix drop chance of quest item Swoop Gizzard: %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-15 WHERE item=4806 AND groupid=0; -- Nostalrius");
Logs("Fix drop chance of quest item Plainstrider Scale: %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-20 WHERE item=4804 AND groupid=0; -- Nostalrius");
Logs("Fix drop chance of quest item Prairie Wolf Heart: %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-25 WHERE item=10458 AND groupid=0; -- Nostalrius");
Logs("Fix drop chance of quest item Prayer to Elune: %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-33 WHERE item=1519 AND ChanceOrQuestChance<=-80; -- Kronos-2, also compare to 21% chance for Skullsplitter Tusk");
Logs("Fix/lower drop chance of quest item Bloodscalp Ear: %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-20 WHERE item=2466 AND ChanceOrQuestChance<=-80; -- Kronos-2");
Logs("Fix/lower drop chance of quest item Skullsplitter Fetish: %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-25 WHERE item=4898 AND ChanceOrQuestChance<=-50");
Logs("Fix/lower drop chance of quest item Lightning Gland: %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=CASE WHEN entry IN(11501,9196,10584,9217) THEN -100 WHEN entry IN(11440,11442,11443) THEN -5 ELSE -20 END WHERE item=21982 AND groupid=0");
Logs("Fix drop chance of quest item Ogre Warbeads (quest Falrin's Vendetta): %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-35 WHERE item=3714 AND ChanceOrQuestChance<=-80");
Logs("Fix/lower drop chance of quest item Worn Stone Token: %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-100 WHERE item=21137 AND mincountOrRef>0");
Logs("Fix 100%% quest drop of Blue Scepter Shard from Maws (Azshara): %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-30 WHERE item=18604 AND mincountOrRef>0; -- was -80%");
Logs("Fix/lower quest drop chance of Tears of the Hederine (Winterspring): %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=IF(item=22228,-50,-15) WHERE ChanceOrQuestChance=-100 AND item IN (22226/*Druidical Remains*/,22227/*Starbreeze Village Relic*/,22228/*Brilliant Sword of Zealotry*/,22229/*Soul Ashes of the Banished*/) AND mincountOrRef>0");
Logs("Fix/lower drop chance for Components of Importance (Dungeon Set 2 quest chain): %d loots");

$count = MyRUN(
"UPDATE creature_loot_template SET ChanceOrQuestChance=-1 WHERE item=20951",
"INSERT IGNORE creature_loot_template (entry,item,ChanceOrQuestChance) VALUES
(11673,20951,-1), -- Ancient Core Hound
(12076,20951,-1), -- Lava Elemental
(11667,20951,-1), -- Flameguard
(11666,20951,-1), -- Firewalker
(12101,20951,-1), -- Lava Surger
(11665,20951,-1), -- Lava Annihilator
(11659,20951,-1), -- Molten Destroyer
(11658,20951,-1), -- Molten Giant
(11662,20951,-1), -- Flamewaker Priest
(12119,20951,-1), -- Flamewaker Protector
(12100,20951,-1), -- Lava Reaver
(11668,20951,-1); -- Firelord"
);
Logs("Fix/make Narain's Scrying Goggles 1%% drop from all MC creatures: %d loots" );

$count = MyRUN("
UPDATE creature_loot_template SET ChanceOrQuestChance=-40 WHERE item=4105  AND ChanceOrQuestChance=-80;  -- Elder Crocolisk Skin: 11.55% @ Allakhazam, but only 4 Elder Saltwater Crocolisk
UPDATE creature_loot_template SET ChanceOrQuestChance=-30 WHERE item=18959 AND ChanceOrQuestChance=-100; -- Smithing Tuyere 6.24% @ Allakhazam, but only 5 Dark Iron Steamsmith
UPDATE creature_loot_template SET ChanceOrQuestChance=-15 WHERE item=18960 AND ChanceOrQuestChance=-100; -- Lookout's Spyglass 5.08% @ Allakhazam, 20 Dark Iron Lookout
UPDATE creature_loot_template SET ChanceOrQuestChance=-10 WHERE item=10551 AND ChanceOrQuestChance=-80;  -- Thorium Plated Dagger 0.70..6.81% @ Allakhazam
UPDATE creature_loot_template SET ChanceOrQuestChance=-10 WHERE item=10552 AND ChanceOrQuestChance=-100; -- Symbol of Ragnaros 1.09..4.15% @ Allakhazam
UPDATE creature_loot_template SET ChanceOrQuestChance=-50 WHERE item=11829 AND ChanceOrQuestChance=-100; -- Un'Goro Ash 7.43..8.61% @ Allakhazam
UPDATE creature_loot_template SET ChanceOrQuestChance=-100 WHERE item=12722; -- Good Luck Other-Half-Charm: common sense and @Nostalrius vs 10.85% @Allakhazam
");
Logs("Fix drop chances for some quest items: %d loots" );

/*
MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-12 WHERE item=12722 AND ChanceOrQuestChance=-100");
Logs("Fix/lower drop chance for Good Luck Other-Half-Charm (quest drop): %d loots");
*/

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=-1 WHERE item=12524 AND ChanceOrQuestChance=-100");
Logs("Fix/lower drop chance for Blue-feathered Amulet (quest drop): %d loots");

// Drop while not on quest, but item begins quest

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=5 WHERE item=12558 AND ChanceOrQuestChance=50");
Logs("Fix/lower drop chance for Blue-feathered Necklace (begins quest): %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=8 WHERE entry=6212 AND item=9326 AND ChanceOrQuestChance=-100");
Logs("Fix drop chance for Grime-Encrusted Ring (Gnomeregan): %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=15 WHERE item=9308 AND ChanceOrQuestChance<0 AND groupid=0");
Logs("Fix drop chance for Grime-Encrusted Object (Gnomeregan): %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=3 WHERE item=12771 AND ChanceOrQuestChance=10");
Logs("Fix/lower drop chance for Empty Firewater Flask (begins quest): %d loots");

MyOP("UPDATE item_loot_template SET ChanceOrQuestChance=0, groupid=1 WHERE entry IN (20805, 21386)");
Logs("Fix chances for contents of Followup Logistics Assignment (Silithus quest items): %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=100/*Nostalrius*/ WHERE entry=9568 AND item=12780 AND mincountOrRef>0");
Logs("Fix 100%% quest drop of General Drakkisath's Command from Overlord Wyrmthalak (LBRS): %d loots");

// Drop while not on quest, but quest/REP related

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=100 WHERE item=20513 AND groupid=0; -- was ~83%");
Logs("Fix 100%% drop chance of Abyssal Crests (elemental Templars, Silithus): %d loots");

MyOP("DELETE FROM creature_loot_template WHERE item=18792 AND minCountOrRef>0");
Logs("Fix/remove Blessed Arcanite Barding drop from Risen Construct and Petrified Treant: %d loots");

}


function FixLoot()
{
global $count; PrintHeader(__FUNCTION__);

if (FIRST_RUN) {

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=0.5 WHERE ROUND(ChanceOrQuestChance*100)/100=0.05 AND mincountOrRef=-24065");
Logs("Fix/x10 chance for Rare L19-20 world drop items: %d rows");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=1 WHERE ROUND(ChanceOrQuestChance*100)/100=0.5 AND mincountOrRef=-24066");
Logs("Fix/x2 chance for Uncommon L21-22 world drop items: %d rows");

$count = MyRUN("
UPDATE creature_loot_template SET ChanceOrQuestChance=1 WHERE mincountOrRef < 0 AND ChanceOrQuestChance > 33 AND entry IN (2749,8202); -- [Uncommon] Siege Golem, Cyclok the Mad
DELETE FROM creature_loot_template WHERE mincountOrRef < 0 AND ChanceOrQuestChance > 0 AND entry IN (2852); -- [Uncommon, Rare] Enslaved Druid of the Talon
");
Logs("Fix weird weapon/armor world drop chances for a few specific creatures: %d rows" );


$count = 0;
for($i = 0; $i < 3; $i++) { // цикл по Quality вещей

$groups = array(
/* uncommon */ "24074,24075,24076,24077,24078,24060,24062,24064,24066,24068,24048,24050,24052,24054,24056,24037,24039,24041,24043,24045,24025,24027,24029,24031,24033,24016,24018,24020",
/* rare */     "24061,24063,24065,24067,24069,24049,24051,24053,24055,24057,24038,24040,24042,24044,24046,24026,24028,24030,24032,35015,24034,24017,24019",
/* epic */     "24079,24080,24081,24082,24083,24084,24085,24086,24087,24088,24089,24090,24091"
); $groups = $groups[$i];

// Проверка предположений относительно БД
if (MyVAL("SELECT item FROM reference_loot_template AS rlt JOIN item_template AS it ON (item=it.entry) WHERE rlt.entry IN ($groups) AND Quality!=$i+2") !== null)
   { printf("WARNING! Failed world drop chance fix for items of Quality=%d\n", $i+2); continue; }

$chance = array(2, 0.5, 0.1);
$chance = $chance[$i];
// вероятность выпадания эпических вещей всё равно на порядок выше, чем, например, по YTDB 3.3.5a, где к тому же на порядок меньше число существ, с которых они могут браться.
// надо ещё учитывать, что не со всех существ выпадают все уровни качества, Uncommon для L41+ выпадает с ~ в 1.5 раз большего числа существ, чем Epic

$res = MyOP("SELECT lootid FROM creature_template WHERE rank IN (1,2)");
$eliteLoots = array();
while($row = mysql_fetch_row($res))  $eliteLoots[ $row[0] ] = true;

$res = MYOP("SELECT entry, COUNT(mincountOrRef) AS N FROM creature_loot_template WHERE ROUND(ChanceOrQuestChance*100)/100 IN (1,0.5,0.05,0.1) AND -mincountOrRef IN($groups) AND groupid=1 GROUP BY entry");
while($obj = mysql_fetch_object($res)) {
  MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance = "
       .(isset($eliteLoots[$obj->entry]) ? "2*" : "")
       ."$chance/$obj->N  WHERE entry=$obj->entry AND -mincountOrRef IN($groups) AND groupid=1");
  $count += mysql_affected_rows();
}
unset($eliteLoots);
}
Logs("Decrease too high chances of gear world drops (Uncommon /2, Rare /3, Epic /2.6, but x2 for Elite creatures): %d rows" );

} // endif FIRST_RUN


$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=534, item=4476, ChanceOrQuestChance=40, groupid=2;
INSERT IGNORE creature_loot_template SET entry=534, item=4477, ChanceOrQuestChance=40, groupid=2;
DELETE FROM reference_loot_template WHERE item IN (4476, 4477);
");
Logs("Fix loot from Nefaru (rare elite worgen, Duskwood): %d rows" );


$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=3792, item=5753, ChanceOrQuestChance=40, groupid=2;
INSERT IGNORE creature_loot_template SET entry=3792, item=5754, ChanceOrQuestChance=40, groupid=2;
DELETE FROM reference_loot_template WHERE item IN (5753, 5754);
");
Logs("Fix loot from Terrowulf Packlord (rare worgen, Ashenvale): %d rows" );


$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=2452, item=3011, ChanceOrQuestChance=50; -- uncommon Feathered Headdress
DELETE FROM reference_loot_template WHERE item IN (3011);
UPDATE creature_loot_template SET ChanceOrQuestChance=25 WHERE entry=2452 AND item=6331 AND groupid=0 AND ChanceOrQuestChance>25; -- rare Howling Blade
");
Logs("Fix loot from Skhowl (rare Yeti, Alterac Mountains): %d rows" );


$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=2453, item=4810, groupid=2, ChanceOrQuestChance=40; -- Boulder Pads
UPDATE creature_loot_template SET groupid=2, ChanceOrQuestChance=20 WHERE entry=2453 AND item=1678 AND groupid=0; -- mutually exclusive group for rare Black Ogre Kickers
UPDATE creature_loot_template SET groupid=2, ChanceOrQuestChance=20 WHERE entry=2453 AND item=6327 AND groupid=0; -- mutually exclusive group for rare The Pacifier
DELETE FROM reference_loot_template WHERE item IN (4810);
");
Logs("Fix loot from Lo'Grosh (rare Ogre, Alterac Mountains): %d rows" );


if (USE_DBSCRIPTS)
do {
if (
MyVAL("SELECT MAX(N) FROM (
  SELECT COUNT(*)-1 AS N FROM gossip_menu_option WHERE menu_id=1050 UNION 
  SELECT COUNT(*) AS N FROM dbscripts_on_gossip WHERE id=50111 UNION
  SELECT COUNT(*) AS N FROM conditions WHERE condition_entry IN (1769,1768,1413,1121,1023)
  ) AS NumEntries
") != 0)  break;

$count = MyRUN("
INSERT gossip_menu_option SET menu_id=1050, id=1, option_text='Use engineering to access hidden shematics!', option_id=1, npc_option_npcflag=1, action_menu_id=-1, action_script_id=50111, box_coded=0, box_money=0, box_text=NULL, condition_id=1769;
INSERT dbscripts_on_gossip SET id=50111, command=17, datalong=4413, datalong2=1, comments='Create Item - Schematic: Discombobulator Ray';
INSERT conditions (condition_entry, type, value1, value2) VALUES (1769, -1, 1413, 1768);
INSERT conditions (condition_entry, type, value1, value2) VALUES (1768, 7, 202, 160); -- Engineering 160
INSERT conditions (condition_entry, type, value1, value2) VALUES (1413, -1, 1023 /* 1205 in YTDB */, 1121);
INSERT conditions (condition_entry, type, value1, value2) VALUES (1121, 2, 9327, 1); -- must have Security DELTA Data Access Card
-- INSERT conditions (condition_entry, type, value1, value2) VALUES (1205, -1, 2 /*339 in YTDB*/, 1023);
-- INSERT conditions (condition_entry, type, value1, value2) VALUES (339 /*2 in ClassicDB*/, 2, 9281, 1); -- must have Red Punch Card
INSERT conditions (condition_entry, type, value1, value2) VALUES (1023, 24, 4413, 1); -- does not have Schematic: Discombobulator Ray
");

Logs("Fix/add \"Schematic: Discombobulator Ray\" from Matrix Punchograph 3005-D (Gnomeregan): %d rows" );
} while(false);


$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=723, item=1680, ChanceOrQuestChance=40; -- Headchopper, uncommon IL 44 [39] 2H-Axe
DELETE FROM reference_loot_template WHERE item IN (1680);
");
Logs("Fix loot from Mosh'Ogg Butcher (rare elite ogre, Stranglethorn Vale): %d rows" );


$count = MyVAL("SELECT item FROM creature_loot_template WHERE entry=7016 AND item=6333") !== null ? 0 :
MyRUN("
INSERT IGNORE creature_loot_template SET entry=7016, item=6333, ChanceOrQuestChance=40, groupid=2; -- uncommon Spikelash Dagger
UPDATE creature_loot_template SET groupid=2 WHERE entry=7016 AND item=6332 AND groupid=0; -- mutually exclusive group for rare Black Pearl Ring
DELETE FROM reference_loot_template WHERE item IN (6333);
");
Logs("Fix loot from Lady Vespira (rare naga, Darkshore): %d rows" );


$count = MyVAL("SELECT item FROM creature_loot_template WHERE entry=2600 AND (item IN (5180,5181) OR groupid=2)") !== null ? 0 :
MyRUN("
INSERT IGNORE creature_loot_template SET entry=2600, item=5180, ChanceOrQuestChance=30, groupid=2; -- uncommon Necklace of Harmony
INSERT IGNORE creature_loot_template SET entry=2600, item=5181, ChanceOrQuestChance=67, groupid=2; -- uncommon Vibrant Silk Cape
DELETE FROM reference_loot_template WHERE item IN (5180,5181);
");
Logs("Fix loot from Singer (rare Human, Arathi Highlands): %d rows" );


/*
MyOP("INSERT IGNORE creature_loot_template SET entry=10760, item=5773, ChanceOrQuestChance=1.7; -- in TBC, but not in Classic?");
Logs("Fix Grimtotem Geomancer to drop Pattern: Robes of Arcana: %d loots");
*/

MyOP("UPDATE gameobject_loot_template SET ChanceOrQuestChance=100 WHERE entry=1570 AND item=3706; -- the chance was 0.02%");
Logs("Fix Ensorcelled Parchment to always drop from Worn Wooden Chest: %d loots");


MyOP("INSERT IGNORE creature_loot_template SET entry=9237, item=13173, mincountOrRef=100, maxcount=175, ChanceOrQuestChance=100, groupid=0");
Logs("Fix War Master Voone (LBRS) to drop 100-175 Flightblade Throwing Axes: %d loots");


MyOP("UPDATE gameobject_loot_template SET maxcount=1/*SDB*/ WHERE item=13468 AND mincountOrRef=1 AND maxcount=3 AND ChanceOrQuestChance=100");
Logs("Fix/decrease amount of gathered Black Lotus (1 instead of 1-3): %d loots");


MyOP("UPDATE gameobject_loot_template SET ChanceOrQuestChance=100 WHERE entry=3597 AND item=6172; -- the chance was 0.02%");
Logs("Fix Lost Supplies (Unique) to always drop from Scattered Crate: %d loots");


MyOP("UPDATE gameobject_loot_template SET ChanceOrQuestChance=1 WHERE entry=13761 AND item=13371; -- the chance was 100%, disenchant exploit");
Logs("Fix/lower chances to loot Father Flame item from Father Flame GO (UBRS): %d loots");


MyOP("UPDATE gameobject_loot_template SET groupid=0 WHERE entry=16719 AND minCountOrRef=-12000 AND item=-minCountOrRef");
Logs("Fix chances for contents of Cache of the Firelord (Molten Core): %d loots");


$count = MyRUN("
UPDATE creature_loot_template SET ChanceOrQuestChance=5   WHERE item=21105 AND mincountOrRef>0; -- clbd0: 0.26%
UPDATE creature_loot_template SET ChanceOrQuestChance=100 WHERE item=21108 AND mincountOrRef>0; -- cldb0: 2%
");
Logs("Fix/increase drop chances of Draconic for Dummies ch.III (Hederine Initiate/Slayer) and VI (Onyxia): %d loots" );


MyOP("INSERT IGNORE creature_loot_template SET entry=2931, item=4613, ChanceOrQuestChance=100");
Logs("Fix Zaricotl (elite bird, Badlands) to drop Corroded Black Box: %d loots");


if (USE_CONDITIONS)
{
// Убрать требование на взятие задания и логичнее, т.к. прочитать журнал Baelog'а
// и взять амулет из ларца можно раньше, и лучше, т.к. появляется возможность получить
// хорошие вещи с Ironaya ранее достижения L35
MyOP("UPDATE creature_loot_template SET condition_id=0 WHERE entry=6910 AND item=7741");
Logs("Remove condition to loot the Shaft of Tsol from Revelosh: %d conditions");
}


$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=5837, item=1355, ChanceOrQuestChance=23/*UDB*/; -- Buckskin Cape, [15] uncommon Cloak
DELETE FROM reference_loot_template WHERE item IN (1355);
");
Logs("Fix loot from Stonearm (rare Centaur, The Barrens): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=1140, item=4463, groupid=2, ChanceOrQuestChance=30; -- Beaded Raptor Collar
INSERT IGNORE creature_loot_template SET entry=1140, item=6198, groupid=2, ChanceOrQuestChance=40; -- Jurassic Wristguards
DELETE FROM reference_loot_template WHERE item IN (4463,6198);
");
Logs("Fix loot from Razormaw Matriarch (rare Raptor, Wetlands): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=2541, item=5028, groupid=2, ChanceOrQuestChance=30; -- Lord Sakrasis' Scepter
INSERT IGNORE creature_loot_template SET entry=2541, item=5029, groupid=2, ChanceOrQuestChance=50; -- Talisman of the Naga Lord
DELETE FROM reference_loot_template WHERE item IN (5028,5029);
");
Logs("Fix loot from Lord Sakrasis (rare Naga, Stranglethorn Vale): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=2090, item=5749, groupid=2, ChanceOrQuestChance=30; -- Scythe Axe
INSERT IGNORE creature_loot_template SET entry=2090, item=5750, groupid=2, ChanceOrQuestChance=50; -- Warchief's Girdle
DELETE FROM reference_loot_template WHERE item IN (5749,5750);
");
Logs("Fix loot from Ma'ruk Wyrmscale (rare Orc, Wetlands): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=4015, item=5751, groupid=2, ChanceOrQuestChance=30; -- Webwing Cloak
INSERT IGNORE creature_loot_template SET entry=4015, item=5752, groupid=2, ChanceOrQuestChance=50; -- Wyvern Tailspike
DELETE FROM reference_loot_template WHERE item IN (5751,5752);
");
Logs("Fix loot from Pridewing Patriarch (rare wyvern, Stonetalon Mountains): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=3470, item=5111, groupid=2, ChanceOrQuestChance=50; -- Rathorian's Cape
INSERT IGNORE creature_loot_template SET entry=3470, item=5112, groupid=2, ChanceOrQuestChance=30; -- Ritual Blade
DELETE FROM reference_loot_template WHERE item IN (5111,5112);
");
Logs("Fix loot from Rathorian (rare Felguard, Barrens): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=1944, item=4439, groupid=2, ChanceOrQuestChance=30; -- Bruiser Club
INSERT IGNORE creature_loot_template SET entry=1944, item=5975, groupid=2, ChanceOrQuestChance=50; -- Ruffian Belt
DELETE FROM reference_loot_template WHERE item IN (4439,5975);
");
Logs("Fix loot from Rot Hide Bruiser (rare Gnoll, Silverpine Forest): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=1552, item=1604, groupid=2, ChanceOrQuestChance=30; -- Chromatic Sword
INSERT IGNORE creature_loot_template SET entry=1552, item=4478, groupid=2, ChanceOrQuestChance=50; -- Iridescent Scale Leggings
DELETE FROM reference_loot_template WHERE item IN (1604,4478);
");
Logs("Fix loot from Scale Belly (rare Basilisk, Stranglethorn Vale): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=1112, item=4444, groupid=2, ChanceOrQuestChance=60; -- Black Husk Shield
INSERT IGNORE creature_loot_template SET entry=1112, item=6199, groupid=2, ChanceOrQuestChance=30; -- Black Widow Band
DELETE FROM reference_loot_template WHERE item IN (4444,6199);
");
Logs("Fix loot from Leech Widow (rare Spider, Wetlands): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=1920, item=4437, groupid=2, ChanceOrQuestChance=30; -- Channeler's Staff
INSERT IGNORE creature_loot_template SET entry=1920, item=4436, groupid=2, ChanceOrQuestChance=50; -- Jewel-encrusted Sash
DELETE FROM reference_loot_template WHERE item IN (4437,4436);
");
Logs("Fix loot from Dalaran Spellscribe (rare Human, Silverpine Forest): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=1398, item=1938, groupid=2, ChanceOrQuestChance=35; -- Block Mallet
INSERT IGNORE creature_loot_template SET entry=1398, item=1215, groupid=2, ChanceOrQuestChance=50; -- Support Girdle
DELETE FROM reference_loot_template WHERE item IN (1938,1215);
");
Logs("Fix loot from Boss Galgosh (rare Trogg, Loch Modan): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=1425, item=2284, groupid=2, ChanceOrQuestChance=40; -- Rat Cloth Cloak
INSERT IGNORE creature_loot_template SET entry=1425, item=6195, groupid=2, ChanceOrQuestChance=40; -- Wax-polished Armor
DELETE FROM reference_loot_template WHERE item IN (2284,6195);
");
Logs("Fix loot from Grizlak (rare Kobold, Loch Modan): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=1399, item=2241, groupid=2, ChanceOrQuestChance=50; -- Desperado Cape
INSERT IGNORE creature_loot_template SET entry=1399, item=3571, groupid=2, ChanceOrQuestChance=40; -- Trogg Beater
DELETE FROM reference_loot_template WHERE item IN (2241,3571);
");
Logs("Fix loot from Magosh (rare Trogg, Loch Modan): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=5838, item=7559, ChanceOrQuestChance=25; -- Runic Cane
DELETE FROM reference_loot_template WHERE item IN (7559);
");
Logs("Fix loot from Brokespear (rare Centaur, Barrens): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=1911, item=4303, ChanceOrQuestChance=28; -- Cranial Thumper
DELETE FROM reference_loot_template WHERE item IN (4303);
");
Logs("Fix loot from Deeb (rare Murloc, Tirisfal Glades): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=5849, item=4785, ChanceOrQuestChance=25; -- Brimstone Belt
DELETE FROM reference_loot_template WHERE item IN (4785);
");
Logs("Fix loot from Digger Flameforge (rare Dwarf, Barrens): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=5863, item=1539, ChanceOrQuestChance=25; -- Gnarled Hermit's Staff
DELETE FROM reference_loot_template WHERE item IN (1539);
");
Logs("Fix loot from Geopriest Gukk'rok (rare Quilboar, Barrens): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=10899, item=21525, ChanceOrQuestChance=20; -- Green Winter Hat
DELETE FROM reference_loot_template WHERE item IN (21525);
");
Logs("Fix loot from Goraluk Anvilcrack (rare elite Orc, Upper Blackrock Spire): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=1119, item=2254, ChanceOrQuestChance=15; -- Icepane Warhammer
UPDATE creature_loot_template SET ChanceOrQuestChance=20 WHERE entry=1119 AND item=763; -- Ice-covered Bracers
DELETE FROM reference_loot_template WHERE item IN (2254,763);
");
Logs("Fix loot from Hammerspine (rare Trogg, Dun Morogh): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=5847, item=2035, ChanceOrQuestChance=27; -- Sword of the Night Sky
DELETE FROM reference_loot_template WHERE item IN (2035);
");
Logs("Fix loot from Heggin Stonewhisker (rare Dwarf, Barrens): %d rows" );

$count = MyRUN("
-- INSERT IGNORE creature_loot_template SET entry=947, item=4446, groupid=2, ChanceOrQuestChance=20; -- Blackvenom Blade
INSERT IGNORE creature_loot_template SET entry=947, item=4447, groupid=2, ChanceOrQuestChance=40; -- Cloak of Night
DELETE FROM reference_loot_template WHERE item IN (4447);
");
Logs("Fix loot from Rohh the Silent (rare Gnoll, Redridge Mountains): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=4132, item=8224, ChanceOrQuestChance=25; -- Silithid Ripper
DELETE FROM reference_loot_template WHERE item IN (8224);
");
Logs("Fix loot from Silithid Ravager (rare Silithid, Thousand Needles): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=1948, item=4445, ChanceOrQuestChance=23.67; -- Flesh Carver
DELETE FROM reference_loot_template WHERE item IN (4445);
");
Logs("Fix loot from Snarlmane (rare undead Gnoll, Silverpine Forest): %d rows" );

$count = MyRUN("
INSERT IGNORE creature_loot_template SET entry=7057, item=9382, ChanceOrQuestChance=0; -- Tromping Miner's Boots
DELETE FROM reference_loot_template WHERE item IN (9382);
");
Logs("Fix loot from Digmaster Shovelphlange (rare elite Goblin, outside Uldaman): %d rows" );


MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=0.013 /*YTDB*/ WHERE entry=8525 AND item=12808 AND ChanceOrQuestChance > 5; -- Scourge Warder had absurdly high 85%");
Logs("Fix too high drop chance for Essence of Undeath: %d creatures");


MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=100 /*YTDB*/ WHERE entry=1531 AND item=3322");
Logs("Fix too low drop chance for Wispy Cloak from Lost Soul (Tirisfal Glades): %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=100 /*YTDB*/ WHERE entry=1533 AND item=3323");
Logs("Fix too low drop chance for Ghostly Bracers from Tormented Spirit (Tirisfal Glades): %d loots");


MyOP("INSERT IGNORE fishing_loot_template SET entry=1477, item=11010, ChanceOrQuestChance=100, groupid=1, mincountOrRef=-11010");
Logs("Fix missing fishing loot in non-instanced Temple of Atal'Hakkar: %d loots");


MyOP("UPDATE creature_template SET skinloot=10366 WHERE entry IN (12739, 8976,7846,10258,10683,9461) AND skinloot=0");
Logs("Fix/make skinnable Onyxia's Elite Guard (Stormwind) and some other black dragons: %d creatures");


MyOP("INSERT IGNORE skinning_loot_template SET entry=(SELECT DISTINCT skinloot FROM creature_template WHERE entry IN (14887/*,14888,14889,14890*/)), item=20381, mincountOrRef=1, maxcount=2");
Logs("Fix/add Dreamscale to skinning loot of Taerar,Ysondre,Lethon,Emeriss: %d rows");


MyOP("INSERT IGNORE creature_loot_template (entry,item,ChanceOrQuestChance) VALUES
 (5648, 862, 0.02), (5648,9484, 0.02), -- Sandfury Shadowcaster
 (5650, 862, 0.02), (5650,9484, 0.02); -- Sandfury Witch Doctor
");
Logs("Fix/add missing rare items Runed Ring and Spellshock Leggings (Zul'Farrak): %d loots");


MyOP("DELETE FROM creature_loot_template WHERE entry IN (255) AND item IN (11614,11615,12827,12830); -- Gerard Tiller");
Logs("Fix/remove high-level Blacksmithing plans from Gerard Tiller (Elwynn Forest): %d loots");


MyOP("UPDATE creature_template SET mingold=0, maxgold=0 WHERE entry IN (10577,10699,8257,7769,14989,9178,10925, 9436, 10441, 1862, 11030, 6493) AND lootid=0; -- Crypt Scarab, Carrion Scarab, Oozeling, Hazzali Parasite, Burning Spirit, Rotting Worm, Spawn of Bael'Gar, Plagued Rat, Netherwalker, Mindless Undead, Illusionary Phantasm");
Logs("Fix/remove coppers from spawned creatures (oozelings etc): %d creatures");
                                                 

MyOP("UPDATE creature_template SET skinloot=0 WHERE entry IN (14022,14023,14024,14025)");
Logs("Fix/remove skinning loot from corrupted whelps (BWL): %d creatures");


MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=0.1 WHERE item=18704 AND entry!=6109 AND ChanceOrQuestChance=-100; -- all dragonkin except Azuregos");
Logs("Fix/lower drop chance for Mature Blue Dragon Sinew from Cobalt dragonkin (Winterspring): %d loots");


MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=1.22*3 WHERE item=14493 AND entry=7437");
Logs("Fix/lower drop chance for Pattern: Robe of Winter Night from Cobalt Mageweaver (Winterspring): %d loots");


MyOP("INSERT IGNORE item_loot_template (entry, item, ChanceOrQuestChance) VALUES
(20601, 20696, 2.3184), -- Crystal Spiked Maul
(20601, 20697, 2.1638), -- Crystalline Threaded Cape
(20601, 20698, 0.1546); -- Elemental Attuned Blade
");
Logs("Fix/add missing items to Sack of Spoils: %d loots");


MyOP("UPDATE item_loot_template SET ChanceOrQuestChance=100/*Nostalrius*/ WHERE entry=22320");
Logs("Fix chances for `Mux's Quality Goods` (Gadgetzan quest reward): %d loots");


MyOP("UPDATE item_loot_template SET ChanceOrQuestChance=0, groupid=1 WHERE entry=17727 AND ChanceOrQuestChance>0 AND groupid=0");
Logs("Fix content of `Smokywood Pastures Gift Pack` (Winter Veil event): %d loots");

MyOP("UPDATE item_loot_template SET ChanceOrQuestChance=0, groupid=1 WHERE entry=21310 AND ChanceOrQuestChance>0 AND groupid=0");
Logs("Fix content of `Gaily wrapped present` (Winter Veil event): %d loots");

MyOP("INSERT IGNORE item_loot_template (entry, item, groupid, ChanceOrQuestChance) VALUES
(21327, 17706, 2, 0),
(21327, 17709, 2, 0),
(21327, 17720, 2, 0),
(21327, 17722, 2, 0),
(21327, 17724, 2, 0),
(21327, 17725, 2, 0);
");
Logs("Fix/add missing items to Ticking Present (Winter Veil event): %d loots");


$count = MyRUN("
UPDATE disenchant_loot_template SET ChanceOrQuestChance=1,groupid=1 WHERE entry=50 AND item=20725; -- 1% Nexus Crystal
INSERT IGNORE disenchant_loot_template SET entry=50, item=14344, ChanceOrQuestChance=99, groupid=1; -- 99% Large Brilliant Shard
");
Logs("Fix disenchant loot from Rare items with ItemLevel>=71: %d loots" );


MyOP("UPDATE creature_template SET lootid=8929 WHERE entry=10076");
Logs("Fix loot for High Priestess of Thaurissan (BRD): %d creatures");


MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=25/*Nostalrius*/ WHERE entry=9196 AND item=12336 AND ChanceOrQuestChance BETWEEN 1 AND 20");
Logs("Increase drop chance of Gemstone of Spirestone (LBRS): %d loots");


if (USE_CONDITIONS and MyVAL("SELECT value1 FROM conditions WHERE type=4 AND value1=361") === null)
{
$count = MyRUN("
SET @cond_id := (SELECT MAX(condition_entry)+10 FROM conditions);
INSERT conditions SET condition_entry=@cond_id+0, type=4,  value1=361, value2=0; -- in Felwood
INSERT conditions SET condition_entry=@cond_id+1, type=-1, value1=197, value2=@cond_id+0; -- c1 AND c2
UPDATE gameobject_loot_template SET condition_id=@cond_id+1 WHERE condition_id=197;
UPDATE skinning_loot_template   SET condition_id=@cond_id+1 WHERE condition_id=197;
UPDATE creature_loot_template   SET condition_id=@cond_id+1 WHERE condition_id=197;
UPDATE reference_loot_template  SET condition_id=@cond_id+1 WHERE condition_id=197;
");
Logs("Fix tainted drops related to Cenarion Beacon - Felwood only: %d rows" );
}


if (USE_CONDITIONS) {
$count = MyRUN("
INSERT IGNORE conditions SET type=7,value1=164,value2=300;
SET @cond_id := (SELECT condition_entry FROM conditions WHERE type=7 AND value1=164 AND value2=300);
UPDATE gameobject_loot_template SET ChanceOrQuestChance=100,condition_id=@cond_id WHERE item IN (11614,11615,12827,12830) AND groupid=0 AND condition_id=0;
");
Logs("Fix chance and Blacksmithing 300 requirement to loot recipes from Blacksmithing Plans (BRD, Stratholme): %d rows" );
}


MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=15 WHERE item IN (12430,12431,12432,12433) AND ChanceOrQuestChance>0 AND ChanceOrQuestChance<10");
Logs("Fix/increase drop chance for E'ko (Winterspring): %d loots");


MyOP("DELETE FROM creature_loot_template WHERE item=18240 AND minCountOrRef>0 AND entry IN (14385, 417)");
Logs("Fix/remove Ogre Tanning drop from Doomguard Minion and Felhunter (Dire Maul): %d loots");


MyOP("DELETE FROM creature_loot_template WHERE item IN (18207,18146,18145) AND minCountOrRef>0");
Logs("Fix/do not drop Orc Tooth, Tauren Hoof, Darkspear Troll Mojo from NPCs (Alterac Valley): %d loots");

MyOP("DELETE FROM creature_loot_template WHERE item IN (17422,17423) AND entry IN (10981,10990, /*10985,10989,*/ 13676,13618, 11678,10986, 13419,13256, 14283)");
Logs("Fix/do not drop Armor Scraps and Storm Crystals from some inappropriate NPCs (Alterac Valley): %d loots");

MyOP("UPDATE creature_loot_template SET mincountOrRef=1,maxcount=1 WHERE item=17423");
Logs("Fix/minimize large numbers of Storm Crystal drops (Alterac Valley): %d loots");

//MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=50 WHERE item IN (17423,17306) AND ChanceOrQuestChance<0 AND groupid=0");
//Logs("Remove quest requirement from all loots of Storm Crystal and Stormpike Soldier's Blood (Alterac Valley): %d loots");

MyOP("UPDATE creature_loot_template SET ChanceOrQuestChance=50 WHERE item=17422 AND ChanceOrQuestChance<0 AND groupid=0");
Logs("Fix/remove quest requirement from all loots of Armor Scraps (Alterac Valley): %d loots");


MyOP("UPDATE creature_template SET lootid=13996 WHERE entry=14401");
// Непустой loot - мотивация не дать ему погибнуть от драконидов будучи под Mind Control (сверху)
Logs("Set loot from Master Elemental Shaper Krixix the same as from Blackwing Technicians (BWL): %d creatures");


// ПОСТ-ОБРАБОТКА

if (! FIRST_RUN) return;

$res = MyOP("SELECT ct.entry,
 (SELECT SUM(ChanceOrQuestChance) FROM creature_loot_template WHERE entry=ct.lootid AND mincountOrRef<0 AND ChanceOrQuestChance>0) AS sumchance
 FROM creature_template AS ct WHERE ct.rank IN (2,4) AND  ct.lootid!=0 AND
  (SELECT clt.entry FROM creature_loot_template AS clt JOIN item_template AS it ON clt.item=it.entry AND mincountOrRef>0
   WHERE clt.entry=ct.lootid AND (ChanceOrQuestChance=0  OR  quality >= 3  OR  ChanceOrQuestChance>=3 AND class IN (2,4) AND (quality>=2 OR ct.minlevel<=10 AND quality=1))
   LIMIT 1) IS NULL
");
$crea_sumchance = array();
while($row = mysql_fetch_object($res))
  if ($row->sumchance !== null)  $crea_sumchance[$row->entry] = $row->sumchance;
$count = 0;
foreach($crea_sumchance AS $entry => $sumchance) {
  if ($sumchance >= 20) continue;
  MyOP(
    "UPDATE creature_loot_template SET ChanceOrQuestChance = ChanceOrQuestChance * "
    .($sumchance <= 3 ? "15" : ($sumchance <= 5 ? "10" : ($sumchance <= 8 ? "8" : "5")))
    ." WHERE entry=$entry AND mincountOrRef < 0"
  );
  $count += mysql_affected_rows();
}
unset($crea_sumchance);
Logs("Ensure boosted chances for generic loot from Rare creatures without specific loot: %d loot groups" );

}


function FixItems()
{
global $count; PrintHeader(__FUNCTION__);

MyOP("UPDATE item_template SET subclass=0 WHERE class=4 AND subclass=3 AND InventoryType=12");
Logs("Fix trinkets to get rid of Mail requirement: %d items");

/* это по-любому неигровые вещи; есть другие entry с таким же названием
MyOP("UPDATE `item_template` SET `InventoryType`=5 WHERE  `entry`=3034");
Logs("Fix InventoryType for %d Glyphed Breastplate");

MyOP("UPDATE `item_template` SET `InventoryType`=9 WHERE  `entry`=5229");
Logs("Fix InventoryType for %d Handstitched Leather Bracers");
*/

MyOP("UPDATE item_template SET Duration=7200 WHERE  entry=9365");
Logs("Fix duration of High Potency Radioactive Fallout: %d items");

MyOP("UPDATE item_template SET Duration=1200 WHERE entry=18488");
Logs("Fix/limit duration of Heated Ancient Blade (20 min): %d items");


MyOP("UPDATE item_template SET spellcharges_1=-3, duration=14*24*60*60 WHERE entry=23379 AND spellcharges_1=-1 AND duration=0");
Logs("Fix Cinder Bracers (Midsummer reward) - must have 3 charges: %d items");

MyOP("UPDATE item_template SET duration=3*24*60*60, ExtraFlags=ExtraFlags|2 WHERE entry=21212");
Logs("Fix/limit duration of Fresh Holly (Winter Veil): %d items");

MyOP("UPDATE item_template SET ExtraFlags=ExtraFlags|2 WHERE entry IN (/*Burning Blossom*/23247,/*Cinder Bracers*/23379, /*Lunar Festival Invitation*/21711, /*Wand of Holiday Cheer*/21328)");
Logs("Fix duration type to realtime for items from Seasonal Events: %d items");


$count = MyRUN("
UPDATE item_template SET RequiredReputationFaction=890 WHERE RequiredReputationRank !=0 AND RequiredReputationFaction=0 AND 14753 IN (SELECT entry FROM npc_vendor WHERE item=item_template.entry); -- Silverwing Sentinels reputation for items sold by Illiyana Moonblaze
UPDATE item_template SET RequiredReputationFaction=889 WHERE RequiredReputationRank !=0 AND RequiredReputationFaction=0 AND 14754 IN (SELECT entry FROM npc_vendor WHERE item=item_template.entry); -- Warsong Outriders reputation for items sold by Kelm Hargunth
UPDATE item_template SET RequiredReputationFaction=730 WHERE RequiredReputationRank !=0 AND RequiredReputationFaction=0 AND 13216 IN (SELECT entry FROM npc_vendor WHERE item=item_template.entry); -- Stormpike Guard reputation for items sold by Gaelden Hammersmith
UPDATE item_template SET RequiredReputationFaction=729 WHERE RequiredReputationRank !=0 AND RequiredReputationFaction=0 AND 13218 IN (SELECT entry FROM npc_vendor WHERE item=item_template.entry); -- Frostwolf Clan reputation for items sold by Grunnda Wolfheart
UPDATE item_template SET RequiredReputationFaction=529 WHERE RequiredReputationRank !=0 AND RequiredReputationFaction=0 AND 10856 IN (SELECT entry FROM npc_vendor WHERE item=item_template.entry); -- Argent Dawn reputation for items sold by Argent Quartermaster Hasana
UPDATE item_template SET RequiredReputationFaction=59  WHERE RequiredReputationRank !=0 AND RequiredReputationFaction=0 AND 12944 IN (SELECT entry FROM npc_vendor WHERE item=item_template.entry); -- Thorium Brotherhood reputation for items sold by Lokhtos Darkbargainer
UPDATE item_template SET RequiredReputationFaction=576 WHERE RequiredReputationRank !=0 AND RequiredReputationFaction=0 AND 11555 IN (SELECT entry FROM npc_vendor WHERE item=item_template.entry); -- Timbermaw Hold reputation for items sold by Gorn One Eye
UPDATE item_template SET RequiredReputationRank=0 WHERE RequiredReputationRank !=0 AND RequiredReputationFaction=0 AND entry IN (15742,15754); -- Timbermaw Hold reputation not required for Pattern: Warbear Harness, Pattern: Warbear Woolies (are dropped, not sold)
");
Logs("Fix Faction requirement for lots of quartermaster items: %d items" );

MyOP("UPDATE item_template SET spellcharges_1=1 WHERE entry=17204 AND spellcharges_1=-1");
// Требует самого себя как реагент, поэтому должен быть нерасходуемым при использовании, иначе их нужно 2
Logs("Fix `Item not ready yet` error on use of Eye of Sulfuras: %d items");


MyOP("UPDATE item_template SET DisenchantID=29 WHERE entry=20086; -- disenchantable in SDB");
Logs("Fix Dusksteel Throwing Knife, allow disenchant: %d items");


MyOP("UPDATE item_template SET spellcharges_1=-3 WHERE entry=15778 AND spellcharges_1=-1");
Logs("Fix Mechanical Yeti (quest reward) - must have 3 charges: %d items");


MyOP("UPDATE item_template SET class=13,subclass=0/*YTDB*/ WHERE entry IN (11197,8444) AND class=0");
Logs("Fix item class of Dark Keeper Key (BRD) and Executioner's Key (Zul'Farrak), for Auction convenience: %d items");


MyOP("UPDATE item_template SET spellcooldown_1=3*24*60*60*1000 WHERE spellid_1=24325 AND entry=19974");
// В cMangos нет SD2 скрипта, использовать вещь почему-то можно без ограничения по местности (Pagle's Pointe в ZG)
Logs("Hackfix/set 3-day cooldown on Mudskunk Lure to prevent repeating Gahz'ranka summons (ZG): %d items");


MyOP("UPDATE item_template SET spellcooldown_1=3000 WHERE entry=20004 AND spellid_1=24361");
Logs("Fix/set cooldown for Major Troll's Blood Potion to make the item usable: %d items");

}


function FixNPC()
{
global $count; PrintHeader(__FUNCTION__);

MyOP("UPDATE npc_trainer SET reqskillvalue=200 WHERE spell IN (20653,10485) AND reqskillvalue=180");
Logs("Fix Leatherworking req.skill 200 for Thick Leather, Cured Thick Hide: %d rows");

MyOP("UPDATE npc_trainer SET reqskillvalue=250 WHERE spell IN (22332,19147,19148) AND reqskillvalue=230");
Logs("Fix Leatherworking req.skill 250 for Rugged Leather, Cured Rugged Hide, Rugged Armor Kit: %d rows");


MyOP("INSERT IGNORE npc_vendor SET entry=12941, item=15756");
Logs("Fix/add Pattern: Runic Leather Headband to Jase Farlane (EPL): %d items");

MyOP("DELETE FROM npc_vendor WHERE entry=14846 AND item IN (13456, 13468); -- Greater Frost Protection Potion and Black Lotus not present in SDB");
Logs("Fix/remove non-Classic items from vendor Lhara (Darkmoon Faire): %d items");


// Удалить Mighty Troll's Blood Elixir у обычного Expert наставника. Этому учит Henry Stern в Razorfen Dawns
MyOP("DELETE FROM npc_trainer WHERE entry=11042 AND spell=13030");
Logs("Fix/remove Mighty Troll's Blood Elixir from Sylvanna Forestmoon (Darnassus): %d spells");


// Торговец алкоголем Malgin Barleybrew в Barrens, Bael'dun Keep
$count = MyRUN("
UPDATE creature_template SET faction_A=122, faction_H=122, npcflag=132 WHERE  entry=5848;
INSERT IGNORE npc_vendor SET  entry=5848, item=2593;
INSERT IGNORE npc_vendor SET  entry=5848, item=2594;
INSERT IGNORE npc_vendor SET  entry=5848, item=2595;
INSERT IGNORE npc_vendor SET  entry=5848, item=2596;
INSERT IGNORE npc_vendor SET  entry=5848, item=2723;
");
Logs("Fix Vendor Malgin Barleybrew (Barrens, Bael'dun Keep): %d rows" );


/*
if (USE_CONDITIONS)
{
$count = MyRUN("
UPDATE gossip_menu_option SET condition_id=178 WHERE menu_id IN (6092,6094); -- require Engineering 260, removes Gnome/Goblin Engineering requirement
"); // были condition_id 192 и 191, теперь нужно только Engineering 260
Logs("Remove Gnomish/Goblin Engineering requirement from Gadgetzan/Everlook Transporter trainers: %d rows" );
}
*/

MyOP("DELETE FROM npc_trainer WHERE spell IN (23490,23491) AND entry=8736");
Logs("Fix/remove Everlook and Gadgetzan Transporters schematics from goblin Buzzek Bracketswing (Gadgetzan): %d rows");


MyOP("DELETE FROM npc_trainer WHERE spell=18249 AND entry=14740");
Logs("Fix/remove Artisan Fishing from Katoom the Angler (Hammerfell): %d trainers");


MyOP("INSERT IGNORE npc_gossip SET npc_guid=(SELECT guid FROM creature WHERE id=7998 LIMIT 1), textid=1693");
Logs("Fix Blastmaster Emi Shortfuse Gossip text: %d gossips");


MyOP("INSERT IGNORE npc_gossip SET npc_guid=(SELECT guid FROM creature WHERE id=3678 LIMIT 1), textid=698");
Logs("Fix Disciple of Naralex Gossip text: %d gossips");


MyOP("UPDATE npc_text SET text0_0=\"On the northern dock, you can board a ship that will carry you to Rut'theran Village and Darnassus. From the southern dock, you can find passage across the Great Sea to Menethil Harbor on Khaz Modan. Safe journeys to you!\" WHERE ID IN (10555,5480) AND INSTR(text0_0,'Exodar')");
Logs("Fix gossip text for Thamarian (Night Elf, Darkshore): %d texts");


$count = MyRUN("
UPDATE creature_template SET npcflag=npcflag&~1048576|2048 WHERE entry IN (14990,14991,15102); -- Defilers Emissary, League of Arathor Emissary, Silverwing Emissary
");
Logs("Fix Battlemaster status of Emissaries: %d creatures" );

MyOP("UPDATE creature_template SET npcflag=npcflag&~1 WHERE npcflag=1+4 AND gossip_menu_id=0 AND (SELECT textid FROM npc_gossip WHERE npc_guid IN (SELECT guid FROM creature WHERE id=entry) LIMIT 1) IS NULL");
Logs("Fix vendors having gossip flag, but no gossip texts/options: %d creatures");

if (USE_CONDITIONS)
{
MyOP("DELETE FROM gossip_menu_option WHERE id=2 AND option_text IS NULL AND option_id=16 AND npc_option_npcflag=16 AND action_menu_id=0 AND condition_id=0");
Logs("Fix/remove empty gossip options from some of Paladin/Shaman/Mage/Rogue trainers: %d options");
}

/*
MyOP("INSERT IGNORE creature_template_addon SET entry=7898, auras=4986");
Logs("Invisibility for `Pirate treasure trigger mob` (Cuergo's Gold quest): %d creatures");
*/


function AddTakeGossipOption($npc, $quest, $item, $itemName, $optionNum)
{
$menu_id = MyVAL("SELECT gossip_menu_id FROM creature_template WHERE entry=$npc");
if ($menu_id !== null and $menu_id != 0) {
$gossip_last = MyVAL("SELECT MAX(N) FROM (SELECT COUNT(*) AS N FROM gossip_menu_option WHERE menu_id=(SELECT gossip_menu_id FROM creature_template WHERE entry=$npc)) AS NumEntries");
if (++$gossip_last == $optionNum) {

$count = MyRUN("
SET @action_id := (SELECT MAX(id)+1 FROM dbscripts_on_gossip);
INSERT dbscripts_on_gossip SET id=@action_id, command=17, datalong=$item, datalong2=1, comments=\"Create Item - $itemName\";
SET @cond_id := (SELECT condition_entry FROM conditions WHERE type=8 AND value1=$quest AND value2=0);
SET @cond_id := IF(@cond_id IS NULL, (SELECT MAX(condition_entry)+10 FROM conditions), @cond_id);
INSERT IGNORE conditions SET condition_entry=@cond_id, type=8, value1=$quest;
INSERT gossip_menu_option SET menu_id=$menu_id, id=$gossip_last, option_text=\"Take $itemName\", option_id=1, npc_option_npcflag=1, action_menu_id=-1, action_script_id=@action_id, box_coded=0, box_money=0, box_text=NULL, condition_id=@cond_id;
");

Logs("Fix/add menu option to NPC %d to take $itemName: %d rows", $npc, $count);
}}
}
if (USE_DBSCRIPTS) {
    AddTakeGossipOption(8579, 3528, 10818, "Yeh'kinya's Scroll", 1);
    AddTakeGossipOption(13716,7046, 17191, "Scepter of Celebras", 2);
    AddTakeGossipOption(10307, 975, 12384, "Cache of Mau'ari", 3);
}

if (USE_CONDITIONS) 
do {
$menu_id = MyVAL("SELECT gossip_menu_id FROM creature_template WHERE entry=7607");
if ($menu_id === null or $menu_id == 0)  break;

$count = MyRUN("
INSERT IGNORE conditions SET type=33, value1=10, value2=0; -- previously used wrong id 390 with value1=19 related to Pusillin in Dire Maul
UPDATE gossip_menu_option SET condition_id=(SELECT condition_entry FROM conditions WHERE type=33 AND value1=10 AND value2=0) WHERE menu_id=$menu_id AND condition_id IN (390,0);
");

Logs("Fix waypoint number where gossip option becomes enabled for Weegle Blastfuse (Zul'Farrak): %d rows" );
} while(false);

}


function FixMissingCreatures()
{
global $count; PrintHeader(__FUNCTION__);

$count = MyRUN("
UPDATE creature_template SET minmana=1600, maxmana=1600, faction_A=152, faction_H=152 WHERE entry=4842 AND minmana=0 AND maxmana=0 AND faction_A=32 AND faction_H=32;
");
$count += IsCreatureGuidExists(4842) ? 0 :
MyRUN("","
 INSERT creature SET id=4842,
 map=47, position_x=2137.48, position_y=1705.32, position_z=80.7048, orientation=3.49861,
 spawntimesecs=21600, spawndist=10, curhealth=3289, curmana=1600, MovementType=1;
");
Logs("Fix/add Earthcaller Halmgar (rare elite, Razorfen Kraul): %d rows" );


$count = MyRUN("
UPDATE creature_template SET minmana=1926, maxmana=1926, MovementType=2 WHERE entry=6228 AND minmana=0 AND maxmana=0 AND MovementType=1;
");
$count += MyVAL("SELECT guid FROM creature WHERE id=6228") !== null ? 0 :
MyRUN("", "
 INSERT creature SET id=6228,
 map=90, position_x=-670.959, position_y=700.469, position_z=-331.599, orientation=2.79324,
 spawntimesecs=21600, spawndist=3, curhealth=4924, curmana=1926, MovementType=2;
");
$count += MyRUN("", "
INSERT IGNORE creature_movement_template (entry, point, position_x, position_y, position_z,  orientation) VALUES
(6228, 1,  -670.959, 700.469, -331.599, 2.79324),
(6228, 2,  -681.021, 703.321, -331.087, 2.86785),
(6228, 3,  -699.948, 706.936, -330.782, 2.93461),
(6228, 4,  -711.55,  704.961, -330.782, 3.35087),
(6228, 5,  -726.669, 696.458, -330.782, 3.7043 ),
(6228, 6,  -732.787, 675.869, -330.748, 4.419  ),
(6228, 7,  -738.058, 656.47,  -322.064, 4.43472),
(6228, 8,  -740.584, 647.778, -321.699, 4.46613),
(6228, 9,  -745.422, 627.984, -312.896, 4.45044),
(6228, 10, -747.379, 619.931, -312.783, 4.46222),
(6228, 11, -752.768, 600.302, -304.067, 4.45042),
(6228, 12, -752.768, 600.302, -304.067, 4.45042),
(6228, 13, -755.976, 578.582, -303.782, 4.58003),
(6228, 14, -752.988, 600.057, -303.941, 1.32845),
(6228, 15, -747.104, 619.802, -312.783, 1.34415),
(6228, 16, -744.996, 627.542, -312.783, 1.37163),
(6228, 17, -739.913, 647.863, -321.782, 1.28523),
(6228, 18, -737.531, 656.281, -322.041, 1.31272),
(6228, 19, -732.373, 676.094, -330.781, 1.32843),
(6228, 20, -728.248, 692.276, -330.783, 0.939658),
(6228, 21, -711.47,  705.714, -330.783, 0.495909),
(6228, 22, -700.726, 705.705, -330.783, 6.19398),
(6228, 23, -687.432, 702.892, -330.788, 6.04476);
");
Logs("Fix/add Dark Iron Ambassador (rare elite, Gnomeregan): %d rows" );


for($count = 0; is_null($guid = MyVAL("SELECT guid FROM creature WHERE id=15119")); )
    $count += MyRUN("INSERT creature SET id=15119, map=0, position_x=-4960.39, position_y=-933.914, position_z=501.66, orientation=5.47344, spawntimesecs=600, spawndist=0, curhealth=3517; -- Add Barrus <Fishing Promoter> (Ironforge)");
$count += MyRUN("
INSERT IGNORE game_event_creature SET guid=$guid, event=14; -- Assign Barrus to event 'Fishing Extravaganza Announce';
");
Logs("Fix/add NPC Barrus (Ironforge, event Fishing Extravaganza Announce): %d rows" );


$count = IsCreatureGuidExists(5081) ? 0 :
MyRUN("
INSERT creature SET id=5081, map=0, position_x=-9102, position_y=834.873, position_z=105.117, orientation=5.18, spawntimesecs=600, spawndist=0, curhealth=713, MovementType=0;
");
Logs("Fix/add missing questgiver Connor Rivers: %d guids" );


$count = MyVAL("SELECT guid FROM creature WHERE id=6490") !== null ? 0 :
MyRUN("
INSERT creature SET id=6490, map=189, position_x=1755.1, position_y=1400.77, position_z=20.9539, orientation=5.58465, spawntimesecs=7200, spawndist=10, curhealth=2765, curmana=1870, MovementType=1;
");
Logs("Fix/add missing Azshir the Sleepless (rare elite Human, Scarlet Monastery Graveyard): %d creatures" );


$count = IsCreatureGuidExists(723) ? 0 :
MyRUN("INSERT creature SET id=723, map=0, position_x=-12482.2, position_y=-958.652, position_z=40.6509, orientation=1.42566, spawntimesecs=21600, spawndist=0, curhealth=5947, MovementType=1");
Logs("Fix/add Mosh'Ogg Butcher: %d guids" );

$count = IsCreatureGuidExists(5400) ? 0 :
MyOP("INSERT creature SET id=5400, map=0, position_x=-10238.4, position_y=-3998.45, position_z=-109.881, orientation=5.96744, spawntimesecs=28800, curhealth=6352, spawndist=10, MovementType=1");
Logs("Fix/add Zekkis (rare Troll, outside Temple of Atal'Hakkar): %d guids" );

$count = IsCreatureGuidExists(5399) ? 0 :
MyOP("INSERT creature SET id=5399, map=109, position_x=-414.111, position_y=23.1485, position_z=-90.8587, orientation=5.53157, spawntimesecs=6600, curhealth=6261, spawndist=10, MovementType=1");
Logs("Fix/add Veyzhak the Cannibal (rare Troll, Temple of Atal'Hakkar): %d guids" );

$count = IsCreatureGuidExists(3652) ? 0 :
MyOP("INSERT creature SET id=3652, map=1, position_x=-621.612, position_y=-2270.82, position_z=18.8419, orientation=2.67112, spawntimesecs=28800, curhealth=1341, spawndist=0");
Logs("Fix/add Trigore the Lasher (rare Hydra, outside Wailing Caverns): %d guids" );

$count = IsCreatureGuidExists(14237) ? 0 :
MyOP("INSERT creature SET id=14237, map=1, position_x=-4240.73, position_y=-2866.63, position_z=37.1291, orientation=5.23007, spawntimesecs=259200, curhealth=2508, spawndist=5, MovementType=1");
Logs("Fix/add Oozeworm (rare Rock borer, Dustwallow Marsh): %d guids" );

$count = IsCreatureGuidExists(14236) ? 0 :
MyOP("INSERT creature SET id=14236, map=1, position_x=-4190, position_y=-4011, position_z=-9, orientation=4.337, spawntimesecs=259200, curhealth=6455, spawndist=4, MovementType=1");
Logs("Fix/add Lord Angler (rare Makrura, Dustwallow Marsh): %d guids" );

$count = IsCreatureGuidExists(9718) ? 0 :
MyOP("INSERT creature SET id=9718, map=229, position_x=-94.917, position_y=-339.754, position_z=70.9524, orientation=1.55013, spawntimesecs=259200, curhealth=8996, spawndist=5, MovementType=1");
Logs("Fix/add Ghok Bashguud (rare elite Orc, Lower Blackrock Spire): %d guids" );


$count = IsCreatureGuidExists(5981) ? 0 :
MyRUN("", "
INSERT creature (id,map,position_x,position_y,position_z,orientation,spawntimesecs,spawndist,curhealth,curmana,MovementType) VALUES
(5981, 0, -11359, -2797, 5.421, 4.76,  430, 7, 2131, 0, 1);
");
Logs("Fix/add missing Portal Seeker creature (Blasted Lands): %d rows" );


$count = IsCreatureGuidExists(5432) ? 0 :
MyRUN("
UPDATE creature_template SET type_flags=type_flags|1,PetSpellDataId=5931 WHERE entry=5432; -- tameable, has Bite 7
","
INSERT creature (id,map,position_x,position_y,position_z,orientation,spawntimesecs,spawndist,curhealth,curmana,MovementType) VALUES
(5432, 1, -10260, -3792, 0.569, 2.841, 430, 4, 7088, 0, 1),
(5432, 1, -10257, -3874, 2.209, 2.441, 430, 4, 7088, 0, 1),
(5432, 1, -10254, -4093, 0.567, 3.711, 430, 4, 7088, 0, 1),
(5432, 1, -10200, -3943, 3.372, 1.621, 430,15, 7088, 0, 1),
(5432, 1, -10145, -3699, 0.151, 1.476, 430,15, 7088, 0, 1),
-- (5432, 1, -10119, -4055, 5.396, 2.164, 430,15, 7088, 0, 1), -- Cuergo's Gold location
(5432, 1, -10103, -3846, 5.825, 0.791, 430,15, 7088, 0, 1),
(5432, 1, -10100, -4246, 0.558, 3.181, 430,15, 7088, 0, 1),
-- (5432, 1, -10094, -4147, 4.887, 4.363, 430,15, 7088, 0, 1), -- near airplane wreck
(5432, 1, -10021, -3726, 7.162, 0.37,  430,15, 7088, 0, 1),
(5432, 1, -10007, -3596, 0.59,  1.329, 430,15, 7088, 0, 1),
(5432, 1,  -9989, -4221, 6.916, 1.987, 430,15, 7088, 0, 1),
(5432, 1,  -9944, -4370, 0.551, 3.518, 430,15, 7088, 0, 1),
(5432, 1,  -9855, -3637, 11.177,6.259, 430,15, 7088, 0, 1),
(5432, 1,  -9855, -3556, 0.715, 2.209, 430,15, 7088, 0, 1),
(5432, 1,  -9836, -4304, 8.469, 1.723, 430,15, 7088, 0, 1),
(5432, 1,  -9754, -4453, 0.569, 4.148, 430,15, 7088, 0, 1),
(5432, 1,  -9718, -4372, 5.972, 3.225, 430,15, 7088, 0, 1),
(5432, 1,  -9628, -4404, 0.569, 1.831, 430,15, 7088, 0, 1);
");
Logs("Fix/add missing Giant Surf Glider creatures (Tanaris): %d rows" );

/*
$count = IsCreatureGuidExists(14506) ? 0 :
MyRUN("","
INSERT creature (id,map,position_x,position_y,position_z,orientation,spawntimesecs,spawndist,curhealth,curmana,MovementType) VALUES
(14506, 429, -2.88275, 705.305, -24.5804, 4.4783, 7200, 0, 31080, 5136, 0);
");
Logs("Add missing rare elite Lord Hel'nurath (@Dire Maul) as static spawn: %d rows" );
*/

$count = MyVAL("SELECT guid FROM creature WHERE id IN (8718,8717,12396) AND map=0 AND (position_x BETWEEN -11891 AND -11763) AND (position_y BETWEEN -3256 AND -3144) AND ABS(-14 - position_z) < 100") !== null ? 0 :
MyRUN("","
INSERT creature
(id, map, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, curhealth, MovementType) VALUES
(8718, 0, -11891,-3199,-14, 0.175, 6300, 0, 47563, 0),
(8717, 0, -11891,-3196,-14, 0.04,  6300, 0, 55230, 0),
(8718, 0, -11889,-3214,-14, 0.176, 6300, 0, 47563, 0),
(8717, 0, -11888,-3216,-14, 0.304, 6300, 0, 55230, 0),
(8717, 0, -11876,-3187,-15, 0.114, 6300, 0, 55230, 0),
(8717, 0, -11871,-3222,-15, 0.134, 6300, 0, 55230, 0),
(8717, 0, -11848,-3192,-29, 0.005, 6300, 0, 55230, 0),
(8718, 0, -11848,-3186,-29, 0.092, 6300, 0, 47563, 0),
(8717, 0, -11846,-3210,-29, 0.146, 6300, 0, 55230, 0),
(8718, 0, -11845,-3216,-29, 0.103, 6300, 0, 47563, 0),
(8717, 0, -11830,-3226,-30, 3.899, 6300, 9, 55230, 1),
(8717, 0, -11837,-3256,-26, 1.352, 6300, 0, 55230, 0),
(8717, 0, -11813,-3186,-31, 2.646, 6300, 9, 55230, 1),
(8717, 0, -11809,-3235,-30, 1.333, 6300, 0, 55230, 0),
(8717, 0, -11819,-3144,-26, 5.63,  6300, 7, 55230, 1),
(12396,0, -11804,-3233,-30, 1.56,  6300, 0, 34350, 0),
(8717, 0, -11799,-3237,-30, 1.756, 6300, 0, 55230, 0),
(8717, 0, -11804,-3146,-26, 4.828, 6300, 0, 55230, 0),
(12396,0, -11800,-3150,-26, 4.596, 6300, 0, 34350, 0),
(8717, 0, -11789,-3222,-30, 4.636, 6300, 9, 55230, 1),
(8718, 0, -11791,-3168,-29, 0.462, 6300, 9, 47563, 1),
(8717, 0, -11792,-3149,-26, 4.427, 6300, 0, 55230, 0),
(8717, 0, -11778,-3182,-29, 4.439, 6300, 9, 55230, 1),
(8718, 0, -11763,-3199,-24, 5.08,  6300, 9, 47563, 1),
(8717, 0, -11766,-3159,-22, 0.683, 6300, 9, 55230, 1);
");
Logs("Fix/add missing Elite demons around Dark Portal (Blasted Lands): %d guids" );


$count = MyVAL("SELECT COUNT(guid) FROM creature WHERE id=12125 AND map=1") > 2 ? 0 :
MyRUN( // YTDB data + modified
"UPDATE creature_template SET modelid_2=12208, maxlevel=57, maxhealth=11136, speed_run=2.0, mingold=0, maxgold=0 WHERE entry=12125",
"INSERT creature
(id, map, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, curhealth, MovementType) VALUES
(12125, 1, 2247.58, -7314.71, -32.7716, 5.07, 900, 30, 8267, 1),
(12125, 1, 2141.54, -7237.98, -32.0054, 1.83, 900, 30, 8267, 1),
(12125, 1, 3575.07, -6375.80, -33.5823, 4.58, 900, 30, 8267, 1),
(12125, 1, 5107.84, -6557.01, -22.2130, 5.69, 900, 30, 8267, 1),
(12125, 1, 2787.04, -7286.35, -13.3887, 2.88, 900, 30, 8267, 1),
(12125, 1, 4146.76, -6796.36, -12.9569, 1.08, 900, 30, 8267, 1),
(12125, 1, 4029.04, -6521.56, -11.6539, 2.93, 900, 30, 8267, 1),
(12125, 1, 2807.91, -7145.15, -24.6603, 1.25, 900, 30, 8267, 1),
(12125, 1, 5164.87, -6681.64, -30.1950, 5.30, 900, 30, 8267, 1);
");
Logs("Fix/add missing Mammoth Shark elite creatures (Azshara): %d rows" );


$count = MyVAL("SELECT guid FROM creature WHERE id=10441 AND map=329") !== null ? 0 :
MyRUN("","
INSERT creature (id, map, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, curhealth) VALUES
(10441, 329, 3698.92, -3633,    139.911, 1.86605, 7200, 0, 798), -- Plagued Rat
(10441, 329, 3623.84, -3627.79, 138.853, 3.90023, 7200, 0, 798),
(10441, 329, 3582.39, -3470.66, 135.393, 2.03884, 7200, 0, 798),
(10441, 329, 3546.05, -3379.63, 132.549, 1.43015, 7200, 0, 798),
(10441, 329, 3472.81, -3379.6,  135.962, 3.12269, 7200, 0, 798),
(10441, 329, 3553.33, -3353.96, 129.911, 1.21024, 7200, 0, 798),
(10441, 329, 3778.26, -3580.02, 142.439, 3.65283, 7200, 0, 798),
(10441, 329, 3717.27, -3600.17, 141.841, 0.507305,7200, 0, 798),
(10441, 329, 3644.87, -3594.51, 137.722, 0.432695,7200, 0, 798),
(10441, 329, 3633.95, -3509.38, 136.426, 1.91317, 7200, 0, 798),
(10461, 329, 3570.37, -3354.58, 130.923, 1.49691, 7200, 0, 750), -- Plagued Insect
(10461, 329, 3530.95, -3342.88, 130.699, 2.23911, 7200, 0, 750),
(10461, 329, 3558.25, -3328.61, 129.403, 4.65028, 7200, 0, 750),
(10461, 329, 3539.64, -3409.33, 133.913, 4.65028, 7200, 0, 750),
(10461, 329, 3422.90, -3380.03, 141.688, 3.08341, 7200, 0, 750),
(10461, 329, 3495.72, -3395.43, 137.787, 5.63595, 7200, 0, 750),
(10536, 329, 3522.53, -3401.26, 133.425, 5.18434, 7200, 0, 820), -- Plagued Maggot
(10536, 329, 3629.79, -3502.55, 136.589, 5.64772, 7200, 0, 820);
"); // YTDB
Logs("Fix/add missing Plagued Rats, Insects and Maggots (Stratholme): %d guids" );


$count = MyVAL("SELECT guid FROM creature WHERE id=10819") !== null ? 0 :
MyRUN("
INSERT creature SET id=10819, map=0, position_x=3104.2, position_y=-3711.8, position_z=132.547, orientation=2.32201, spawntimesecs=19800, spawndist=5, curhealth=3998, curmana=0, MovementType=1;
");
Logs("Fix/add missing rare Baron Bloodbane (EPL): %d guids" );


$count = MyVAL("SELECT guid FROM creature WHERE id=11887 AND map=0") !== null ? 0 :
MyRUN("","
INSERT creature (id, map, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, curhealth, MovementType) VALUES
(11887, 0, 1569.40, -3272, 88.154, 0.285, 430, 3, 5149, 1),
(11887, 0, 1572.08, -3278, 89.318, 0.348, 430, 3, 5149, 1),
(11887, 0, 1576.60, -3275, 89.088, 0.168, 430, 3, 5149, 1),
(11887, 0, 1939.64, -2561, 61.335, 0.859, 430, 3, 5149, 1),
(11887, 0, 1941.22, -2523, 61.039, 1.487, 430, 3, 5149, 1),
(11887, 0, 1943.96, -2557, 61.040, 3.004, 430, 3, 5149, 1);
"); // SDB
Logs("Fix/add missing Crypt Robbers (WPL, EPL): %d guids" );


$count = MyVAL("SELECT COUNT(*) FROM creature WHERE id=8538 AND map=0") > 2 ? 0 :
MyRUN("
INSERT creature (id, map, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, curhealth, MovementType) VALUES
(8538, 0, 1967.87, -4462, 74.394, 3.490, 600, 4, 3665, 1),
(8538, 0, 2026.09, -4538, 74.664, 6.038, 600, 7, 3665, 1),
(8538, 0, 2092.11, -4532, 76.169, 3.204, 600, 4, 3665, 1),
(8538, 0, 2104.73, -4635, 75.404, 0.808, 600, 4, 3665, 1),
(8538, 0, 2166.23, -4502, 73.726, 1.046, 600, 4, 3665, 1),
(8538, 0, 2376.41, -4651, 77.874, 0.111, 600, 4, 3665, 1),
(8538, 0, 2407.92, -4445, 73.921, 0.256, 600, 4, 3665, 1); -- YTDB
",
"REPLACE creature_template_addon SET entry=8538, b2_0_sheath=1, b2_1_flags=16, auras='8279 6408'; -- Detect Stealth, Faded",
"DELETE ca FROM creature_addon AS ca JOIN creature AS c USING(guid) WHERE id=8538;"
);
Logs("Add more Unseen Servants, the only source of Patterns for Ghostweave Vest (EPL): %d rows" );


$count = MyVAL("SELECT guid FROM creature WHERE id IN (11447,11497,11498) AND map=1") !== null ? 0 :
MyRUN("
INSERT creature (id, map, position_x, position_y, position_z, orientation, spawntimesecs, spawndist, curhealth, MovementType) VALUES
(11447, 1, -3758.47, 1096.15, 131.97, 3.34614, 25200, 10, 60811, 1), -- Mushgog
(11497, 1, -3753.20, 1097.89, 131.97, 3.46003, 25200, 10, 74479, 1), -- The Razza
(11498, 1, -3753.20, 1097.89, 131.97, 3.46003, 25200, 10, 59085, 1); -- Skarr the Unbreakable
",
"SET @POOL=(SELECT MAX(entry) FROM pool_template)+1",
"INSERT pool_template SET entry=@POOL, max_limit=1, description=''",
"INSERT pool_creature SET guid=(SELECT guid FROM creature WHERE id=11497 AND map=1), pool_entry=@POOL, chance=50, description='The Razza, no Skarr'",
"INSERT pool_creature SET guid=(SELECT guid FROM creature WHERE id=11498 AND map=1), pool_entry=@POOL, chance=50, description='Skarr, no The Razza'",
"UPDATE creature_template SET lootid=entry WHERE entry IN (11447,11497,11498) AND lootid=0",
"INSERT IGNORE creature_loot_template (entry, item, ChanceOrQuestChance, mincountOrRef) VALUES
(11447, 24016, 100, -24016),
(11447, 24024,  10, -24024),
(11447, 35015, 100, -35015),
(11497, 24016, 100, -24016),
(11497, 24024,  10, -24024),
(11497, 35015, 100, -35015),
(11498, 24016, 100, -24016),
(11498, 24024,  10, -24024),
(11498, 35015, 100, -35015);"
); // Nostalrius
Logs("Fix/add 3 missing Dire Maul Arena rare combatants (Feralas): %d rows" );


$count = MyVAL("SELECT guid FROM creature WHERE id=15440") !== null ? 0 :
MyRUN("
INSERT creature SET id=15440, map=1, position_x=-7168.18, position_y=1389.3, position_z=2.91802, orientation=6.24593, spawntimesecs=25, spawndist=0, curhealth=24000, MovementType=0;
");
Logs("Fix/add missing questgiver Captain Blackanvil (Silithus): %d guids" );

}


function FixCreaturePlacement()
{
global $count; PrintHeader(__FUNCTION__);

MyOP("UPDATE creature SET position_x=-4875.47, position_y=-1109.89,position_z=502.212 WHERE guid=1895 AND id=5595 AND map=0");
Logs("Fix initial position for Ironforge Guard patrolling around Great Forge: %d guids");


MyOP("UPDATE creature SET position_z=200.85+10, spawndist=15 WHERE guid=53999 AND id=14388 AND position_z < 200.85+10");
Logs("Raise one of flying Rogue Black Drakes from ground (Burning Steppes): %d guids");


$count = MyVAL("SELECT guid FROM creature WHERE guid=51692 AND id=5357") === null ? 0 :
MyRUN("DELETE FROM creature WHERE guid=51697 AND id=5358; -- this Cliff Giant #51697 has the same coordinates as Land Walker #51692");
Logs("Fix Cliff Giant / Land Walker collision (Feralas): %d rows" );


MyOP("UPDATE creature SET position_x=1032.46, position_y=1479.80, position_z=37.48 WHERE id=1766 AND FLOOR(position_x)=1029 AND FLOOR(position_y)=1474 AND FLOOR(position_z)=36; -- GUID 17952");
Logs("Fix/relocate Mottled Worg spawned inside a tree (Silverpine Forest): %d guids");

MyOP("UPDATE creature SET position_x=1618.04, position_y=-5615.69, position_z=101.28, orientation=1.80 WHERE id=9448 AND FLOOR(position_x)=1617 AND FLOOR(position_y)=-5614; -- GUID 56554");
Logs("Fix/relocate Scarlet Praetorian spawned inside a tree (EPL): %d guids");

MyOP("UPDATE creature SET position_x=1578.53, position_y=-5321.02, position_z=75.887047, orientation=5.28 WHERE id=9447 AND FLOOR(position_x)=1580 AND FLOOR(position_y)=-5322; -- GUID 92054");
Logs("Fix/relocate Scarlet Warder spawned in a table (EPL): %d guids");

/*
MyOP("UPDATE creature SET map=0, position_x=-8752.3, position_y=402.5, position_z=101.056, orientation=4.48 WHERE guid=15");
Logs("Relocate Sergeant Biggins outside Champions' Hall: %d creatures");
*/


MyOP("UPDATE creature SET spawndist=5, MovementType=1 WHERE (id IN (14361,14398) OR id=11469 AND guid IN (136179,136173)) AND spawndist=0 AND MovementType=0");
Logs("Animate overlapping/too static spawns of Shen'dralar Wisp, Eldreth Darter, Eldreth Seether (Dire Maul): %d guids");


$count = 0;
if (MyVAL("SELECT COUNT(*) FROM creature_movement WHERE id=80283") == 21) {
$count = MyRUN("", "
INSERT IGNORE creature_movement (id, point, position_x, position_y, position_z, waittime, emote, orientation) VALUES
(80283, 22, -9550.16, -68.9811, 57.4588,     0, 0, 1.3598 ),
(80283, 23, -9543.96, -40.0566, 56.5451,     0, 0, 1.11475),
(80283, 24, -9507.09,  35.1121, 56.517,      0, 0, 0.98909),
(80283, 25, -9492.11,  57.8834, 55.8784,     0, 0, 0.70321),
(80283, 26, -9483.7,   65.0161, 56.1693, 10000, 0,-0.05706),
(80283, 27, -9455.61,  63.4114, 55.8832,     0, 0, 0.58068),
(80283, 28, -9393.01,  104.486, 59.2978,     0, 0, 0.27909),
(80283, 29, -9363.17,  113.038, 61.4675,     0, 0, 0.54299),
(80283, 30, -9328.93,  133.697, 64.341,      0, 0, 0.47701),
(80283, 31, -9298.35,  149.504, 66.412,      0, 0, 0.28223),
(80283, 32, -9257.91,  161.229, 67.623,      0, 0, 0.86343),
(80283, 33, -9233.09,  190.265, 67.82,       0, 0, 0.80374),
(80283, 34, -9194.35,  230.449, 71.8101,     0, 0, 1.2467 ),
(80283, 35, -9184.62,  259.409, 73.981,      0, 0, 1.55144),
(80283, 36, -9183.56,  314.518, 79.2184,     0, 0, 1.42263),
(80283, 37, -9181.78,  326.43,  81.1904,     0, 0, 1.21529),
(80283, 38, -9175.93,  342.185, 84.2532,     0, 0, 0.85086),
(80283, 39, -9160.48,  359.541, 89.109,      0, 0, 0.79902),
(80283, 40, -9145.05,  375.98,  90.7306,     0, 0, 0.75897);
");
}
Logs("Fix waypoints for Kira Songshine (Elwynn Forest): %d waypoints" );


$count = MyRUN("", "
INSERT IGNORE creature_movement_template (entry, point, position_x, position_y, position_z, orientation) VALUES
(10202, 1, 6015.8, -5033.05, 782.859, 0.282755),
(10202, 2, 6098.29, -5023.02, 789.547, 5.77312),
(10202, 3, 6137.2, -5046.62, 788.99, 0.026845),
(10202, 4, 6283.54, -5042.69, 771.248, 0.026845),
(10202, 5, 6406.52, -5030.09, 745.262, 0.573787),
(10202, 6, 6444, -5009.44, 737.39, 0.930053),
(10202, 7, 6498.31, -4935.84, 727.041, 0.935071),
(10202, 8, 6553.56, -4869.03, 704.398, 1.58739),
(10202, 9, 6552.9, -4829.49, 705.146, 1.45692),
(10202, 10, 6566.46, -4730.9, 698.258, 1.44187),
(10202, 11, 6570.4, -4640.59, 694.241, 2.39526),
(10202, 12, 6514.25, -4587.68, 715.585, 2.36515),
(10202, 13, 6470.6, -4537.83, 720.399, 1.94365),
(10202, 14, 6453.42, -4493.91, 734.055, 1.82322),
(10202, 15, 6436.27, -4421.44, 723.7, 2.63109),
(10202, 16, 6374.7, -4386.96, 739.173, 2.39024),
(10202, 17, 6340.67, -4359.44, 741.747, 1.9286),
(10202, 18, 6321.45, -4319.45, 734.259, 1.47198),
(10202, 19, 6324.78, -4285.85, 732.48, 2.86693),
(10202, 20, 6275.08, -4272.11, 735.528, 2.1544),
(10202, 21, 6258.4, -4246.29, 735.27, 2.14437),
(10202, 22, 6274.7, -4271.84, 735.551, 6.01812),
(10202, 23, 6325.64, -4285.94, 732.287, 4.62317),
(10202, 24, 6321.94, -4319.59, 734.278, 5.12997),
(10202, 25, 6340.73, -4359.74, 741.776, 5.59663),
(10202, 26, 6375.68, -4387.8, 738.779, 5.79232),
(10202, 27, 6436.53, -4421.69, 723.74, 5.02961),
(10202, 28, 6453.64, -4494.76, 734.031, 5.03965),
(10202, 29, 6470.7, -4538.43, 720.404, 5.39591),
(10202, 30, 6514.34, -4587.73, 715.556, 5.45111),
(10202, 31, 6570.57, -4640.84, 694.228, 4.6884),
(10202, 32, 6566.41, -4731.7, 698.175, 4.51277),
(10202, 33, 6552.84, -4829.72, 705.159, 4.6884),
(10202, 34, 6553.56, -4869.43, 704.485, 4.03019),
(10202, 35, 6498.09, -4936.16, 727.093, 3.99005),
(10202, 36, 6443.77, -5009.57, 737.462, 3.66891),
(10202, 37, 6406.04, -5030.53, 745.354, 3.23235),
(10202, 38, 6282.95, -5042.82, 771.337, 3.15207),
(10202, 39, 6136.82, -5046.69, 789.015, 2.67537),
(10202, 40, 6097.37, -5022.56, 789.355, 3.23737);
"); // Source: PSDB
if ($count > 0)  $count += MyRUN("
-- UPDATE creature_template SET MovementType=2 WHERE entry=10202;
UPDATE creature SET position_x=6015.8, position_y=-5033.05, position_z=782.859, orientation=0.282755, MovementType=2 WHERE id=10202 LIMIT 1; -- Azurous, waypoint movement
");
Logs("Fix waypoints for Azurous (rare elite Drake, Winterspring): %d rows" );


$count =
  MyVAL("SELECT COUNT(guid) FROM creature WHERE id=14339") >= 2 && 
  MyVAL("SELECT id FROM pool_creature_template WHERE id=14339") === null &&
  ($ptsingle = MyVAL("SELECT entry FROM pool_template WHERE max_limit=1")) !== null ?
  MyRUN("INSERT pool_creature_template SET id=14339, pool_entry=$ptsingle, chance=0, description='Death Howl (14339)'")
  : 0;
Logs("Fix/pool Death Howl (rare wolf, Felwood): %d rows" );

if (USE_DBSCRIPTS and FIRST_RUN) {
MyOP("REPLACE dbscripts_on_quest_start SET id=4023, delay=2, command=10, datalong=9461, datalong2=60000, x=-7655.97, y=-3020.78, z=132.3514, o=4.964, comments='Quest:Taste of Flame - Summon Frenzied Black Drake'");
Logs("Change position of summoned Frenzied Black Drake to block cave entrance (Burning Steppes): %d rows");
}


$count = MyRUN("
UPDATE creature SET position_x=-8582.03, position_y=633.634, position_z=96.3386, orientation=5.02218 WHERE id=1368; -- Justin
UPDATE creature SET position_x=-8580.51, position_y=635.108, position_z=96.3386, orientation=5.02218 WHERE id=1370; -- Brandon
UPDATE creature SET position_x=-8583.88, position_y=633.127, position_z=96.3386, orientation=5.02218 WHERE id=1371; -- Roman
");
Logs("Fix initial placement of 3 boys at dock (Stormwind): %d creatures" );


MyOP("UPDATE creature SET spawndist=20 WHERE id=15505 AND map=509 AND MovementType=1 AND spawndist<10");
Logs("Increase random movement distance for Canal Frenzy (AQ20): %d creatures");


MyOP("UPDATE creature SET MovementType=1,spawndist=20 WHERE id=11374 AND map=309 AND MovementType=0 AND spawndist=0");
Logs("Fix/enable random movement for Hooktooth Frenzy (ZG): %d creatures");

}


function FixCreatureOnKillReputation()
{
global $count; PrintHeader(__FUNCTION__);

$count = MyRUN("
UPDATE creature_onkill_reputation SET RewOnKillRepFaction1=21 WHERE RewOnKillRepFaction1=169;
UPDATE creature_onkill_reputation SET RewOnKillRepFaction2=21 WHERE RewOnKillRepFaction2=169;
");
Logs("creature_onkill_reputation FactionIDs changed from Steamwhidle Cartel to Booty Bay: %d" );

MyOP("DELETE FROM creature_onkill_reputation WHERE creature_id=10582");
Logs("Fix/remove Dog (Freewind Post) from onkill REP table: %d rows");


/*
MyOP("UPDATE creature_onkill_reputation SET MaxStanding1=4 WHERE creature_id IN (10481,10485,10482,10391,10390,10399,10480) AND RewOnKillRepFaction1=529 AND MaxStanding1=5");
Logs("Fix/stop onkill REP after Honored for non-elite creatures in Stratholme and Scholomance: %d rows");
*/

MyOP("UPDATE creature_onkill_reputation SET MaxStanding1=5 WHERE creature_id=8550 AND RewOnKillRepFaction1=529 AND MaxStanding1=4");
Logs("Fix/prolong onkill REP until Revered for Shadowmages (EPL): %d rows");


MyOP("UPDATE creature_onkill_reputation SET MaxStanding1=IF(RewOnKillRepValue1 < 0 AND MaxStanding1 < 7,10+MaxStanding1,MaxStanding1), MaxStanding2=IF(RewOnKillRepValue2 < 0 AND MaxStanding2 < 7,10+MaxStanding2,MaxStanding2)");
Logs("Fix negative onkill REP not applied in case of high standing: %d rows");

}


function FixCreatures()
{
global $count; PrintHeader(__FUNCTION__);

$count = MyRUN("
UPDATE creature_template SET rank=1 WHERE rank=3 AND entry IN (8017,9236,14884,15334,15726,15757); -- Sen'jin Guardian, Shadow Hunter Vosh'gajin, Parasitic Serpent, Giant Eye Tentacle, Eye Tentacle, Qiraji Lieutenant General
");
Logs("Fix/remove illegal Worldboss rank from some Elites: %d creatures" );


global $creature_classic_rare;
MyOP("UPDATE creature_template SET
 rank = IF(NOT name IN ($creature_classic_rare), CASE rank WHEN 4 then 0 WHEN 2 then 1 ELSE rank END, -- fix illegal Rares
   IF(name IN (". rtrim(preg_replace('/(?<!\+)"[^",]+"(?:, )?/', '', $creature_classic_rare),', '). "), 2, 4)) WHERE rank IN (0,1,2,3,4)"
);
// Source: all Rare creatures - wowwiki, RareElite - compared to HGC/Oregon/Mangos-TBC230 DBs
Logs("Fix missing and illegal Rare and RareElite ranks: %d creatures");


MyOP("UPDATE creature_template SET InhabitType=3 WHERE entry IN (4821,4822,4823, 4686,4687, 5467, 3231); -- Skittering/Snapping/Barbed Crustacean (BFD), Deepstrider Giant/Searcher (Desolace), Deep Dweller (Tanaris), Corrupted Dreadmaw Crocolisk (Durotar)");
Logs("Fix InhabitType for some water+ground creatures: %d creatures");


MyOP("UPDATE creature_template SET unit_flags=unit_flags&~512, flags_extra=flags_extra&~2, Civilian=0 WHERE
INSTR(name, 'Guard ')=1 AND NOT entry IN (12423,464) -- except Guard Parker and Guard Roberts
OR INSTR(name, 'Brave ')=1
OR INSTR(name, 'Battleguard')
OR INSTR(name, 'Deathguard')"); // includes Stormpike Battleguard, Frostwolf Battleguard
Logs("Make some more Alliance and Horde warriors agressive: %d creatures");

MyOP("UPDATE creature_template SET Civilian=0, unit_flags=unit_flags&~512, flags_extra=flags_extra&~2 WHERE faction_A IN (10,11,23,33,57,71,79,85,105,113,121,150,231,232,250,475,495,637,854,877,1054,1096,1134,1154,1495,1554,1615,1624,1635) AND NOT entry IN (12423,464)"); // except Guard Parker and Guard Roberts
Logs("Remove Civilian and NoAggro flags from NPCs with PvP icon: %d creatures");

// Убийство неагрессивных NPC Орды/Альянса влечёт потерю некоторого количества Honor c возможностью понижения воинского звания
// NB: У всех Civilian выставлен флаг NO_AGGRO
// NB: Не существует Civilian гоблинов принадлежащих к Booty Bay, Ratchet, Gadgetzan
MyOP("UPDATE creature_template SET Civilian=1, flags_extra=flags_extra|2 WHERE unit_flags&512 AND type=7 AND ScriptName='' AND NOT faction_A IN (/*Booty Bay*/120,121,390,/*Ratchet*/69,637,/*Gadgetzan*/474,475,/*Escortee*/113,/*Orc,Blackrock*/40)");
Logs("Set dishonorable kill `Civilian` to humanoids with UNIT_FLAG_PASSIVE: %d creatures");

MyOP("UPDATE creature_template SET flags_extra=flags_extra&~1024 WHERE flags_extra&2 OR Civilian!=0");
Logs("Remove wrong GUARD flag from some NoAggro creatures (trainers etc.): %d creatures");


MyOP("UPDATE creature_template SET Civilian=0, unit_flags=unit_flags&~512, flags_extra=flags_extra|2 WHERE entry IN (12423,464)");
Logs("Make Guard Parker (Redridge) and Guard Roberts (Elwynn) non-agressive non-Civialians: %d creatures");

MyOP("UPDATE creature_template SET flags_extra=flags_extra&~2 WHERE entry IN (80)");
Logs("Fix/remove wrong NO_AGGRO flag from Kobold Laborer: %d creatures");

MyOP("UPDATE creature_template SET flags_extra=flags_extra|2 WHERE entry=3094");
Logs("Fix/make Unseen creatures non-aggressive (Darkshire): %d creatures");


// Чтобы они стали PvP, надо сменить faction_X с 68 (Undercity) на 71 (Undercity) и не сбрасывать флаг UNIT_FLAG_PVP (4096)
// UNIT_FLAG_PVP в Creature.cpp: Creature::UpdateEntry() сбрасывается или
// устанавливается в зависимости от шаблона фракции; если этого не делать,
// то рядовые персонажи становятся PvP 
MyOP("UPDATE creature_template SET Civilian=0, unit_flags=unit_flags&~512&~4096, flags_extra=flags_extra&(~2) WHERE entry IN (5418,5414); -- Deathstalker Zraedus, Apothecary Faustin");
Logs("Make two Duskwood L40 Hordies agressive (but keep non-PvP): %d creatures");


MyOP("UPDATE creature_template SET unit_flags=unit_flags&~524288 WHERE entry IN (424,2103); -- Redridge Poacher, Dragonmaw Scout");
Logs("Fix/reset UNIT_FLAG_IN_COMBAT for: %d creatures");


MyOP("UPDATE creature_template SET unit_flags=unit_flags&~2, mindmg=269*2, maxdmg=346*2 WHERE entry IN (10080,10081)");
Logs("Fix non-attackable trolls Dustwraith and Sandarr Dunereaver (Zul'Farrak): %d creatures");


MyOP("UPDATE creature_template SET speed_walk=0.00001, speed_run=0.00001, unit_flags=0x00048204/* флаг UNIT_FLAG_DISABLE_MOVE ничего не даёт, сбрасывается для Guardian'а */ WHERE entry IN (2673,2674,12426)");
Logs("Disable movement for Target Dummies (act as Guardian Pets): %d creatures");


MyOP("UPDATE creature_template SET flags_extra=flags_extra|0x4000 WHERE entry=4166");
Logs("Disable mmaps for Gazelles (Barrens), their waypoints are too far from each other: %d creatures");

MyOP("UPDATE creature_template SET flags_extra=flags_extra|0x4000 WHERE entry=14304");
Logs("Disable mmaps for Kor'kron Elite (Orgrimmar), they cannot jump from ledges: %d creatures");

MyOP("UPDATE creature_template SET flags_extra=flags_extra|0x4000 WHERE entry=14517");
// вероятно и без этого будет работать, она не движется, за исключением Charge сверху из логова вниз
Logs("Disable mmaps for High Priestess Jeklik (ZG), just in case: %d creatures");


MyOP("UPDATE creature_template SET flags_extra=flags_extra|64 WHERE entry IN (8437); -- Hakkari Minion");
Logs("Fix/disable XP gain for some spawned creatures: %d creatures");


MyOP("UPDATE creature_template SET unit_flags=2|0x100|32768, flags_extra=2|64 WHERE entry=8982");
Logs("No combat/XP with Ironhand Guardians (BRD): %d creatures");


// У всех существ с equipslot3=25 было equipinfo3=33492994=01FF1002, из-за
// 01FF они метали кубики. Теперь Defias Smuggler метает ножи,
// Skullsplitter Axe Thrower - топорики, Torn Fin Coastrunner - копья
MyOP("UPDATE creature_equip_template_raw SET equipinfo3=0x19011002 /* InvType(25) Material(1) Subclass(16) Class(2) */ WHERE equipinfo3 IN (0x01FF1002,0x02FF1002) AND equipslot3 IN (25,1817)");
Logs("Fix \"throwing boxes\" shown instead of throwing daggers/axes/spears/etc: %d equips");


function CopyEquipmentId($src, $dst) {
MyOP("UPDATE creature_template AS ct JOIN creature_template AS ct0 ON ct0.entry=$src SET ct.equipment_id=ct0.equipment_id WHERE ct.entry IN ($dst) AND ct.equipment_id=0");
}

CopyEquipmentId(7038/*Thaurissan Agent*/, 8978);
Logs("Fix equipment for Thauris Balgarr (rare dwarf, Burning Steppes), so he could shoot: %d creatures");

CopyEquipmentId(2184/*Lady Moongazer*/, "6647,16052,16097"); // Magister Hawkhelm, Malgen Longspear (his spear model @ equipment_id 613), Isalien");
Logs("Fix bow equipment for some creatures, so they could shoot: %d creatures");

CopyEquipmentId(879/*Saltscale Hunter*/, 578);
Logs("Fix spear equipment for Murloc Scout (Redridge Mountains), so they could throw: %d creatures");

CopyEquipmentId(1744/*Deathguard Mort*/, 15138);
Logs("Fix axe equipment for summoned Silverpine Elite: %d creatures");


MyOP("UPDATE creature_template SET speed_walk=1 WHERE entry IN (8978,6647); -- Thauris Balgarr, Magister Hawkhelm");
Logs("Fix speed for some creatures: %d creatures");


MyOP("UPDATE creature_template SET speed_walk=1.0, speed_run=2.14286, minhealth=64, maxhealth=64 WHERE entry=4277 AND speed_run<2");
Logs("Fix speed of Eye of Kilrogg (Warlock's summon): %d creatures");


// Исправляет ошибку, когда Captain Greenskin в Deadmines появляется как Undead (перепутаны номера моделей)
$count = MyRUN("
UPDATE creature_template SET modelid_1=7113, modelid_2=0 WHERE entry=15373 AND modelid_1=3494 AND modelid_2=7113;
UPDATE creature_model_info SET modelid_other_gender=0 WHERE modelid=3494 AND modelid_other_gender=7113;
UPDATE creature_model_info SET modelid_other_gender=0 WHERE modelid=7113 AND modelid_other_gender=3494;
");
Logs("Fix Captain Greenskin model: %d rows" );

MyOP("UPDATE creature_template SET modelid_1=11686 WHERE entry=14989; -- Poisonous Cloud model number from HGDB/TDB, see also creature 15933");
Logs("Fix/change model (a child[262] to void) for Poisonous Cloud spawned by Son of Hakkar (ZG): %d creatures");


MyOP("UPDATE creature SET modelid=14393 WHERE id=14358");
Logs("Fix model of Shen'dralar Ancient - female (Dire Maul): %d creatures");

MyOP("UPDATE creature_template SET faction_A=14, faction_H=14 WHERE entry=11472 AND faction_A=92");
Logs("Fix faction of Eldreth Spirit, align with nearby creatures (Dire Maul): %d creatures");


MyOP("UPDATE creature SET modelid=0 WHERE id=1949");
Logs("Fix/allow Female gender for Servants of Azora: %d guids");


$count = MyRUN("
UPDATE creature_model_info SET modelid_other_gender=0 WHERE  modelid=4016;
UPDATE creature_template SET faction_A=14, faction_H=14 WHERE  entry=13082;
");
Logs("Fix gender and faction for Milton Beats (Ravenholdt): %d rows" );

$count = MyRUN("
UPDATE creature_template SET faction_A=87,  faction_H=87  WHERE entry IN (14281, 2638); -- Jimmy the Bleeder, Syndicate Spectre
UPDATE creature_template SET faction_A=108, faction_H=108 WHERE entry IN (13149,13150,13151); -- Syndicate Brigand,Syndicate Agent,Syndicate Master Ryson
UPDATE creature_model_info SET modelid_other_gender=0 WHERE modelid IN (3616,3618); -- Syndicate Rogue male and female models (just as in YTDB)
"); // Jimmy the Bleeder был нейтральным, а Syndicate xxxx были как Rothide Gnolls (faction = 70)
Logs("Fix gender and faction for Jimmy the Bleeder etc. (Alterac Mountains): %d rows" );


$count = MyRUN("
UPDATE creature SET modelid=7310 WHERE guid=90391 AND modelid=7311; -- 7311 is invalid: has female voice, but male in looks
UPDATE creature_model_info SET modelid_other_gender=0 WHERE modelid=7310; -- disable use of 7311 as alternative to 7310
");
Logs("Fix model/voice combination for Protector of the People (Westfall): %d rows" );


$count = MyRUN("
UPDATE creature_model_info SET gender=1 WHERE modelid IN (5446, 6782,11157,11161,11163,11164) AND gender=2; -- Justine Demalier (Stormwind), high elf females
UPDATE creature_model_info SET gender=0 WHERE modelid IN (796,11357, 6779) AND gender=2; -- pirates, high elf
");
Logs("Fix gender of some models: %d models" );


MyOP("UPDATE creature_template SET minlevel=35, maxlevel=35 WHERE  entry=522"); // был уровень 38
Logs("Fix level for Mor'Ladim to match the Quest Level: %d creatures");


MyOP("INSERT IGNORE creature_template_addon SET entry = 6729, auras = 6408");
Logs("Stealth aura for dwarf Morridune in Blackfathom Deeps: %d creatures");


MyOP("DELETE FROM creature_template_addon WHERE entry=13020");
Logs("Fix Vaelastrasz the Corrupt STAND_STATE after evade (BWL): %d creatures");


MyOP("UPDATE creature_template SET minlevel=62, maxlevel=62, minhealth=3277, maxhealth=3277, armor=4348 WHERE entry=14984");
Logs("Fix level and health for Sergeant Maclear (Arathi Highlands): %d rows");


MyOP("UPDATE creature_template SET minlevel=63, maxlevel=63, rank=3 WHERE entry=15362");
Logs("Fix level and rank for Malfurion Stormrage (@Moonglade): %d creatures");

if (FIRST_RUN) {
// Более адекватные параметры вождей фракций и др. сильных существ
// HP и Mana взяты с https://vanilla-twinhead.twinstar.cz/?npc=1748 и Nostalrius
// Для Magni, Cairne, Vol'jin и Thrall есть и SD2 скрипты, и EventAI
$count = MyRUN("
UPDATE creature_template SET minhealth=799500, maxhealth=minhealth, minmana=52400, maxmana=minmana, mingold=866, maxgold=2060 WHERE entry=1748; -- Highlord Bolvar Fordragon
UPDATE creature_template SET minhealth=1332400,maxhealth=minhealth, mingold=866, maxgold=4750 WHERE entry=2784; -- King Magni Bronzebeard, было крайне мало HP; ScriptName='boss_magni_bronzebeard'
UPDATE creature_template SET RacialLeader=1, flags_extra=0, minhealth=1332400,maxhealth=minhealth, mingold=866, maxgold=7250 WHERE entry=7937; -- High Tinker Mekkatorque: было мало HP; был Elite NoAggro, а не worldboss
UPDATE creature_template SET minhealth=780000,maxhealth=minhealth, minmana=52400, maxmana=minmana, mingold=866, maxgold=5750 WHERE entry=7999; -- Tyrande Whisperwind
UPDATE creature_template SET minhealth=462000,maxhealth=minhealth, minmana=492480,maxmana=minmana, mingold=100000, maxgold=200000 WHERE entry=4968; -- Lady Jaina Proudmoore
UPDATE creature_template SET minhealth=1066000,maxhealth=minhealth, minmana=78600, maxmana=minmana, mingold=866, maxgold=7250 WHERE entry=4949; -- Thrall
UPDATE creature_template SET minhealth=1332400,maxhealth=minhealth, mingold=866, maxgold=7450  WHERE entry=3057; -- Cairne Bloodhoof: было слишком мало HP; ScriptName='npc_cairne_bloodhoof'
UPDATE creature_template SET RacialLeader=1, subname='King of Darkspear Trolls', minhealth=976800, maxhealth=minhealth, minmana=38944, maxmana=minmana, rank=3, mingold=866, maxgold=7250  WHERE entry=10540; -- был Elite, а не worldboss; ScriptName='npc_voljin'
UPDATE creature_template SET minhealth=670000,maxhealth=minhealth, minmana=52400, mingold=866, maxgold=7250, ScriptName='npc_lady_sylvanas_windrunner' WHERE entry=10181; -- Sylvanas Windrunner, было слишком мало HP
UPDATE creature_template SET minhealth=647400, maxhealth=647400, mindmg=2000, maxdmg=3000, mingold=1, maxgold=873 WHERE entry=10182; -- Rexxar
UPDATE creature_template SET minlevel=62, maxlevel=62, minhealth=154100, maxhealth=152600, mindmg=3000, maxdmg=5000, armor=3000, mingold=0, maxgold=0 WHERE entry=10204; -- Misha
UPDATE creature_template SET RacialLeader=0 WHERE entry=15423; -- Caldorei Infantry
");
Logs("Strengthen Alliance and Horde Leaders: %d rows" );

MyOP("UPDATE creature_template SET minhealth=1332400, maxhealth=minhealth, mindmg=3850, maxdmg=5110, unit_flags=unit_flags&~32768 WHERE entry=15467; -- ClassicDB");
Logs("Strengthen boss Omen, disable Swimming (Moonglade, Lunar Festival): %d creatures");

MyOP("UPDATE creature_template SET minhealth=1000616, maxhealth=minhealth, mindmg=2000, maxdmg=2100 WHERE entry=15625 AND minhealth<=190000; -- Nostalrius");
Logs("Strengthen boss Twilight Corrupter (Duskwood, Scepter of the Shifting Sands quest line): %d creatures"); // было слишком мало HP и dmg

MyOP("UPDATE creature_template SET rank=1, mindmg=2400,maxdmg=2600, attackpower=290 WHERE entry=15552 AND mindmg<=600; -- Nostalrius");
Logs("Fix rank and strengthen Doctor Weavil (Alcaz Island): %d creatures"); // было слишком мало dmg, ClassicDB:1170-1500
}

MyOP("UPDATE creature_template SET rank=1, mindmg=1639,maxdmg=1791, attackpower=330 WHERE entry=15591 AND mindmg<=800; -- Nostalrius");
Logs("Fix rank and strengthen Minion of Weavil (Alcaz Island): %d creatures"); // было слишком мало dmg

MyOP("UPDATE creature_template SET mindmg=1587,maxdmg=2105, attackpower=278 WHERE entry=15554 AND mindmg<=600; -- Nostalrius");
Logs("Strengthen Number Two (Alcaz Island): %d creatures"); // было слишком мало dmg

MyOP("UPDATE creature_template SET mindmg=mindmg * IF(entry=12803,3,2), maxdmg=maxdmg * IF(entry=12803,3,2) WHERE mindmg < 700 AND entry IN (12803/*Lord Lakmaeran*/,12800/*Chimaerok*/,12801/*Arcane Chimaerok*/,12802/*Chimaerok Devourer*/); -- Nostalrius");
Logs("Strengthen 4 species of Chimaeroks (Feralas, Isle of Dread): %d creatures");

MyOP("UPDATE creature_template SET mindmg=972,maxdmg=1287, attackpower=262 WHERE entry=15629 AND mindmg<=500; -- ClassicDB");
Logs("Strengthen Nightmare Phantasm (Moonglade): %d creatures");

MyOP("UPDATE creature_template SET minhealth=969550,maxhealth=minhealth,mindmg=3169,maxdmg=4096,speed_walk=1 WHERE entry=14834 AND maxdmg>=5702; -- Nostalrius");
Logs("Decrease damage and healthen boss Hakkar (ZG): %d creatures");

MyOP("UPDATE creature_template SET mindmg=1530,maxdmg=2280,baseattacktime=2000 WHERE entry=10162 AND maxdmg<1000; -- YTDB (much faster attacks according to Nostalrius: 0.8 vs 2.0)");
Logs("Increase damage from Lord Victor Nefarius (BWL): %d creatures");

MyOP("UPDATE creature_template SET mindmg=400,maxdmg=600,baseattacktime=2000 WHERE entry=16124 AND maxdmg<100");
Logs("Increase damage from Unrelenting Trainee (Naxxramas): %d creatures");

MyOP("UPDATE creature_template SET minhealth=8700,maxhealth=9156 WHERE entry=15043 AND maxhealth>=29256");
Logs("Decrease health of Zulian Crocolisks (ZG): %d creatures");

MyOP("UPDATE creature_template SET minhealth=7325/*Kronos*/, maxhealth=7325 WHERE entry=13421 AND minhealth<6000");
Logs("Healthen Champion Guardian (Alterac Valley): %d creatures");

MyOP("UPDATE creature_template SET minhealth=15720/*Kronos*/, maxhealth=15720 WHERE entry=13446 AND minhealth<10000");
Logs("Healthen Field Marshal Teravaine (Alterac Valley): %d creatures");

MyOP("UPDATE creature_template SET minhealth=3144/*Kronos*/, maxhealth=3144 WHERE entry=13816 AND minhealth<3000");
Logs("Healthen Prospector Stonehewer (Alterac Valley): %d creatures");

MyOP("UPDATE creature_template SET minhealth=3297/*Allakhazam @2005,YTDB*/, maxhealth=3297 WHERE entry=14479 AND minhealth<3000; -- was HP 1259 (SDB)");
Logs("Healthen Twilight Lord Everun (Silithus): %d creatures");


$count = MyRUN("
UPDATE creature_template SET faction_A=1216, faction_H=1216 WHERE entry IN (14946,13797,13086,13335,13336,13525,13554,13557,13548,13317,13551) AND faction_A=32 AND faction_H=32; -- Slidore's Gryphon, Mountaineer Boombellow, Aggi Rumblestomp, Veteran Mountaineer, Veteran Sentinel, Seasoned Commando, Champion Irondeep Guard, Champion Irondeep Surveyor, Champion Coldmine Explorer, Coldmine Miner, Champion Coldmine Invader
UPDATE creature_template SET faction_A=1214, faction_H=1214 WHERE entry IN (14943,13421,13099) AND faction_A=32 AND faction_H=32; -- Guse's War Rider, Champion Guardian, Irondeep Explorer
");
Logs("Fix faction for Alterac Valley enemies (previously neutral): %d creatures" );

MyOP("UPDATE creature SET position_x=-1138.28, position_y=-424.918, position_z=56.6286, orientation=1.34722 WHERE map=30 AND id=14946 LIMIT 1");
Logs("Change location of Slidore's Gryphon (Alterac Valley), or else he will kill all nearby Horde guards: %d guids");


MyOP("UPDATE creature_template SET type=2 WHERE entry IN (14755,14756) AND type >= 12");
Logs("Fix type for Tiny Green/Red Dragon companions: %d creatures");


MyOP("UPDATE creature_template SET minmana=0, maxmana=0 WHERE entry=5615");
Logs("Fix/remove mana from Wastewander Rogue (Tanaris): %d creatures");


MyOP("UPDATE creature_template SET MovementType=1 WHERE entry IN (10441,10461,10536); -- Plagued Rat, Plagued Insect, Plagued Maggot");
Logs("Fix/set random Movement type for plagued critters that could be spawned by trap (Stratholme): %d creatures");


MyOP("INSERT IGNORE creature_template SET entry=15118, modelid_1=15234, armor=17, name='Master Angler Form'");
Logs("Fix Master Angler Form: %d creatures");


MyOP("UPDATE creature_template SET mechanic_immune_mask=mechanic_immune_mask&~2048 WHERE entry IN (10503/*Jandice Barov*/, 11622/*Rattlegore*/, 10508/*Ras Frostwhisper*/, 10504/*Lord Alexei Barov*/, 10507/*The Ravenian*/, 10901/*Lorekeeper Polkelt*/, 10505/*Instructor Malicia*/); -- youtube tZ-s1EXoL4Y");
Logs("Fix/remove Stun Immunity from some creatures (according to old videos): %d creatures");

MyOP("UPDATE creature_template SET mechanic_immune_mask=mechanic_immune_mask|16|64|512|2048|4096|16384|131072, resistance2=1000, resistance5=1000 WHERE entry=7664; -- Immune: Fear,Root,Sleep,Stun,Freeze,Bleed,Banish; Fire,Shadow");
Logs("Fix immunities for Razelikh the Defiler (Blasted Lands): %d creatures");

MyOP("UPDATE creature_template SET mechanic_immune_mask=mechanic_immune_mask|1|16|64|512|2048|131072|2097152 WHERE entry IN (11022,11023); -- Immune: Charm,Fear,Root,Sleep,Stun,Banish,Infected (wowhead.com)");
Logs("Add immunities for Alexi Barov and Weldon Barov (Tirisfal Glades, WPL): %d creatures");


MyOP("UPDATE creature_template SET rank=0 WHERE entry=910");
Logs("Fix rank of Defias Enchanter to non-Elite: %d creatures");


MyOP("UPDATE creature_template SET rank=0 WHERE entry=4528");
Logs("Fix/remove Elite rank from Stone Rumbler (summoned by spell 8270 Summon Earth Rumbler): %d creatures");


MyOP("UPDATE creature_template SET faction_A=14, faction_H=14, mindmg=1635, maxdmg=1984, baseattacktime=1175, rangeattacktime=1292 WHERE entry=14101; -- Nostalrius");
Logs("Fix summoned Enraged Felguard (BWL) to be hostile and hit hard: %d creatures");


MyOP("UPDATE creature_template SET mindmg=197, maxdmg=282 WHERE entry=14226; -- SDB");
Logs("Strengthen rare Kaskk (Desolace): %d creatures");

MyOP("UPDATE creature_template SET mindmg=207, maxdmg=295 WHERE entry=2749; -- SDB");
Logs("Strengthen rare elite Siege Golem (Badlands): %d creatures");


MyOP("UPDATE creature_template SET minlevel=62,maxlevel=62, minhealth=10000,maxhealth=10000, mindmg=400,maxdmg=600, baseattacktime=1500, armor=7000, resistance2=100,resistance3=100,resistance4=100,resistance5=100,resistance6=100 WHERE entry=14306");
Logs("Strengthen summoned Eskhandar: %d creatures");

MyOP("UPDATE creature_template SET mindmg=300,maxdmg=500 WHERE entry=11200 AND maxdmg < 400");
Logs("Strengthen summoned Skeleton (from epic Ancient Cornerstone Grimoire): %d creatures");

MyOP("UPDATE creature_template SET mindmg=40,maxdmg=60 WHERE entry=2678 AND maxdmg < 50");
Logs("Strengthen Mechanical Dragonling: %d creatures");

MyOP("UPDATE creature_template SET minhealth=4000,maxhealth=4000, mindmg=100,maxdmg=200 WHERE entry=8615 AND maxdmg < 150");
Logs("Strengthen Mithril Dragonling: %d creatures");

MyOP("UPDATE creature_template SET minhealth=5000,maxhealth=5000, mindmg=200,maxdmg=300 WHERE entry=12473 AND maxdmg < 250");
Logs("Strengthen Arcanite Dragonling: %d creatures");



MyOP("UPDATE creature_template SET mindmg=116, maxdmg=208 /* HGDB */ WHERE entry=5775 AND (mindmg+maxdmg)/2 < 150");
Logs("Fix/increase melee damage for Verdan the Everliving (Wailing Caverns): %d creatures");

MyOP("UPDATE creature_template SET mindmg=78, maxdmg=103 /* Nostalrius */ WHERE entry=8675 AND (mindmg+maxdmg)/2 < (78+103)/2");
Logs("Fix/increase melee damage for Felbeast (Blasted Lands): %d creatures");

MyOP("UPDATE creature_template SET mindmg=281*2, maxdmg=381*2 WHERE entry=15220 AND (mindmg+maxdmg)/2 < 500");
Logs("Fix/increase melee damage for The Duke of Zephyrs (Silithus, summoned): %d creatures");


MyOP("UPDATE creature_template SET minhealth=400,maxhealth=400/*Nostalrius*/ WHERE entry=11197 AND maxhealth>400; -- SDB:1600 HP, but they supposed to be destroyed by 1 vial of Stratholme Holy Water");
Logs("Fix/lower health of Mindless Skeletons raised by Baron Rivendare (Stratholme): %d creatures");


MyOP("UPDATE creature_template SET minlevel=63,maxlevel=63, minhealth=80925,maxhealth=minhealth, mindmg=1129,maxdmg=1481, attackpower=290,baseattacktime=2000 WHERE entry=10363; -- Nostalrius");
Logs("Fix/lower melee DPS from General Drakkisath (UBRS): %d creatures");


MyOP("UPDATE creature_template SET faction_A=87, faction_H=87 WHERE entry IN (2597,2599) AND faction_A=16");
Logs("Fix Syndicate Faction for Lord Falconcrest and Otto: %d creatures");


MyOP("UPDATE creature_template SET faction_A=12, faction_H=12 WHERE entry IN (12781,12783) AND faction_A=35");
Logs("Fix Stormwind faction for Master Sergeant Biggins and Lieutenant Karter: %d creatures");


MyOP("UPDATE creature_template SET faction_A=14, faction_H=14 WHERE entry=2624 AND faction_A=7");
Logs("Fix summoned Gazban to be hostile: %d creatures");

MyOP("UPDATE creature_template SET faction_A=21, faction_H=21 WHERE entry=6490 AND faction_A=32");
Logs("Fix Azshir the Sleepless to be hostile: %d creatures");


$count = MyRUN(" -- previously all these had neutral values faction_A=32, faction_H=32
UPDATE creature_template SET faction_A=7,   faction_H=7   WHERE faction_A=32 AND entry=14224; -- 7:XT
UPDATE creature_template SET faction_A=16,  faction_H=16  WHERE faction_A=32 AND entry=5347;  -- Antilus the Soarer
UPDATE creature_template SET faction_A=14,  faction_H=14  WHERE faction_A=32 AND entry=6648;  -- Antilos
UPDATE creature_template SET faction_A=21,  faction_H=21  WHERE faction_A=32 AND entry=7895;  -- Ambassador Bloodrage
UPDATE creature_template SET faction_A=103, faction_H=103 WHERE faction_A=32 AND entry=10202; -- Azurous
UPDATE creature_template SET faction_A=16,  faction_H=16  WHERE faction_A=32 AND entry=5346;  -- Bloodroar the Stalker
UPDATE creature_template SET faction_A=45,  faction_H=45  WHERE faction_A=32 AND entry=8202;  -- Cyclok the Mad
UPDATE creature_template SET faction_A=7,   faction_H=7   WHERE faction_A=32 AND entry=14223; -- Cranky Benj
UPDATE creature_template SET faction_A=38,  faction_H=38  WHERE faction_A=32 AND entry=10077; -- Deathmaw (rare Wolf, Searing Gorge)
UPDATE creature_template SET faction_A=270, faction_H=270 WHERE faction_A=32 AND entry=5912;  -- Deviate Faerie Dragon
UPDATE creature_template SET faction_A=24,  faction_H=24  WHERE faction_A=32 AND entry=507;   -- Fenros (rare Worgen, Duskwood)
UPDATE creature_template SET faction_A=67,  faction_H=67  WHERE faction_A=32 AND entry=1843;  -- Foreman Jerris
UPDATE creature_template SET faction_A=38,  faction_H=38  WHERE faction_A=32 AND entry=14228; -- Giggler (rare Hyena, Desolace)
UPDATE creature_template SET faction_A=45,  faction_H=45  WHERE faction_A=32 AND entry=9604;  -- Gorgon'och
UPDATE creature_template SET faction_A=40,  faction_H=40  WHERE faction_A=32 AND entry=9718;  -- Ghok Bashguud
UPDATE creature_template SET faction_A=21,  faction_H=21  WHERE faction_A=32 AND entry=10825; -- Gish the Unmoving
UPDATE creature_template SET faction_A=87,  faction_H=87  WHERE faction_A=32 AND entry=14221; -- Gravis Slipknot
UPDATE creature_template SET faction_A=18,  faction_H=18  WHERE faction_A=32 AND entry=14447; -- Gilmorian
UPDATE creature_template SET faction_A=16,  faction_H=16  WHERE faction_A=32 AND entry=5934;  -- Heartrazor (rare elite wyvern, Thousand Needles)
UPDATE creature_template SET faction_A=14,  faction_H=14  WHERE faction_A=32 AND entry=9602;  -- Hahk'Zor
UPDATE creature_template SET faction_A=21,  faction_H=21  WHERE faction_A=32 AND entry=10558; -- Hearthsinger Forresten
UPDATE creature_template SET faction_A=14,  faction_H=14  WHERE faction_A=32 AND entry=10821; -- Hed'mush the Rotting
UPDATE creature_template SET faction_A=49,  faction_H=49  WHERE faction_A=32 AND entry=5935;  -- Ironeye the Invincible
UPDATE creature_template SET faction_A=7,   faction_H=7   WHERE faction_A=32 AND entry=8213;  -- Ironback
UPDATE creature_template SET faction_A=50,  faction_H=50  WHERE faction_A=32 AND entry=1063;  -- Jade (rare elite Green Drake, Swamp of Sorrow)
UPDATE creature_template SET faction_A=45,  faction_H=45  WHERE faction_A=32 AND entry=2453;  -- Lo'Grosh (rare Ogre, Alterac Mountains)
UPDATE creature_template SET faction_A=21,  faction_H=21  WHERE faction_A=32 AND entry=1848;  -- Lord Maldazzar
UPDATE creature_template SET faction_A=129, faction_H=129 WHERE faction_A=32 AND entry=14236; -- Lord Angler
UPDATE creature_template SET faction_A=45,  faction_H=45  WHERE faction_A=32 AND entry=2604;  -- Molok the Crusher (Boulderfist Ogre, Arathi Highlands)
UPDATE creature_template SET faction_A=38,  faction_H=38  WHERE faction_A=32 AND entry=8208;  -- Murderous Blisterpaw (rare Hyena, Tanaris)
UPDATE creature_template SET faction_A=45,  faction_H=45  WHERE faction_A=32 AND entry=723;   -- Mosh'Ogg Butcher
UPDATE creature_template SET faction_A=45,  faction_H=45  WHERE faction_A=32 AND entry=8297;  -- Magronos the Unyielding
UPDATE creature_template SET faction_A=654, faction_H=654 WHERE faction_A=32 AND entry=2606;  -- Nimar the Slayer (Witherbark Troll, Arathi Highlands)
UPDATE creature_template SET faction_A=14,  faction_H=14  WHERE faction_A=32 AND entry=14237; -- Oozeworm
UPDATE creature_template SET faction_A=74,  faction_H=74  WHERE faction_A=32 AND entry=2779;  -- Prince Nazjak
UPDATE creature_template SET faction_A=39,  faction_H=39  WHERE faction_A=32 AND entry=947;   -- Rohh the Silent
UPDATE creature_template SET faction_A=67,  faction_H=67  WHERE faction_A=32 AND entry=1837;  -- Scarlet Judge
UPDATE creature_template SET faction_A=67,  faction_H=67  WHERE faction_A=32 AND entry=1838;  -- Scarlet Interrogator
UPDATE creature_template SET faction_A=67,  faction_H=67  WHERE faction_A=32 AND entry=1839;  -- Scarlet High Clerist
UPDATE creature_template SET faction_A=67,  faction_H=67  WHERE faction_A=32 AND entry=1841;  -- Scarlet Executioner
UPDATE creature_template SET faction_A=14,  faction_H=14  WHERE faction_A=32 AND entry=3295;  -- Sludge Beast
UPDATE creature_template SET faction_A=111, faction_H=111 WHERE faction_A=32 AND entry=5864;  -- Swinegart Spearhide
UPDATE creature_template SET faction_A=124, faction_H=124 WHERE faction_A=32 AND entry=5916;  -- Sentinel Amarassan
UPDATE creature_template SET faction_A=14,  faction_H=14  WHERE faction_A=32 AND entry=3652;  -- Trigore the Lasher
UPDATE creature_template SET faction_A=14,  faction_H=14  WHERE faction_A=32 AND entry=8212;  -- The Reak
UPDATE creature_template SET faction_A=14,  faction_H=14  WHERE faction_A=32 AND entry=14345; -- The Ongar
UPDATE creature_template SET faction_A=37,  faction_H=37  WHERE faction_A=32 AND entry=5399;  -- Veyzhak the Cannibal
UPDATE creature_template SET faction_A=47,  faction_H=47  WHERE faction_A=32 AND entry=14492; -- Verifonix
UPDATE creature_template SET faction_A=654, faction_H=654 WHERE faction_A=32 AND entry=8218;  -- Witherheart the Stalker
UPDATE creature_template SET faction_A=37,  faction_H=37  WHERE faction_A=32 AND entry=10822; -- Warlord Thresh'jin
UPDATE creature_template SET faction_A=37,  faction_H=37  WHERE faction_A=32 AND entry=5400;  -- Zekkis
UPDATE creature_template SET faction_A=37,  faction_H=37  WHERE faction_A=32 AND entry=10823; -- Zul'Brin Warpbranch
UPDATE creature_template SET faction_A=310, faction_H=310 WHERE faction_A=32 AND entry=14474; -- Zora
-- unique, but not rare
UPDATE creature_template SET faction_A=14,  faction_H=14  WHERE faction_A=32 AND entry=11897; -- Duskwing (EPL)
UPDATE creature_template SET faction_A=21,  faction_H=21  WHERE faction_A=32 AND entry=10516; -- The Unforgiven (wraith boss, Stratholme, summoned)
UPDATE creature_template SET faction_A=21,  faction_H=21  WHERE faction_A=32 AND entry=10939; -- Marduk the Black (Scholomance)
UPDATE creature_template SET faction_A=22,  faction_H=22  WHERE faction_A=32 AND entry=2707;  -- Shadra (Hinterlands, summoned)
UPDATE creature_template SET faction_A=230, faction_H=230 WHERE faction_A=32 AND entry=7167;  -- Polly (Barrens, parrot, summoned)
UPDATE creature_template SET faction_A=14,  faction_H=14  WHERE faction_A=32 AND entry=10581; -- Young Arikara (Thousand Needles, summoned)
UPDATE creature_template SET faction_A=14,  faction_H=14  WHERE faction_A=32 AND entry=10882; -- Arikara (Thousand Needles, summoned)
UPDATE creature_template SET faction_A=38,  faction_H=38  WHERE faction_A=32 AND entry=2275;  -- Enraged Stanley (Hillsbrad Foothills, summoned)
");
Logs("Fix falsely neutral Faction template for many unique creatures: %d creatures" );



$count = MyRUN("
UPDATE creature_template SET unit_flags=unit_flags|32768 WHERE (InhabitType&2)!=0 AND NOT type IN (5) AND NOT family IN (8); -- except giants, crabs
UPDATE creature_template SET unit_flags=unit_flags&~32768 WHERE entry IN (1420,3835,5742,6653,15010,12419, 7551,13321,7552,7549,7550,14866); -- toads and frogs have no swimming animation
");
Logs("Fix non-swimming movement in water for few water-only (Rippa, Canal Frenzy ...) and for lots of water-tolerant: %d creatures" );


$l = 1;
$baseArmorByLevel = "";
foreach(array(15,16,41,76,120,174,239,316,406,512,538,573,608,642,677,713,748,782,817,852,888,922,957,992,1026,1061,1097,1130,1165,1200,1234,1270,1304,1340,1373,1480,1593,1709,1834,1964,2101,2246,2397,2557,2725,2780,2835,2888,2944,2999,3052,3108,3163,3216,3271,3327,3380,3435,3489,3791,4091,4391)
as $armor) { $baseArmorByLevel .= "WHEN $l THEN $armor "; $l++; }

MyOP("UPDATE creature_template SET armor=(SELECT CASE minlevel $baseArmorByLevel ELSE 0 END) WHERE armor=0");
Logs("Set generic armor values for remaining creatures with armor 0 (mostly guards): %d creatures");

}


function FixCreatureScripts()
{
global $count; PrintHeader(__FUNCTION__);

MyOP("UPDATE creature_ai_scripts SET action3_type=23, action3_param1=1 WHERE INSTR(comment,' - Prevent Combat Movement and Prevent Melee and Set Phase 1')>0 AND event_type=1 AND action3_type=0");
Logs("Fix ranged attackers AI scripts (Defias Smuggler, Riverpaw Scout...): %d");


// Для случая Warsong Peon была некорректная работа, связанная с неправильным
// порядком создания генераторов движения по событию AGGRO: сначала запускался
// MoveFleeing(), затем включался режим атаки и запускался либо MoveChase(),
// либо MoveIdle() - в результате бегство вообще не обрабатывалось
$count = MyVAL("SELECT COUNT(*) FROM creature_ai_scripts WHERE creature_id=11656") != 1 ? 0 :
  MyRUN("UPDATE creature_ai_scripts SET event_type=0, event_param1=500, event_param2=1000 WHERE creature_id=11656 AND event_type=4; -- EVENT_T_TIMER_IN_COMBAT instead of EVENT_T_AGGRO");
Logs("Fix Warsong Peon EventAI: %d rows" );


MyOP("UPDATE creature_ai_scripts SET action1_param1=21832 WHERE id=1220602 AND action1_param1=21071; -- Replace non-working spell 21071 with Princess Theradras' Boulder");
Logs("Fix EventAI ranged attack for Primordial Behemoth (Maraudon): %d rows");


MyOP("UPDATE creature_ai_scripts SET action1_param1=11428 WHERE id=1149803 AND action1_param1=16033");
Logs("Fix wrong spell ID (Chain Lightning instead of Knockdown) for Skarr the Unbreakable: %d rows");


MyOP("UPDATE creature_template SET gossip_menu_id=0, ScriptName='npc_sayge' WHERE entry=14822; -- Sayge has script in npcs_special.cpp");
Logs("Attach SD2 script for NPC Sayge (Darkmoon Faire) instead of UDB dbscripts, which allow rebuff exploit: %d creatures");

if (FIRST_RUN) { // из-за mingold,maxgold
MyOP("UPDATE creature_template SET ScriptName='npc_Emissary_Romankhan', armor=3769, baseattacktime=1280, MovementType=1, speed_walk=1.24,speed_run=1.24, mingold=3000,maxgold=5000 WHERE entry=14862");
Logs("Attach SD2 script for Emissary_Roman'khan and summoned lords of Silithid Hives (Silithus): %d creatures");
}

if (USE_CONDITIONS) {
MyOP("INSERT IGNORE creature_linking_template (entry,map,master_entry,flag,search_range) VALUES
(15288, 1, 15286, 1+2, 60), -- Aluntir <=> Xil'xix
(15290, 1, 15286, 1+2, 60); -- Arakis <=> Xil'xix
"); // достигает цели лишь частично: если убит самый "толстый" (Xil'xix), то между двумя оставшимся связи нет
Logs("Link three Silithid Hive Lords (Silithus): %d rows");
}


$count = MyRUN("
UPDATE gameobject_template SET ScriptName='go_omen_cluster' WHERE entry=180859;
UPDATE creature_template SET ScriptName='npc_minion_of_omen' WHERE entry=15466;
UPDATE creature_template SET ScriptName='boss_omen', MovementType=1 WHERE entry=15467;
");
Logs("Attach SD2 script for worldboss Omen (Lunar Festival quest): %d rows" );


if (USE_DBSCRIPTS
    and MyVAL("SELECT id FROM scripted_event_id WHERE ScriptName='event_go_tutenkash_gong'") === null
) {
$count = MyRUN("
INSERT IGNORE dbscripts_on_go_template_use SET id=148917, delay=0, command=10, datalong=7349, datalong2=3600000, data_flags=2, comments='Gong (RFD) - Summon Tomb Fiend';
INSERT IGNORE dbscripts_on_go_template_use SET id=148917, delay=1, command=10, datalong=7349, datalong2=3600000, data_flags=2, comments='Gong (RFD) - Summon Tomb Fiend';
INSERT IGNORE dbscripts_on_go_template_use SET id=148917, delay=2, command=10, datalong=7349, datalong2=3600000, data_flags=2, comments='Gong (RFD) - Summon Tomb Fiend';
INSERT IGNORE dbscripts_on_go_template_use SET id=148917, delay=3, command=10, datalong=7349, datalong2=3600000, data_flags=2, comments='Gong (RFD) - Summon Tomb Fiend';
INSERT IGNORE dbscripts_on_go_template_use SET id=148917, delay=4, command=10, datalong=7349, datalong2=3600000, data_flags=2, comments='Gong (RFD) - Summon Tomb Fiend';
INSERT IGNORE dbscripts_on_go_template_use SET id=148917, delay=5, command=10, datalong=7349, datalong2=3600000, data_flags=2, comments='Gong (RFD) - Summon Tomb Fiend';
INSERT IGNORE dbscripts_on_go_template_use SET id=148917, delay=6, command=10, datalong=7349, datalong2=3600000, data_flags=2, comments='Gong (RFD) - Summon Tomb Fiend';
INSERT IGNORE dbscripts_on_go_template_use SET id=148917, delay=7, command=10, datalong=7349, datalong2=3600000, data_flags=2, comments='Gong (RFD) - Summon Tomb Fiend';
INSERT IGNORE dbscripts_on_go_template_use SET id=148917, delay=60, command=10, datalong=7351, datalong2=3600000, data_flags=2, comments='Gong (RFD) - Summon Tomb Reaver';
INSERT IGNORE dbscripts_on_go_template_use SET id=148917, delay=61, command=10, datalong=7351, datalong2=3600000, data_flags=2, comments='Gong (RFD) - Summon Tomb Reaver';
INSERT IGNORE dbscripts_on_go_template_use SET id=148917, delay=62, command=10, datalong=7351, datalong2=3600000, data_flags=2, comments='Gong (RFD) - Summon Tomb Reaver';
INSERT IGNORE dbscripts_on_go_template_use SET id=148917, delay=63, command=10, datalong=7351, datalong2=3600000, data_flags=2, comments='Gong (RFD) - Summon Tomb Reaver';
INSERT IGNORE dbscripts_on_go_template_use SET id=148917, delay=120, command=10, datalong=7355, datalong2=3300000, data_flags=2, comments='Gong (RFD) - Summon Tuten\'kash';
UPDATE gameobject SET spawntimesecs=3*24*60*60 WHERE guid=32045 AND id=148917; -- 3 days, long enough to be not exploitable
DELETE FROM scripted_event_id WHERE INSTR(ScriptName,'tutenkash')>0;
");
Logs("Custom Tuten'kash summoning (Razorfen Downs): %d rows" );
}

if (USE_DBSCRIPTS) {
MyOP("UPDATE dbscripts_on_gossip SET delay=1, data_flags=2 WHERE id=3141 AND command=29 LIMIT 1");
Logs("Fix/prevent multiple quest credits from Darrowshire Spirits: %d rows");
}

if (USE_DBSCRIPTS) {
MyOP("UPDATE dbscripts_on_creature_movement SET command=15, datalong=3617, data_flags=8, comments='ironbark redeemed - Suicide' WHERE id=14241 AND command=28 AND datalong=7");
Logs("Fix Ironbark the Redeemed event to be recognized by SD2 and saved as instance state (Dire Maul): %d dbscripts");
}


if (USE_CONDITIONS) {
MyOP("INSERT IGNORE creature_linking_template (entry,map,master_entry,flag,search_range) VALUES
(11885, 0, 11878, 1+2+4+128+1024, 60); -- Blighthound <=> Nathanos Blightcaller
");
Logs("Link Blighthounds to Nathanos Blightcaller (EPL): %d rows");
}


if (USE_DBSCRIPTS and FIRST_RUN) {
MyOP("INSERT IGNORE dbscripts_on_creature_death SET id=15262, delay=1, command=15, datalong=27630, comments='Obsidian Eradicator - drop Large Obsidian Chunk'");
Logs("Fix/add missing Large Obsidian Chunk drop from Obsidian Eradicator (AQ40): %d rows");
}


if (USE_CONDITIONS) {
MyOP("INSERT IGNORE creature_linking (guid,master_guid,flag) VALUES
(154602, 154620, 1), -- Death Lash
(154604, 154620, 1), -- Whip Lasher
(154606, 154620, 1), -- Whip Lasher
(154605, 154620, 1), -- Whip Lasher
(154607, 154620, 1), -- Whip Lasher
(154614, 154620, 1), -- Death Lash
(154619, 154620, 1), -- Whip Lasher
(154617, 154620, 1), -- Whip Lasher
(154616, 154620, 1), -- Whip Lasher
(154610, 154620, 1), -- Whip Lasher
(154618, 154620, 1), -- Whip Lasher
(154613, 154620, 1), -- Whip Lasher
(154608, 154620, 1), -- Death Lash
(154612, 154620, 1), -- Whip Lasher
(154611, 154620, 1), -- Whip Lasher
(154603, 154620, 1), -- Fel Lash
(154609, 154620, 1); -- Fel Lash
");
Logs("Link nearby creatures to Alzzin Wildshaper (Dire Maul): %d rows");
}

MyOP("UPDATE creature SET MovementType=1, spawndist=20 WHERE guid=154620 AND id=11492 AND MovementType=2");
// после Evade или .respawn WP-движение таки работает, причём не вызывая ступора в бою
Logs("Disable initial waypoint movement for Alzzin Wildshaper (Dire Maul): %d rows");


if (USE_CONDITIONS) {
$count = MyVAL("SELECT entry FROM creature_loot_template WHERE entry=10508 AND item=13626 AND condition_id=0") === null ? 0 :
MyRUN("
INSERT IGNORE conditions SET type=1, value1=1000000+17186, value2=0; -- Ras Becomes a Boy! aura
UPDATE creature_loot_template SET condition_id=(SELECT condition_entry FROM conditions WHERE type=1 AND value1=1000000+17186 AND value2=0) WHERE entry=10508 AND item=13626;
"); // подразумевает правку ядра cMangos
Logs("Fix/implement Ras Frostwhisper Human transformation and loot check (Scholomance): %d rows" );
}


if (USE_CONDITIONS) {
$count = 0;
foreach(array(15391,15392,15390,15389, 15386,15388, 15385, 15387,15344) as $entry) {
  MyOP("INSERT IGNORE creature_linking_template SET entry=$entry,map=509,master_entry=15341,flag=1+128+1024,search_range=200");
  $count += mysql_affected_rows();
}
Logs("Link Captains, Majors, Colonel and whole army to General Rajaxx (AQ20): %d rows" );
}


if (USE_CONDITIONS) {
$count = 0;
foreach(array(14022,14023,14024,14025) as $entry) {
  MyOP("INSERT IGNORE creature_linking_template SET entry=$entry,map=469,master_entry=12017,flag=1024");
  $count += mysql_affected_rows();
}
Logs("Fix/do not respawn corrupted whelps while Broodlord Lashlayer is dead (BWL): %d rows" );

MyOP("UPDATE creature_linking_template SET flag=flag|1024 WHERE entry=10814");
Logs("Fix/do not respawn Chromatic Elite Guards while General Drakkisath is dead (UBRS): %d rows");
}


MyOP("UPDATE creature SET spawntimesecs=7200 WHERE spawntimesecs < 7200 AND spawntimesecs>0 AND id IN (16044/*Mor Grayhoof Trigger*/, 16048/*Lord Valthalak Trigger*/)");
Logs("Fix/respawn time 2 hours for Mor Grayhoof and Valthalak encounters: %d guids");

}


function TweakGeneral()
{
global $count; PrintHeader(__FUNCTION__);

// Растягивание прогрессии опыта, чтобы проходить все зоны и задания, брать
// задания более высокого уровня и рано получать за них вещи с высоким
// ItemLevel без требования RequiredLevel
$count = 0;
if (MyVAL("SELECT xp_for_next_level FROM player_xp_for_level WHERE lvl=1") == 400)
{
MyOP("UPDATE player_xp_for_level SET xp_for_next_level=
 IF(
  (@t := xp_for_next_level * CASE
   WHEN lvl <= 19 THEN 6 + (10-6)*(lvl- 1)/(19- 1) -- L1..L19  => x6..x10
   WHEN lvl <= 49 THEN 10- (10-4)*(lvl-20)/(49-20) -- L20..L49 => x10..x4
   WHEN lvl <= 57 THEN 4                           -- L50..L57 => x4
                  ELSE 8 + (16-8)*(lvl-58)/(59-58) -- L58..L59 => x8..x16
   END
  ) > 10000, @t - @t MOD 1000, @t - @t MOD 100
 )
");
$count = mysql_affected_rows();
}
Logs("Slow down XP/leveling progression: %d levelups" );


MyOP("DELETE FROM playercreateinfo_spell WHERE Spell=20599");
// Скорость набора опыта мы настраиваем как пожелаем, а соблазн переключаться на человека при массовом получении опыта надо устранить
Logs("Remove Diplomacy (XP +10%%) from Human racial abilities list: %d race_class");

// Общие изначальные умения для всех классов - необходимо для мультиклассовой соло игры
$count = 0;
$res = MyOP("SELECT DISTINCT race,class FROM playercreateinfo_spell");
while($obj = mysql_fetch_object($res)) {
  $count += MyRUN("", "INSERT IGNORE playercreateinfo_spell (race,class,Spell,Note) VALUES
($obj->race,$obj->class, 2481,'+Find Treasure'),
($obj->race,$obj->class,   75,'+Auto Shot'),
($obj->race,$obj->class, 5019,'+Shoot'),
($obj->race,$obj->class,  107,'+Block'),
($obj->race,$obj->class, 2457,'+Battle Stance'),
($obj->race,$obj->class, 9116,'+Shield'),
($obj->race,$obj->class, 9077,'+Leather'),
($obj->race,$obj->class, 8737,'+Mail'),
($obj->race,$obj->class,  201,'+One-Handed Swords'),
($obj->race,$obj->class,  202,'+Two-Handed Swords'),
($obj->race,$obj->class,  196,'+One-Handed Axes'),
($obj->race,$obj->class,  197,'+Two-Handed Axes'),
($obj->race,$obj->class,  198,'+One-Handed Maces'),
($obj->race,$obj->class,  199,'+Two-Handed Maces'),
($obj->race,$obj->class, 1180,'+Daggers'),
($obj->race,$obj->class,  227,'+Staves'),
($obj->race,$obj->class,  203,'+Unarmed'),
($obj->race,$obj->class,27762,'+Libram'),
($obj->race,$obj->class,27763,'+Totem'),
($obj->race,$obj->class, 5009,'+Wands'),
($obj->race,$obj->class,  264,'+Bows'),
($obj->race,$obj->class,  266,'+Guns'),
($obj->race,$obj->class, 2567,'+Thrown');
  ");
} 
Logs("Define default abilities {Block,Auto Shot,Shoot[Wands],Find Treasure,...} for all: %d race_class" );


// Возможность без смены класса использовать перелёт Druid'а Moonglade -> Ru'terran Village, получить
// Elegant Letter от Rogue наставников и т.п.
if (USE_CONDITIONS)
{
MyOP("UPDATE conditions SET value1=IF(value1=0 OR value1>>12!=0, value1, value1<<12|2047), value2=IF(value2=0 OR value2>>12!=0, value2, value2<<12|2047) WHERE type=14");
// NB: из-за требования уникальности условий приходится старые значения хранить сдвинутыми на 12 битов вверх
Logs("Tweak `conditions` to allow any class/race combination: %d conditions");
}


MyOP("UPDATE spell_affect SET SpellFamilyMask=SpellFamilyMask&~0x40000 WHERE entry IN (18218,18219); -- Warlock's mask 0x40000 => Life Tap, luckily has no range");
// На самом деле просто не следует использовать увеличители расстояния нерабочих классов, которые ничего не дают, но сбивают с толку WoW.exe
Logs("Disable range increase of Hunter's Scatter Shot from Warlock's Grim Reach talent: %d rows");


MyOP("UPDATE gameobject_template SET data0=1 WHERE type=18 AND data0 > 1 AND data0 < 10");
Logs("Set reqParticipants=1 for Rituals requiring more than 1 player: %d gameobjects");


MyOP("UPDATE instance_template SET reset_delay=CASE map WHEN 229/*BRS*/ THEN 0 WHEN 309/*ZG*/ THEN 7 WHEN 509/*AQ20*/ THEN 7 ELSE reset_delay END");
Logs("Disable planned reset for BRS (treat as regular dungeon), increase from 3 to 7 days for ZG and AQ20: %d rows");


$count = MyRUN("
-- Переменить тип TIMESTAMP в DATETIME, чтобы всё было по локальному времени и не было ограничения 2038 годом
SET @@session.time_zone = '+03:00'; -- то, что было при генерации БД из *.sql
ALTER TABLE game_event MODIFY start_time DATETIME NOT NULL DEFAULT '1970-01-01 00:00:00' COMMENT 'Absolute start date, the event will never start before', MODIFY end_time DATETIME NOT NULL DEFAULT '1970-01-01 00:00:00' COMMENT 'Absolute end date, the event will never start after';
SET @@session.time_zone = 'SYSTEM';
-- Исправить периоды Gurubashi Arena Booty Run - через 3 часа, начиная с 00:00
UPDATE game_event SET start_time='2005-04-19 00:00:00' WHERE entry=16; -- started with patch 1.4.0
-- Сделать Darkmoon Faire постоянно действующим, неделю в Mulgore, неделю
-- в Elwynn Forest (в последнем случае два дня заняты приготовлениями)
UPDATE game_event SET start_time='2006-01-02 02:00:00', occurence=20160, length=10080 WHERE description='Darkmoon Faire (Mulgore)';
UPDATE game_event SET start_time='2006-01-09 02:00:00', occurence=20160, length=2880  WHERE description='Darkmoon Faire Building (Elwynn)';
UPDATE game_event SET start_time='2006-01-11 02:00:00', occurence=20160, length=7200  WHERE description='Darkmoon Faire (Elwynn)';
-- Проводить раз в два дня (вместо раза в неделю) Fishing Extravaganza Announce, Fishing Extravaganza (14:00-16:00), Fishing Extravaganza Turn-in
UPDATE game_event SET start_time='2006-01-01 11:00:00', length=3*60, occurence=2*24*60 WHERE entry=14 AND occurence=7*24*60;
UPDATE game_event SET start_time='2006-01-01 14:00:00', length=2*60, occurence=2*24*60 WHERE entry=15 AND occurence=7*24*60;
UPDATE game_event SET start_time='2006-01-01 14:30:00', length=3*60, occurence=2*24*60 WHERE entry=34 AND occurence=7*24*60;
-- Удлинить Midsummer Fire Festival примерно в два раза, до 30 дней: с ~20 июня по 20 июля (из-за occurence=525600=365 дней дата уменьшается по прошествии лет!)
UPDATE game_event SET length=43200 WHERE entry=1;
-- Удлинить в три раза Harvest Festival: 3 недели с 5 октября
UPDATE game_event SET length=30240 WHERE entry=33;
-- Сократить бездарный Hallow's End до двух суток: 29-31 октября
UPDATE game_event SET start_time='2006-10-29 22:59:00', length=2880 WHERE entry=12;
-- Установить год начала равным прошлому году для событий, привязанных к числам месяца, иначе будут 'съезжать' их даты, т.к. период = 365 дней
UPDATE game_event SET start_time=IF(YEAR(start_time)=0,start_time, CONCAT(YEAR(CURDATE())-1,'-',MONTH(start_time),'-',DAYOFMONTH(start_time),' ',HOUR(start_time),':',MINUTE(start_time),':',SECOND(start_time))) WHERE NOT INSTR(description,'Darkmoon Faire');
-- Установить год конца через 10 лет от текущей даты, дабы ничто не завершалось
UPDATE game_event SET end_time=IF(YEAR(end_time)=0,end_time, CONCAT(YEAR(CURDATE())+10,'-',MONTH(end_time),'-',DAYOFMONTH(end_time),' ',HOUR(end_time),':',MINUTE(end_time),':',SECOND(end_time)));
");
Logs("Game Event schedule modifications: %d" );

}


function TweakItems()
{
global $count; PrintHeader(__FUNCTION__);

// Уравнять цены покупки и продажи на табарды, чтобы можно было купить поносить на время, а потом продать без потерь
MyOP("UPDATE npc_vendor AS v JOIN item_template AS it ON v.item=it.entry SET SellPrice=0.80*BuyPrice WHERE InventoryType=19 AND BuyPrice>0");
Logs("Equal Sell and Buy prices for tabards from vendors: %d items");

MyOP("UPDATE item_template SET BuyPrice=BuyPrice*10 WHERE name IN ('Felcloth','Black Lotus','Enchanted Leather') AND BuyPrice < 10000");
Logs("Increase BuyPrice x10 for Felcloth, Black Lotus, Enchanted Leather: %d items");


MyOP("UPDATE item_template SET spellcategorycooldown_1=0 WHERE entry=15846 AND spellid_1=19566; -- also cooldown removed from spell.dbc ID 19566");
Logs("Remove unacceptable 3-day cooldown from Salt Shaker: %d items");

MyOP("UPDATE item_template SET spellcooldown_1=0, spellcategorycooldown_1=0 WHERE entry=22754 AND spellid_1=21358");
Logs("Remove unacceptable cooldown from Eternal Quintessence: %d items");


MyOP("UPDATE item_template SET maxcount=7 WHERE entry=17333");
Logs("Allow a single player to carry up to 7 Aqual Quintessences (Azshara/Molten Core): %d items");
// можно складировать неограниченно много в Warehouse

if (USE_CONDITIONS) {
$count = MyRUN("
UPDATE conditions SET value2=7 WHERE type=24 AND value1=17333 AND value2<7;
");
Logs("Allow a single player to fetch up to 7 Aqual Quintessences (Azshara/Molten Core): %d rows" );
}

// MyOP("UPDATE item_template SET stackable=stackable*10 WHERE stackable > 1");
// max. stack size = 255 in WoW 1.12
// Объединять оружие (2) и доспехи (4) нельзя, т.к. объединение/разделение позволяет дублировать Durability и др. свойства (хотя это и непринципиально для Quality <= 1)
// Объединять сумки (1) нельзя, т.к. при установке пачки в банковский слот несколько штук превращаются в одну
// Объединять колчаны нельзя, т.к. они будут далее превращены в сумки
// Объединять вещи с зарядами нельзя, см. Spell.cpp: Spell::TakeCastItem()
// Псевдоконтейнеры (Trunk, Clam) теперь можно объединять - благодаря модификации cMangos-ядра loot на пачке удаляет только 1, а не все сразу
// Объединение quest trinket'ов Arena Master запрещено, чтобы задание не теряло сложность, связанную с хранением 11 soulbound вещей
MyOP("UPDATE item_template SET stackable=250 WHERE stackable > 1 OR stackable=1 AND NOT(class IN (1,2,4,11) OR class=12 AND InventoryType=12) AND spellcharges_1 IN(-1,0) AND spellcharges_2 IN(-1,0) AND spellcharges_3 IN(-1,0) AND spellcharges_4 IN(-1,0) AND spellcharges_5 IN(-1,0) /* AND RIGHT(name,6)!=' Trunk' AND RIGHT(name,5)!=' Clam' */ OR entry IN /* Twilight Cultist ...*/ (20408,20406,20407,20451,20422)");
Logs("Maximize stack limits for: %d items");

                                                                                                                                                                                                                                                                                                                                                                    
MyOP("UPDATE item_template SET spellcharges_1=spellcharges_1*4 WHERE class!=12 AND spellcharges_1 <= -2 AND spellcharges_1 > -15");
Logs("Increase charges x4 for multicharge non-quest items (Wizard Oil etc): %d items");


MyOP("UPDATE item_template SET AllowableClass=AllowableClass|0x5FF WHERE AllowableClass>0 AND NOT entry IN (23320,21293,21291,21292); -- except Horde-only Shaman L60 learnable tablets");
Logs("Remove class restriction from items: %d items");

                                                                                                            
// Выравнивание показателя armor для всех типов доспехов (Cloth, Leather, Mail,
// Plate) для одиночной мультиклассовой игры, благодаря чему лёгкие доспехи
// не лишаются смысла, повышается широта выбора и разнообразие внешнего вида.
// Более тяжёлые типы сохраняют некоторое преимущество, но оно не так велико.
// До 40-го уровня вещей включительно Cloth и Leather выравниваются на Mail.
// После 40-го уровня, когда появляется Plate, Cloth/Leather/Mail постепенно,
// в течение 41..49 уровней, подтягиваются до Plate.
// Начиная с 50-го уровня вещей все типы примерно выровнены.
// В оригинале при повышении категории тяжести доспехов на одну ступень
//   armor увеличивается примерно в 2 раза. Но есть вещи с повышенным armor,
//   поэтому используется ограничитель - минимальный armor среди всех вещей
//   такого же уровня, но максимальной категории тяжести (т.е. mail/plate)
$count = MyRUN(
"SET @boosted:=0", // без SET @...= команд работает неправильно,
"SET @lim:=0",     //  кажется, предполагая строковый тип данных
"UPDATE item_template
 SET armor = CASE
     WHEN (@boosted := FLOOR(armor * POW(1.9, 3-subclass) * (CASE WHEN ItemLevel <= 40 THEN 1.0 WHEN ItemLevel < 50 THEN (1 + 0.7*(ItemLevel-40)/(50-40)) ELSE 1.7 END) )) < armor THEN armor
     WHEN (@lim := (". RetrieveArmorLimits() .") - (IF(ItemLevel < 40, 3, 4)-subclass) ) < armor THEN armor
     WHEN @lim < @boosted THEN @lim
     ELSE @boosted
 END
 WHERE InventoryType IN (1,3,5,6,7,8,9,10,20) AND class=4 AND (subclass IN (1,2) OR subclass=3 AND ItemLevel >= 40)"
);
Logs("Boost armor of Cloth/Leather/[Mail] items to match Mail/Plate: %d items" );


/* 
// Поскольку для Soul Shard разрешены пачки, то особые сумки для них
// теряют всякий смысл. Теперь cMangos-ядро опционально поддерживает Soul Bag
// как сумки общего назначения, которые, однако, нельзя экипировать на себя, а
// можно только помещать их в банк, что очень полезно ввиду увеличенной ёмкости
// Soul Bag в сравнении с обычными сумками

// Преобразование Soul Bag в обычные сумки меньшей ёмкости.
$count = MyRUN("
UPDATE item_template SET subclass=0, ContainerSlots=10 WHERE entry= 22243; -- Small Soul Pouch (12)
UPDATE item_template SET subclass=0, ContainerSlots=12 WHERE entry= 22244; -- Box of Souls (16)
UPDATE item_template SET subclass=0, ContainerSlots=14 WHERE entry= 21340; -- Soul Pouch (20)
UPDATE item_template SET subclass=0, ContainerSlots=16 WHERE entry= 21341; -- Felcloth Bag (24)
UPDATE item_template SET subclass=0, ContainerSlots=18 WHERE entry= 21342; -- Core Felcloth Bag (28)
");
Logs("Change Soul Bags to ordinary Bags of lesser capacity: %d items" );
*/

// Сделать Bottomless Bag (очень редкий world drop L60 рецепт) не 18-, а 20- местной сумкой
// иначе просто неинтересно, ибо 18-местные сумки поставляет Onyxia в неограниченном количестве
MyOP("UPDATE item_template SET ContainerSlots=20 WHERE entry=14156 AND ContainerSlots=18");
Logs("Change capacity of Bottomless Bag from 18- to 20-slot");


if (USE_DBSCRIPTS) {
// Применять следующие две модификации пока только к cMangos (где есть нужная правка кода ядра)

// Помещать отмычку, расходные материалы разбойника, инженерный порох,
// кристаллы чернокнижника, некоторые реагенты, стрелы и пули в сумку для
// ключей (4/8/12 мест в зависимости от уровня персонажа L1/L40/L50).
// Подразумевается, что Soul Bag и Quiver/Pouch переделываются в сумки
// общего назначения, иначе в них нельзя будет положить ни кристаллы,
// ни стрелы/пули
MyOP("UPDATE item_template SET BagFamily=9 WHERE
 name IN (\"Thieves' Tools\", 'Flash Powder','Blinding Powder', 'Small Seaforium Charge','Large Seaforium Charge','Powerful Seaforium Charge', 'Light Feather','Shiny Fish Scales','Rune of Teleportation','Rune of Portals')
 OR class=0 AND subclass=0 AND name LIKE '% Poison%'
 OR class=7 AND subclass=0 AND (name LIKE '% Sharpening Stone' OR name LIKE '% Weightstone')
 OR BagFamily IN (3, 1,2)
");
Logs("Keyring as special container for Thieves' Tools, Soul Shards, Arrows, Bullets, Weapon stones: %d items");

// Колчаны и мешки для пуль будут хранить любые вещи (разрешение для
// нестандартных подклассов в cMangos-ядре). Они нужны, поскольку увеличивают
// скорость стрельбы, при этом не обладая преимуществом перед обычными сумками
// по вместительности, но ограничения на кол-во носимых вещей неприемлемо
// в мультиклассовой игре.
// Вспомогательные персонажи низкого уровня не смогут использовать, скажем,
// Heavy Quiver вместо Runecloth Bag из-за требования Required Level 30.
// По-прежнему можно экипировать только один контейнер аммуниции, т.е.
// прибавки скорости стрельбы не суммируются.
// Помещение сумок подкласса 0 в банковские слоты запрещено, чтобы не упрощать
// чрезмерно жизнь основному персонажу (но подкласс 1 можно было бы в банк)
MyOP("UPDATE item_template SET subclass=0 /*, maxcount=1*/ WHERE class=11 AND subclass IN (2,3)");
Logs("Enable any items in Quivers and Ammo Pouches (requires .cpp patch): %d items");
}

}


function TweakQuests()
{
global $count; PrintHeader(__FUNCTION__);

$count = 0;
$egroup = MyVAL("SELECT entry FROM quest_template WHERE Title=\"The Hunter's Path\" ORDER BY entry");
if ($egroup !== null) {
    MyOP("UPDATE quest_template SET ExclusiveGroup=$egroup WHERE Title=\"The Hunter's Path\"");
    $count += mysql_affected_rows();
}
MyOP("UPDATE quest_template SET ExclusiveGroup=6061 WHERE entry IN (6061,6062,6063,6064); -- Taming the Beast #1/3)");
$count += mysql_affected_rows();
Logs("Make initial \"The Hunter's Path\" and \"Taming the Beast\" quest groups exclusive: %d quests" );


$count = MyRUN("
UPDATE quest_template SET ExclusiveGroup = 3630 WHERE entry IN (3630,3632,3634,3635,3637);  -- Gnomish + Goblin Engineering
UPDATE quest_template SET ExclusiveGroup = 0 WHERE entry IN (3638,3640,3642);  -- 'The Pledge of Secrecy' Gnomish/Goblin quests
UPDATE quest_template SET ExclusiveGroup = 0 WHERE entry IN (5143,5148, 5144,5146, 5141,5145); -- Tribal+Elemental+Dragonscale Leatherworking
UPDATE quest_template SET ExclusiveGroup = 0 WHERE entry IN (5283,5301, 5284,5302); -- Armorsmith + Weaponsmith Blacksmithing
UPDATE quest_template SET ExclusiveGroup = 0 WHERE entry IN (5306,5305,5307); -- Master Axesmith/Hammersmith/Swordsmith
");
Logs("Make prof. specialization quests mutually non-exclusive: %d quests" );


MyOP("UPDATE quest_template SET ExclusiveGroup=8316 WHERE entry IN (8316,8376,8377,8378,8379,8380,8381,8382) AND ExclusiveGroup=0");
Logs("Make class quests \"Armaments of War\" mutually exclusive (Silithus): %d quests");

MyOP("UPDATE quest_template SET NextQuestInChain=0 WHERE title IN ('Just Compensation','Anthion\'s Parting Words') AND NextQuestInChain!=0 AND NextQuestId=NextQuestInChain");
Logs("Make Dungeon Set upgrade quests non-exclusive: %d quests");


MyOP("UPDATE quest_template SET MinLevel=45 WHERE MinLevel>45 AND entry IN (2783)");
Logs("Lower MinLevel from 50 to 45 for quest \"Petty Squabbles\" (Blasted Lands): %d quests");

/* вроде все рецепты и так доступны у наставников, непонятно зачем надо Gnome/Goblin Engineering
$count = 0;
$egroup = MyVAL("SELECT MIN(entry) FROM quest_template WHERE INSTR(Title, 'Goblin Engineering')>0");
MyOP("UPDATE quest_template SET ExclusiveGroup=$egroup WHERE INSTR(Title, 'Goblin Engineering')>0");
$count += mysql_affected_rows();

$egroup = MyVAL("SELECT MIN(entry) FROM quest_template WHERE INSTR(Title, 'Gnome Engineering')>0");
MyOP("UPDATE quest_template SET ExclusiveGroup=$egroup WHERE INSTR(Title, 'Gnome Engineering')>0");
$count += mysql_affected_rows();
Logs("Change ExlusiveGroup for prof.spec.quests: %d quests" );
*/


MyOP("UPDATE quest_template SET RequiredClasses=0 WHERE RequiredClasses!=0");
Logs("Remove quest class restrictions: %d quests"); // 791 for AlterWoW-3.5

MyOP("UPDATE quest_template SET RequiredRaces = RequiredRaces | 0xB2 WHERE NOT (RequiredRaces & 0xB2) IN (0, 0xB2) AND NOT Title IN (\"The Hunter's Path\",\"Taming the Beast\")");
Logs("Remove Horde quest race restrictions: %d quests");

MyOP("UPDATE quest_template SET RequiredRaces = RequiredRaces | 0x4D WHERE NOT (RequiredRaces & 0x4D) IN (0, 0x4D) AND NOT Title IN (\"The Hunter's Path\",\"Taming the Beast\")");
Logs("Remove Alliance quest race restrictions: %d quests");

MyOP("UPDATE quest_template SET RequiredRaces=0x4D|0xB2/*255*/ WHERE entry IN (8185,8188)");
Logs("Remove race restrictions from Paladin \"Syncretist's Sigil\" and Shaman \"Vodouisant's Vigilant Embrace\" quests (NPC Zanza, ZG): %d quests");


$count = MyRUN("
DELETE FROM creature_questrelation WHERE id=15351 AND quest IN (8374,8384,8391,8393,8392,8394,8395,8397,8372,8386,8399,8404,8400,8405,8401,8406,8402,8407); -- Alliance Brigadier General
DELETE FROM creature_questrelation WHERE id=15350 AND quest IN (8368,8389,8426,8431,8427,8432,8428,8433,8429,8434,8370,8390,8436,8440,8437,8441,8438,8442); -- Horde Warbringer
");
Logs("Remove low-level versions of BG Marks of Honor turn-in quests from Alliance Brigadier General and Horde Warbringer: %d quests" );

// Сперва минимизируется репутация за BG-задания, и только после устанавливается на "Additional Runecloth" задания
MyOP("UPDATE quest_template SET RewSpellCast=0/*no Honor*/, RewRepValue1=1, RewRepValue2=IF(RewRepValue2>0,1,0), RewRepValue3=IF(RewRepValue3>0,1,0),  RewRepValue4=IF(RewRepValue4>0,1,0),  RewRepValue5=IF(RewRepValue5>0,1,0) WHERE SpecialFlags&1 AND RewRepFaction1 IN (509,730,890,889,729,510)");
Logs("Minimize Reputation gain and remove Honor gain from repeatable BG quests: %d quests");
//
$count = MyRUN("
UPDATE quest_template SET RewRepFaction1=509 WHERE RewRepFaction1=72  AND Title='Additional Runecloth' -- Stormwind => The League of Arathor
UPDATE quest_template SET RewRepFaction1=730 WHERE RewRepFaction1=47  AND Title='Additional Runecloth' -- Ironforge => Stormpike Guard
UPDATE quest_template SET RewRepFaction1=890 WHERE RewRepFaction1=69  AND Title='Additional Runecloth' -- Darnassus => Silverwing Sentinels
UPDATE quest_template SET RewRepFaction1=909 WHERE RewRepFaction1=54  AND Title='Additional Runecloth' -- Gnomeregan Exiles => Darkmoon Faire
UPDATE quest_template SET RewRepFaction1=889 WHERE RewRepFaction1=76  AND Title='Additional Runecloth' -- Orgrimmar => Warsong Outriders
UPDATE quest_template SET RewRepFaction1=729 WHERE RewRepFaction1=68  AND Title='Additional Runecloth' -- Undercity => Frostwolf Clan
UPDATE quest_template SET RewRepFaction1=510 WHERE RewRepFaction1=530 AND Title='Additional Runecloth' -- Darkspear Trolls => The Defilers
UPDATE quest_template SET RewRepFaction1=909 WHERE RewRepFaction1=81  AND Title='Additional Runecloth' -- Thunder Bluff => Darkmoon Faire
");
Logs("Change Additional Runecloth donation quests Reputation to BGs and Darkmoon Faire: %d quests" );


// Идея в том, чтобы можно было бы набрать репутацию с пиратами Bloodsail
// Buccaneers, а затем восстановить репутацию с фракциями Steamwheedle Cartel
// за счёт сдачи ткани + Southsea Pirates + сдача Wastewander Water Pouch,
// не потеряв репутацию Bloodsail
MyOP("UPDATE quest_template SET RewRepValue1=-1 WHERE RewRepFaction1=87 AND RewRepValue1<0 AND entry IN (9267,9268,9259,9266)");
Logs("Dampen negative Bloodsail Reputation from amend quests (Ratchet, Gadgetzan, Booty Bay, Everlook): %d quests");


MyOP("UPDATE quest_template SET RewRepValue1=IF(entry=5981, 750,500) WHERE entry IN (4970,5201, 5981) AND RewRepFaction1=589");
Logs("Make Wintersaber Trainers quests yield x10 REP (Winterspring): %d quests");


MyOP("UPDATE quest_template SET RewRepFaction1=0,RewRepValue1=0 WHERE entry IN (8507,8731) AND RewRepFaction1=609");
Logs("Disallow Cenarion REP gain with repeatable Field Duty quests, which currently do not implement boss encounters in Alliance/Horde camps (Silithus): %d quests");

}


function TweakOnKillReputations()
{
global $count; PrintHeader(__FUNCTION__);

MyOP("
REPLACE creature_onkill_reputation (creature_id, RewOnKillRepFaction1, MaxStanding1, RewOnKillRepValue1) VALUES
-- League of Arathor onkill Reputation
(2618,  509, 3, 10),  -- Hammerfall Peon L33-34
(2619,  509, 3, 20),  -- Hammerfall Grunt L34-35
(2733,  509, 3, 50),  -- Apothecary Jorell L36
(2621,  509, 5, 80),  -- Hammerfall Guardian L50
(15128, 509, 5, 100), -- Defiler Elite L55
(15021, 509, 5, 150), -- Deathmaster Dwire L62
(15022, 509, 5, 150), -- Deathstalker Mortis L62
(15126, 509, 5, 100), -- Rutherford Twing L55 QM
(14990, 509, 7, 50),  -- Defilers Emissary
-- Defilers onkill Reputation
(2582,  510, 3, 10),  -- Dabyrie Laborer L30-31
(2581,  510, 3, 20),  -- Dabyrie Militia L31-32
(4479,  510, 3, 30),  -- Fardel Dabyrie L33
(4481,  510, 3, 30),  -- Marcel Dabyrie L34
(4480,  510, 3, 30),  -- Kenata Dabyrie L35
(2738,  510, 4, 20),  -- Stromgarde Cavalryman L36-37
(2584,  510, 4, 20),  -- Stromgarde Defender L38-39
(2583,  510, 4, 20),  -- Stromgarde Troll Hunter L37-38
(2585,  510, 4, 20),  -- Stromgarde Vindicator L39-40
(10696, 510, 4, 20),  -- Refuge Pointe Defender L41-45
(15130, 510, 4, 20),  -- League of Arathor Elite L40
(14983, 510, 5, 150), -- Field Marshal Oslight
(14984, 510, 5, 100), -- Sergeant Maclear L62
(15127, 510, 5, 150), -- Samuel Hawke L63 QM
(14991, 510, 7, 50),  -- League of Arathor Emissary
-- Silverwing Sentinels onkill Reputation
(11656, 890, 3, 10),  -- Warsong Peon L26-27
(11682, 890, 3, 20),  -- Warsong Grunt L29-30
(12863, 890, 3, 20),  -- Warsong Runner L29
(12862, 890, 3, 20),  -- Warsong Scout L28
(11683, 890, 3, 20),  -- Warsong Shaman L28-29
(11684, 890, 3, 50),  -- Warsong Shredder L27
(11681, 890, 3, 20),  -- Horde Deforester L27
(11680, 890, 3, 20),  -- Horde Scout L26-28
(14718, 890, 3, 50),  -- Horde Laborer L26
(14717, 890, 5, 100), -- Horde Elite L55
(14781, 890, 5, 150), -- Captain Shatterskull L55
(14754, 890, 5, 100), -- Kelm Hargunth L55 QM
(15105, 890, 7, 50),  -- Warsong Emissary L30
-- Warsong Outriders onkill Reputation
(12896, 889, 3, 20),  -- Silverwing Sentinel L22-23
(12897, 889, 3, 20),  -- Silverwing Warrior L21-22
(14715, 889, 5, 100), -- Silverwing Elite L55
(14733, 889, 5, 50),  -- Sentinel Farsong L55
(14753, 889, 5, 100), -- Illiyana Moonblaze L55 QM
(15102, 889, 7, 50),  -- Silverwing Emissary L22
-- the next two can be grinded in BG even in single player
-- Stormpike Guard Reputation
(14285, 730, 4, 12), -- Frostwolf Battleguard L61
(13840, 730, 4, 15), -- Warmaster Laggrond L59
(13817, 730, 4, 10), -- Voggah Deathgrip L61
(13219, 730, 4, 10), -- Jekyll Flandring L58 QM
(15106, 730, 7, 10), -- Frostwolf Emissary L55
-- Frostwolf Clan Reputation
(14284, 729, 4, 10), -- Stormpike Battleguard L59
(16392, 729, 4, 15), -- Captain Armando Ossex L60
(13777, 729, 4, 10), -- Sergeant Durgen Stormpike L58
(13841, 729, 4, 15), -- Lieutenant Haggerdin L61
(13217, 729, 4, 10), -- Thanthaldis Snowgleam L58 QM
(15103, 729, 7, 10); -- Stormpike Emissary L55
"); // all Emissaries are Dishonorable Kills
Logs("Set onkill reputation rewards as replacement of AB, WSG and addition to AV Battlegrounds: %d creatures");


$count = 0;
$res = MyOP("SELECT entry,name,rank,minlevel,maxlevel,minhealth,faction_A,faction_H FROM creature_template WHERE faction_A IN (1214,1215,1216,1217) AND 30 IN (SELECT DISTINCT map FROM creature WHERE id=entry)");
while($obj = mysql_fetch_object($res)) {
  MyOP("INSERT IGNORE creature_onkill_reputation SET creature_id=$obj->entry, RewOnKillRepFaction1=".($obj->faction_A >= 1216 ? 729:730).", MaxStanding1=".($obj->rank==0 ? 4 : ($obj->minlevel <= 60 ? 5 : ($obj->entry != 11948/*Vanndar Stormpike*/ && $obj->entry != 11946/*Drek'Thar*/ ? 6 : 6))).", RewOnKillRepValue1=".($obj->rank==0 ? ($obj->minhealth < 12000 ? 10:15):($obj->minlevel <= 60 ? 20:50)));
  $count += mysql_affected_rows();
}
Logs("Set onkill reputation rewards for Alterac Valley enemies: %d creatures" );


MyOP("UPDATE creature_onkill_reputation SET RewOnKillRepValue1=IF(RewOnKillRepValue1 > 0 AND RewOnKillRepValue1 <= 400, 2*RewOnKillRepValue1, RewOnKillRepValue1), RewOnKillRepValue2=IF(RewOnKillRepValue2 > 0 AND RewOnKillRepValue2 <= 400, 2*RewOnKillRepValue2, RewOnKillRepValue2)");
Logs("Apply limited 2x positive onkill_reputation gain rate: %d creatures");

}


function TweakGameobjectRespawnTimes()
{
global $count; PrintHeader(__FUNCTION__);

MyOP(<<<EOT
UPDATE gameobject SET spawntimesecs=spawntimesecs+3600 WHERE spawntimesecs > 0 AND spawntimesecs < 3600
AND id IN (SELECT entry FROM gameobject_template WHERE name IN (
"Practice Lockbox","Buccaneer's Strongbox", "Waterlogged Footlocker","Battered Footlocker","Mossy Footlocker","Dented Footlocker","Scarlet Footlocker"
))
EOT
);
Logs("Increase respawn time of Footlockers (1+ hours): %d gameobjects");

MyOP(<<<EOT
UPDATE gameobject SET spawntimesecs=20*60+1+ROUND(spawntimesecs*RAND(guid))
WHERE spawntimesecs > 0 AND spawntimesecs <= 20*60 AND id IN (SELECT entry FROM gameobject_template WHERE  name IN (
"Food Crate", "Barrel of Milk", "Barrel of Melon Juice", "Barrel of Sweet Nectar",
"Half-Buried Bottle" -- might begin Quest
))
EOT
);
Logs("Increase respawn time of Food Crates etc (20 minutes minimum): %d gameobjects");

MyOP(<<<EOT
UPDATE gameobject SET spawntimesecs=IF( map IN ($GLOBALS[InstancedMaps]),
 IF(spawntimesecs < 100000, 100000+spawntimesecs, spawntimesecs),
 IF(spawntimesecs <=2*3600, 2*3600+1+ROUND(spawntimesecs*RAND(guid)), spawntimesecs) )
WHERE spawntimesecs > 0 AND id IN (SELECT entry FROM gameobject_template WHERE name IN (
"Giant Clam", "Weapon Crate", "Armor Crate",
"Battered Chest","Large Battered Chest","Solid Chest","Large Solid Chest","Large Iron Bound Chest","Large Mithril Bound Chest",
"Box of Assorted Parts", "Blacksmithing Plans", "Supply Crate", "Old Treasure Chest",
"Black Lotus",
"Muddy Churning Waters", "Jinxed Hoodoo Pile", "Hakkari Thorium Vein", "Dark Iron Deposit",
-- quest GO in instances
"Artificial Extrapolator", "Spire Spider Egg"
))
EOT
);
// в подземельях эти объекты не должны восстанавливаться вообще (выставляем слишком большое время)
Logs("Increase respawn time of Treasure Chests, unusual Resources or Quest objects (2 hours overworld/inf.instances): %d gameobjects");

// Минимальное время восстановления обломков кораблекрушений, минералов, трав - есть много по 1 минуте и 3 минуты, что слишком мало
MyOP(<<<EOT
UPDATE gameobject SET spawntimesecs=IF( map IN ($GLOBALS[InstancedMaps]),
 IF(spawntimesecs <  5*900, 5*IF(spawntimesecs < 900, 900, spawntimesecs), spawntimesecs),
 IF(spawntimesecs <=2*3600, 2*3600+1+ROUND(spawntimesecs*RAND(guid)), spawntimesecs))
WHERE spawntimesecs > 0 AND id IN (SELECT entry FROM gameobject_template WHERE name IN (
"Floating Debris", "Floating Wreckage", "Schooner Wreckage Pool", "Waterlogged Wreckage Pool",
"Copper Vein", "Tin Vein", "Silver Vein", "Ooze Covered Silver Vein", "Iron Deposit", "Ooze Covered Iron Deposit", "Gold Vein", "Ooze Covered Gold Vein", "Mithril Deposit", "Ooze Covered Mithril Deposit", "Small Thorium Vein", "Ooze Covered Thorium Vein", "Rich Thorium Vein", "Ooze Covered Rich Thorium Vein", "Truesilver Deposit", "Ooze Covered Truesilver Deposit",
"Peacebloom", "Silverleaf", "Earthroot", "Mageroyal", "Swiftthistle", "Bloodthistle", "Briarthorn", "Stranglekelp", "Bruiseweed", "Wild Steelbloom", "Grave Moss", "Kingsblood", "Liferoot", "Fadeleaf", "Goldthorn", "Khadgar's Whisker", "Wintersbite", "Firebloom", "Purple Lotus", "Arthas' Tears", "Sungrass", "Blindweed", "Ghost Mushroom", "Gromsblood", "Golden Sansam", "Dreamfoil", "Mountain Silversage", "Plaguebloom", "Icecap",
"Cleansed Songflower", "Cleansed Windblossom", "Cleansed Night Dragon", "Cleansed Whipper Root",
"Blue Power Crystal", "Green Power Crystal", "Red Power Crystal", "Yellow Power Crystal", "Un'Goro Dirt Pile",
"Full Jug",
-- Alliance overworld quest GO
"Sack of Oats", "Mathystra Relic", "Incendicite Mineral Vein", "Wildkin Feather", "Thaurissan Relic", "Moontouched Feather",
-- Horde overworld quest GO
"Gnomish Toolbox", "Tainted Soil Sample", "Tirisfal Pumpkin", "Stolen Supply Sack", "Taillasher Eggs", "Ju-Ju Heap", "Gaea Seed", "Gaea Dirt Mound", "Giant Softshell Clam", "Horde Supply Crate", "Laden Mushroom", "Tool Bucket", "Troll Chest",
-- Neutral overworld quest GO
"Sack of Meat", "Gahz'ridian", "Azsharite Formation", "Small Lockbox", "Volcanic Ash", "Rocket Car Rubble", "Calcified Elven Gem", "Deepmoss Eggs"
)
OR type=25 -- any fishing school / wreckage / etc.
)
EOT
);
Logs("Increase respawn time of resources and quest GO (2 hours overworld/x5 instances): %d gameobjects");

}


function TweakNPC()
{
global $count; PrintHeader(__FUNCTION__);

MyOP("UPDATE creature_template SET npcflag=npcflag&~1 WHERE entry IN (2455,2457,3309); -- Olivia Burnside, John Burnside, Karus");
Logs("Gossip Menu removed for convenient access: %d creatures");


$count = MyRUN(
"INSERT IGNORE battlemaster_entry (entry,bg_template) VALUES
(13777, 1), -- Sergeant Durgen Stormpike
(14733, 2), -- Sentinel Farsong
(14983, 3), -- Field Marshal Oslight
(13776, 1), -- Corporal Teeka Bloodsnarl
(14781, 2), -- Captain Shatterskull
(15021, 3); -- Deathmaster Dwire",
"UPDATE creature_template SET npcflag=npcflag|2048 WHERE entry IN (13777,14733,14983, 13776,14781,15021)"
);
Logs("Add Battlemaster option to NPCs near Battleground entrances: %d creatures" );


if (USE_CONDITIONS) {
MyOP("INSERT IGNORE npc_vendor SET entry=11536, item=22999, condition_id=161");
Logs("Add Tabard of the Argent Dawn to Quartermaster Miranda Breechlock (the same condition as for Chromatic Mantle of the Dawn): %d items");
}

// Увеличение времени пополнения товаров главным образом нужно для случая
// Felcloth в Darkwhisper Gorge и для торговцев на Darkmoon Faire
// !!! что-то тут не работает, вещи пополняются раньше времени
MyOP("UPDATE npc_vendor AS nv JOIN item_template AS it ON item=it.entry SET incrtime=24*3600 WHERE incrtime<24*3600 AND nv.maxcount>0 AND incrtime>0 AND NOT (class=0 AND subclass=0)");
Logs("1-day vendor renewal period for limited non-consumables: %d items");

}


function TweakCreatures()
{
global $count; PrintHeader(__FUNCTION__);

// Это Tweak или Fix?
MyOP("UPDATE creature_template SET skinloot=12802 WHERE entry=11671 AND skinloot=0 AND ScriptName=''");
// При наличии правильного скрипта горения/возрождения останков skinloot не нужен
Logs("Add skinloot for Core Hound (Molten Core): %d loots");


MyOP("UPDATE creature_template JOIN creature ON id=entry SET mechanic_immune_mask=mechanic_immune_mask&~(0x20A0080|CASE WHEN type=1/*Beast*/ THEN 2+16+64+1024+4096 WHEN type=2/*Dragonkin*/ THEN 2+64+1024+4096 WHEN type=4/*Elemental*/ THEN 64+1024+2048+4096 WHEN type=5/*Giant*/ THEN 2+1024+4096 WHEN type=7/*Humanoid*/ THEN 2+16+64+1024+2048+4096+8192+0x24000000 ELSE 2+64+1024+2048+4096 END) WHERE rank<=1 AND (entry IN (12265/*Lava Spawn*/) OR map IN (532,568, 309,509, 534,544,548,550,564,565,580, 249,409,469,531,533, 603,615,616,624,631,649,724))");
// не меняет иммунитет к Charm, Polymorph, Sleep, Distract, Disarm, Bleed
Logs("Remove most immunities from non-boss raid creatures: %d creatures");


$count = MyRUN("
UPDATE creature_template LEFT JOIN creature ON id=entry SET minlevel= 1, maxlevel=60, minhealth= 1000, curhealth= 1000, maxhealth=60000, faction_A=32, faction_H=32, minrangedmg=0, maxrangedmg=0, unit_flags=4, armor=0,    Civilian=0, flags_extra=2|64, AIName='EventAI', mechanic_immune_mask=0x804012 WHERE entry IN (4952,5652); -- Theramore Combat Dummy, Undercity Practice Dummy
UPDATE creature_template LEFT JOIN creature ON id=entry SET minlevel=61, maxlevel=63, minhealth=61000, curhealth=61000, maxhealth=63000, faction_A=32, faction_H=32, minrangedmg=0, maxrangedmg=0, unit_flags=4, armor=4691, Civilian=0, flags_extra=2|64, AIName='EventAI', mechanic_immune_mask=0x3CCB3F5B/*all except Disarm Grip Pacify Bleed Infected Interrupt*/, resistance2=100/*Fire*/, resistance3=200/*Nature*/, resistance4=300/*Frost*/, resistance5=250/*Shadow*/, resistance6=150/*Arcane*/, rank=1 WHERE entry=16211; -- Naxxramas Combat Dummy
INSERT IGNORE creature_ai_scripts SET id=495201, creature_id=4952, event_type=1, action1_type=21, comment='Theramore Combat Dummy - Prevent Combat Movement on Spawn';
INSERT IGNORE creature_ai_scripts SET id=565201, creature_id=5652, event_type=1, action1_type=21, comment='Undercity Practice Dummy - Prevent Combat Movement on Spawn';
INSERT IGNORE creature_ai_scripts SET id=1621101, creature_id=16211, event_type=1, action1_type=21, comment='Naxxramas Combat Dummy - Prevent Combat Movement on Spawn';
");
// UNIT_FLAG_DISABLE_MOVE(4) is not really supported by cMangos core, but it signals to use unmodified respawn time
Logs("Make combat dummies usable: %d rows" );


MyOP("UPDATE creature_template SET armor=15000 WHERE entry=1842");
Logs("Protect Highlord Taelan Fordring from premature death with increased (15000) armor: %d creatures");

// Weaken: одиночное прохождение боя с 42 драконидами в BWL
MyOP("UPDATE creature_ai_scripts SET action1_param1=15089/*Frost Shock*/ /*22746 Cone of Cold, action1_param2=0*/, action1_param3=2/*cast triggered-no mana req.*/ WHERE creature_id=14261 AND action1_param1=22559");
Logs("Weaken/remove `Brood Power: Blue` mana drain from Nefarian's Blue Drakonids (BWL): %d rows");

// if (USE_CONDITIONS) {
// $count = 0;
// $res = MyOP("SELECT c.guid, c.spawntimesecs, cl.master_guid FROM creature AS c LEFT JOIN creature_linking AS cl USING(guid) WHERE map=230/*BRD*/ AND id=8901/*Anvilrage Reservist*/");
// $masterGuid = MyVAL("SELECT guid FROM creature WHERE id=9938/*Magmus*/");
// while($obj = mysql_fetch_object($res)) {
//   if (isset($obj->master_guid) || $obj->spawntimesecs > 60)  continue;
//   MyOP("INSERT creature_linking SET guid=$obj->guid, master_guid=$masterGuid, flag=1024");
//   $count += mysql_affected_rows();
// }
// Чтобы это работало, надо ограничить сферу действия Corpse.Decay.* = 7200 из mangos.conf
// Logs("Link Anvilrage Reservists to Magmus, so no more respawns after defeated him (BRD): %d creatures" );
// }

}


function TweakCreatureAllocation()
{
global $count; PrintHeader(__FUNCTION__);

$count = FIRST_RUN == false ? 0 :
MyRUN("
SET @GUID=(SELECT (MAX(guid) DIV 10000 + 1)*10000 FROM creature);
INSERT creature SET guid=@GUID, id=10716, map=1, position_x=16208, position_y=16445, position_z=151.95, orientation=3.17, spawntimesecs=180, spawndist=10, curhealth=64, curmana=0, MovementType=1;
");
Logs("Add a second critter (GM Island) to set stable starting value for new GUIDs dynamically added into `creature` table: %d creatures" );


// Увеличить кол-во Mottled Razormaw raptors, чтобы их было достаточно для быстрого выполнения задания
MyOP("UPDATE creature SET id=1023,curhealth=(SELECT minhealth FROM creature_template WHERE entry=1023) WHERE guid IN (10968,11031) AND id=1022");
Logs("Convert Mottled Scytheclaw to Mottled Razormaw: %d guids");

// Увеличить кол-во Syndicate Footpad за счёт Syndicate Thief, чтобы было достаточно для быстрого выполнения задания
MyOP("UPDATE creature SET id=2240,curhealth=(SELECT minhealth FROM creature_template WHERE entry=2240) WHERE guid IN (16756) AND id=2241");
Logs("Convert Syndicate Thief to Syndicate Footpad: %d guids");


if (USE_CONDITIONS) {
$t = 7*24*3600; // 7 дней времени работы сервера, или иначе надо ставить 14 дней реального времени
$count = MyVAL("SELECT guid FROM creature WHERE id IN (14457, 14461, 14464, 14454)") !== null ? 0 :
MyRUN("
INSERT creature (id,map,position_x,position_y,position_z,orientation,spawntimesecs,spawndist,curhealth,curmana,MovementType) VALUES
(14454, 1,   -6582,  1539.14,   2.156, 3.381, $t, 25, 15772, 0, 1), -- The Windreaver (Silithus)
(14455, 1, -6608.49, 1584.09,   5.878, 4.075, $t,  0,  2903, 0, 0), -- Whirling Invader x 5
(14455, 1, -6609.71, 1580.53,   5.894, 3.622, $t,  0,  2903, 0, 0),
(14455, 1, -6615.18, 1576.74,   6.062, 3.466, $t,  0,  2903, 0, 0),
(14455, 1, -6617.96, 1580.36,   6.299, 5.392, $t,  0,  2903, 0, 0),
(14455, 1, -6611.40, 1577.23,   5.921, 2.660, $t,  0,  2903, 0, 0),
/* -- too far distances, creature linking not working
(14455, 1,-6509.86,  1600.66, 119.975, 3.452, $t,  0,  2903, 0, 0),
(14455, 1,-6521.91,  1606.61,  88.493, 4.057, $t,  0,  2903, 0, 0),
(14455, 1,-6545.92,  1630.69,  40.048, 3.626, $t,  0,  2903, 0, 0),
(14455, 1,-6549.12,  1668.98,  36.775, 3.106, $t,  0,  2903, 0, 0),
(14455, 1,-6506.62,  1580.40,  42.567, 4.747, $t,  0,  2903, 0, 0),
*/
(14457, 1, 6565.35,    -4219, 658.379, 1.721, $t,  0, 15144, 0, 0), -- Princess Tempestria (Winterspring)
(14458, 1,  6585.2,    -4205,   658.3, 3.780, $t, 35,  2699, 0, 1), -- Watery Invader x 5
(14458, 1,    6557,    -4193,  658.46, 4.950, $t, 35,  2699, 0, 1),
(14458, 1,    6538,    -4223,   658.6, 0.000, $t, 35,  2699, 0, 1),
(14458, 1,    6561,    -4244,  658.28, 1.400, $t, 25,  2699, 0, 1),
(14458, 1,    6578,    -4241,  658.28, 2.000, $t, 25,  2699, 0, 1),
(14461, 1,-7215.76, -1320.55,-154.822, 3.687, $t,  0, 14881, 0, 0), -- Baron Charr (Un'goro), orig.xyz: -7190.04, -1302.7, -184.241
(14460, 1,-7190.09, -1399.43,-194.095, 4.773, $t,  3,  2505, 0, 1), -- Blazing Invader x 5
(14460, 1,-7198.08, -1369.58,-175.068, 3.195, $t,  3,  2505, 0, 1),
(14460, 1,-7210.73, -1377.11,-191.208, 3.919, $t,  3,  2505, 0, 1),
(14460, 1,-7222.87, -1288.88,-160.840, 1.426, $t,  3,  2505, 0, 1),
(14460, 1,-7240.04, -1290.69,-203.584, 2.779, $t,  3,  2505, 0, 1),
(14464, 1,    4625,    -7250,  167.78, 2.060, $t,  7, 14317, 0, 1), -- Avalanchion (Azshara), orig.xyz: 4487.17,   -7316,   93.526
(14462, 1, 4620.20, -7273.45, 147.109, 5.166, $t, 15,  2728, 0, 1), -- Thundering Invader x 6
(14462, 1, 4610.20, -7267.59, 148.503, 3.869, $t, 15,  2728, 0, 1),
(14462, 1, 4600.88, -7257.34, 148.322, 3.177, $t, 10,  2728, 0, 1),
(14462, 1, 4586.99, -7223.06, 141.709, 2.673, $t,  5,  2728, 0, 1),
(14462, 1, 4597.85, -7206.90, 143.255, 2.524, $t,  5,  2728, 0, 1),
(14462, 1, 4607.68, -7222.58, 158.232, 2.382, $t,  5,  2728, 0, 1);
",
"UPDATE creature_template SET minhealth=2699, maxhealth=2871 WHERE entry=14458; -- Watery Invader YTDB",
"UPDATE creature_template SET speed_walk=2.0, speed_run=2.0, flags_extra=flags_extra|0x4000 WHERE entry=14455; -- Whirling Invader",
"UPDATE creature_template SET scale=2.5 WHERE entry IN (14454,14461,14464); -- leaders bigger than servants",
"
INSERT IGNORE creature_linking_template (entry,map,master_entry,flag,search_range) VALUES
(14455, 1, 14454, 1+2+4+16+128+1024+4096, 200), -- Whirling Invader <=> The Windreaver
(14458, 1, 14457, 1+2+4+16+128+1024+4096, 200), -- Watery Invader <=> Princess Tempestria
(14460, 1, 14461, 1+2+4+16+128+1024+4096, 200), -- Blazing Invader <=> Baron Charr
(14462, 1, 14464, 1+2+4+16+128+1024+4096, 200); -- Thundering Invader <=> Avalanchion
"
);
Logs("Add creatures of Elemental Invasions: %d rows" );
// NB! при изменении БД изменяются guid'ы, и периоды перерождения динамически
// добавляемых существ не соблюдаются при загрузке сохранённых игр
}

if (USE_CONDITIONS) {
MyOP("DELETE FROM creature_linking_template WHERE entry IN (14482,14483) AND master_entry=14501 AND map=429");
// Смысл в том, что стандартный сценарий не реализуется (Jee'vee не ставит
// ритуальные предметы), да его и нереально выполнить в одиночку... зато
// придётся разбираться с призванными демонами (AoE против Imp'ов, ступеньки
// помогают как барьер для pathfinding)
Logs("Do not despawn Xorothian demons before enabling summoning of Warlock epic mount (Dire Maul): %d rows");
}

}


function TweakCreatureRespawnTimes()
{
global $count; PrintHeader(__FUNCTION__);

MyOP("UPDATE creature SET spawntimesecs=9*24*3600 WHERE spawntimesecs=259200 AND map IN (309,509)");
Logs("Prevent boss respawn in ZG and AQ20 if instance exists longer than 3 days: %d creatures");


global $creature_classic_rare;
MyOP("UPDATE creature SET spawntimesecs=ROUND(24 + 24*RAND(guid))*IF(id = 14479/*Twilight Lord Everun*/, 3600/10, 3600) WHERE spawntimesecs < 24*3600 AND spawntimesecs>0 AND id IN (SELECT entry FROM creature_template WHERE name IN ($creature_classic_rare)) AND id!=14479");
Logs("Respawn time 24..48 hours for classic Rare creatures: %d guids");

MyOP("UPDATE creature JOIN creature_template ON entry=id SET spawntimesecs=ROUND(10 + 6*RAND(guid))*3600 WHERE RacialLeader!=0 AND spawntimesecs < 10*3600 AND spawntimesecs>0");
Logs("Respawn time 10..16 hours for Racial Leaders (high rank Honor farm limit): %d guids");

MyOP("UPDATE creature JOIN creature_template ON entry=id SET spawntimesecs=ROUND(22 + 2*RAND(guid))*3600 WHERE entry IN (5319,5317,5320,5312,12497, 12475,12476,12474,5314,12498, 12479,12478,12477,5718,12496) AND spawntimesecs < 24*3600 AND spawntimesecs>0");
Logs("Respawn time 22..24 hours for minion dragons around Nightmare Portals (Hinterlands,Ashenvale,Feralas): %d guids");


//MyOP("UPDATE creature SET spawntimesecs=200000 WHERE spawntimesecs>200000 AND map IN (33,34,36,43,47,48,70,90,109,129,189,209,229,230,269,289,329,349,389,429,540,542,543,545,546,547,552,553,554,555,556,557,558,560,574,575,576,578,585,595,599,600,601,602,604,608,619,632,650,658,668)");
//Logs("Limit respawn times in 5-man Instances to ~56 hours for faster auto resets: %d guids");
// Уже не нужно в связи с patch'ем ядра, устраняющим зависимость времени сброса подземелья от времён возрождения существ

MyOP("UPDATE creature JOIN creature_template ON entry=id SET spawntimesecs=spawntimesecs+100000 WHERE spawntimesecs<100000 AND spawntimesecs>0 AND type IN (1,2,3,4,5,6,7,9,10) AND Civilian=0 AND (unit_flags&4)=0 AND (flags_extra&128)=0 AND map IN (33,34,36,43,47,48,70,90,109,129,189,209,229,230,269,289,329,349,389,429,540,542,543,545,546,547,552,553,554,555,556,557,558,560,574,575,576,578,585,595,599,600,601,602,604,608,619,632,650,658,668) AND NOT entry IN (8901/*Anvilrage Reservist*/,9956/*Shadowforge Flame Keeper*/)");
Logs("Increase respawn times in 5-man Instances: %d guids");

MyOP("UPDATE creature JOIN creature_template ON entry=id SET spawntimesecs=spawntimesecs+100000 WHERE spawntimesecs<100000 AND spawntimesecs>0 AND type IN (1,2,3,4,5,6,7,9,10) AND Civilian=0 AND (unit_flags&4)=0 AND (flags_extra&128)=0 AND map IN (532,568, 309,509, 534,544,548,550,564,565,580, 249,409,469,531,533, 603,615,616,624,631,649,724) AND NOT entry IN (14022,14023,14024,14025/*BWL corrupted whelps*/)");
Logs("Increase respawn times in raid instances: %d guids");

MyOP("UPDATE creature JOIN creature_template ON entry=id SET spawntimesecs=spawntimesecs+100000 WHERE spawntimesecs<100000 AND spawntimesecs>0 AND type IN (1,2,3,4,5,6,7,9,10) AND map=30");
Logs("Increase respawn times in Alterac Valley: %d guids");

}


function TweakCreatureDmgHP()
{
global $count; PrintHeader(__FUNCTION__);

MyOP("UPDATE creature, creature_template SET curhealth = minhealth, curmana = minmana WHERE id = entry AND (RegenHealth&1)!=0");
Logs("Sync'ed creature curhealth/curmana with template values: %d guids");

if (! FIRST_RUN) return;


$pet_entries = array();
$res = MYOP("SELECT DISTINCT creature_entry FROM pet_levelstats");
while($obj = mysql_fetch_object($res))  $pet_entries[] = $obj->creature_entry;


$res = MyOP("SELECT id,map,curhealth FROM creature ORDER BY map ASC");

while($obj = mysql_fetch_object($res)) {
  $curhealth[$obj->id] = $obj->curhealth;
  if (isset($crea_map[$obj->id]) and $crea_map[$obj->id] != $obj->map) {
      $namer = MyROWobj("SELECT name,type,minhealth FROM creature_template WHERE entry=$obj->id");
      if (@$namer->type != 8 or @$namer->minhealth > 120)
         echo "WARNING! Creature \"$namer->name\" collision for maps ".$crea_map[$obj->id]." and $obj->map\n";
  }
  $crea_map[$obj->id] = $obj->map;
}


$res = MyOP("
  SELECT entry,name,rank,mindmg,maxdmg,minrangedmg,maxrangedmg,minhealth,maxhealth,minlevel,maxlevel
  FROM creature_template
  WHERE NOT (flags_extra & 128) AND NOT unit_flags IN (0x2008300, 0x2000300)
  ORDER BY name ASC
");
// ORDER BY (mindmg+maxdmg)/2/maxlevel ASC
// ... and (mindmg+maxdmg)/2/IF(minlevel<maxlevel,maxlevel,minlevel) > 5

$nTotal = 0;
$nTweaked = 0;

while($obj = mysql_fetch_object($res)) {

++$nTotal;

$health_div = 1;
$dmg_div = 1;
$map = isset($crea_map[$obj->entry]) ? $crea_map[$obj->entry] : -1;
$health = ($obj->minhealth + $obj->maxhealth)/2; // = isset($curhealth[$obj->entry]) ? $curhealth[$obj->entry] : 0;

if (in_array($obj->entry, array(
    7846/*Teremus the Devourer*/,1284/*Archbishop Benedictus*/,12126/*Lord Tirion Fordring*/,14941/*High Priestess Jeklik Transform Visual*/,15382/*Fandral Staghelm(not used)*/,15410/*Anachronos Dragon Form*/,15411/*Arygos Dragon Form*/,15412/*Caelestrasz Dragon Form*/,15413/*Merithra Dragon Form*/,15427/*Merithra's Wake*/,15507/*Buru the Gorger Transform Visual*/,15633/*Tyrande(not used)*/,16387/*Atiesh*/,
    11447/*Mushgog*/,11497/*The Razza*/,11498/*Skarr the Unbreakable*/,
    5764/*Guardian of Blizzard*/,10942/*Nessy*/
    )))
    // неизменяемые существа: 1) ранга BOSS, 2) RareElite, 3) прочие
    continue;
elseif (in_array($map, array(33,34,36,43,47,48,70,90,109,129,189,209,230,269,289,329,349,389,429,540,542,543,545,546,547,552,553,554,555,556,557,558,560,574,575,576,578,585,595,599,600,601,602,604,608,619,632,650,658,668, 229))
        or in_array($obj->entry, array(
        11121/*Black Guard Swordsmith*/,10813/*Balnazzar*/,10439/*Ramstein the Gorger*/,
        1853/*Darkmaster Gandling*/,
        16042/*Lord Valthalak*/,10339/*Gyth*/,10429/*Warchief Rend Blackhand*/,15776/*Christmas Warchief Rend Blackhand*/,15796/*Christmas Goraluk Anvilcrack*/
       ))) {
    // 5-man dungeons incl. Blackrock Spire(229)
    continue;
}
elseif (in_array($map, array(532,568))) { // 10-man TBC raids (Karazhan, Zul'Aman)
    $health_div = ($obj->rank == 3) ?  2 : 1;
    $dmg_div    = ($obj->rank == 3) ?  2 : 1;
    printf("raid(10) %s: %s\n", rankstr($obj->rank), $obj->name);
}
elseif (in_array($map, array(309,509))
        or in_array($obj->entry, array(
        14515/*High Priestess Arlokk*/ /*,15101 Zulian Prowler*/ /*,15068 Zulian Guardian*/,14986/*Shade of Jin'do*/,14988/*Ohgan*/,15082/*Gri'lek*/,15083/*Hazza'rah*/,15084/*Renataki*/,15085/*Wushoolay*/,15114/*Gahz'ranka*/,15041/*Spawn of Mar'li*/,14965/*Frenzied Bloodseeker Bat*/,14884/*Parasitic Serpent*/,15146/*Mad Voidwalker*/,
        15934/*Hive'Zara Hornet*/,15521/*Hive'Zara Hatchling*/,/*15555 Hive'Zara Larva,*/ 15527/*Mana Fiend*/
        )) ) {
    // 20-man Classic raids (Zul'Gurub, AQ20 Ruins of Ahn'Qiraj)
    $health_div = ($obj->rank == 3) ?  4 : 1;
    $dmg_div    = ($obj->rank == 3) ?  2 : 2;
    printf("raid(20) %s: %s\n", rankstr($obj->rank), $obj->name);
}
elseif (in_array($map, array(534,544,548,550,564,565,580))) { // 25-man TBC raids
    $health_div = ($obj->rank == 3) ?  5 : 2;
    $dmg_div    = ($obj->rank == 3) ?  3 : 2;
    printf("raid(25) %s: %s\n", rankstr($obj->rank), $obj->name);
}
elseif (in_array($map, array(249,409,469,531,533)) or in_array($obj->entry, array(
        11262/*Onyxian Whelp*/,
        12018/*Majordomo Executus*/,11502/*Ragnaros*/,12265/*Lava Spawn*/,12143/*Son of Flame*/,
        11583/*Nefarian*/,14101/*Enraged Felguard*/, 14261/*Blue Drakonid*/,14262/*Green Drakonid*/,14263/*Bronze Drakonid*/,14264/*Red Drakonid*/,14265/*Black Drakonid*/,14302/*Chromatic Drakonid*/,14605/*Bone Construct*/,
        15517/*Ouro*/,15630/*Spawn of Fankriss*/,15622/*Vekniss Borer*/,15621/*Yauj Brood*/,
        15989/*Sapphiron*/,16775/*Spirit of Mograine*/,16776/*Spirit of Blaumeux*/,16777/*Spirit of Zeliek*/,16778/*Spirit of Korth'azz*/,16441/*Guardian of Icecrown*/,16783/*Plague Slime (Blue)*/,16784/*Plague Slime (Red)*/,16785/*Plague Slime (Green)*/,16127/*Spectral Trainee*/,16148/*Spectral Deathknight*/,16149/*Spectral Horse*/,16150/*Spectral Rider*/,16124/*Unrelenting Trainee*/,16125/*Unrelenting Deathknight*/,16126/*Unrelenting Rider*/,
        15302/*Shade of Taerar*/ /*,15260 Demented Druid Spirit*/
       ))) {
    // 40-man Classic raids (Onyxia, MC, BWL, AQ40, Naxxramas)
    $health_div = ($obj->rank == 3) ? 10 : 5;
    $dmg_div    = ($obj->rank == 3) ?  3 : 2;
    printf("raid(40) %s: %s\n", rankstr($obj->rank), $obj->name);
}
elseif (in_array($obj->entry, array(11664/*Flamewaker Elite*/,11663/*Flamewaker Healer*/) )) {
    // 40-man Classic raids - weaken too strong
    $health_div = 10;
    $dmg_div    = 2;
    printf("raid(40) further weaken halving HP %s: %s\n", rankstr($obj->rank), $obj->name);
}
elseif (in_array($map, array(603,615,616,624,631,649,724))) { // 10/25-man WotLK raids
    $health_div = ($obj->rank == 3) ?  4 : 2;
    $dmg_div    = ($obj->rank == 3) ?  2 : 1;
    printf("raid(10/25) %s: %s\n", rankstr($obj->rank), $obj->name);
}
elseif (in_array($obj->entry, $pet_entries)) {
    $dmg_div = 0.5;
    echo "pet dmg-boost: $obj->name\n";
}
elseif ($map == -1 and in_array($obj->entry, array(14460,14462,14458,14455 /*elemental invaders*/,
        698/*Bloodscalp Tiger*/,756/*Skullsplitter Panther*/,10979/*Scarlet Hound*/,6412/*Skeleton[by Sylvanas]*/))) {
    $dmg_div = 0.5;
    echo "mapless dmg-boost: $obj->name\n";
}
elseif ($map == -1) {
    if ($obj->rank != 3 or $obj->maxlevel < 60 or $health < 10000)
        continue;

    printf("mapless %s: %s, HP %d", rankstr($obj->rank), $obj->name, $health);
    if ($health > 40000)  {
        $health_div = $health / (40000 + sqrt(($health-40000)/10)*200); // 100k => 55k, 2000k => 128k
        printf(" =>%d", $health / $health_div);
    }
    if (!in_array($obj->entry, array(
        15305/*Lord Skwol*/,15204/*High Marshal Whirlaxis*/,15203/*Prince Skaldrenox*/,15205/*Baron Kazum*/,
        14435/*Prince Thunderaan*/
        ))) {
        $dmg_div = 2;
        $avdmg = ($obj->mindmg + $obj->maxdmg)/2;
        printf("  DMG %d => %d", $avdmg, $avdmg / $dmg_div);
    }
    echo "\n";
}
elseif (in_array($obj->rank, array(0,2,4)) and $obj->maxdmg < 20*$obj->maxlevel) {
    // 1) удвоить урон от несильных статических неэлитных существ в
    // верхнем мире, но так, что оно всё равно остаётся меньше, чем от элитных;
    // также и количество жизни у них по-прежнему меньше
    // 2) удвоить урон от Rare и Rare Elite существ; поскольку многие
    // неэлитные Rare обладают повышенными показателями, то они могут стать
    // сильнее регулярных элитных
    $dmg_div = 0.5;
    echo "overworld dmg-boost: $obj->name\n";
}
elseif ($obj->rank == 3 or $health > 120000) { // overworld Boss or Boss-like uber-Elite
    printf("overworld %s: %s, HP %d", $obj->rank==3 ? "BOSS":"BOSS-LIKE", $obj->name, $health);
    if ($health > 120000) {
        $health_div = $health / (100000 + sqrt(($health-100000)/10)*400); // 200k=>140k, 800k=>205k
        printf(" =>%d", $health / $health_div);
    }
    if ($obj->rank == 3 and !in_array($obj->entry, array(
       15192/*Anachronos*/,
       3516/*Arch Druid Fandral Staghelm*/,7937/*High Tinker Mekkatorque*/,1748/*Highlord Bolvar Fordragon*/,2784/*King Magni Bronzebeard*/,7999/*Tyrande Whisperwind*/,
       1284/*Archbishop Benedictus*/,4968/*Lady Jaina Proudmoore*/,
       3057/*Cairne Bloodhoof*/,10181/*Lady Sylvanas Windrunner*/,4949/*Thrall*/,10540/*Vol'jin*/,
       )))
        $dmg_div = 2;
    echo "\n";
}
else continue;

$affected = 0;

if ($health > 0 and $health_div != 1) {
   MyOP("UPDATE creature SET curhealth=IF(curhealth DIV $health_div > 1, curhealth DIV $health_div, 1) WHERE id=$obj->entry");
   $affected += mysql_affected_rows();
}

$obj->minhealth = max(1, intval($obj->minhealth / $health_div));
$obj->maxhealth = max(1, intval($obj->maxhealth / $health_div));

/*
// изменённые значения величин урона приходилось записывать в БД раньше,
// а теперь в cMangos-ядре dmg_multiplier трактуется как универсальный
// множитель для наносимого существами физического и магического урона
$obj->mindmg = max(1, intval($obj->mindmg / $dmg_div));
$obj->maxdmg = max(1, intval($obj->maxdmg / $dmg_div));
$obj->minrangedmg = max(1, intval($obj->minrangedmg / $dmg_div));
$obj->maxrangedmg = max(1, intval($obj->maxrangedmg / $dmg_div));
*/

MyOP("
 UPDATE creature_template
 SET minhealth=$obj->minhealth,maxhealth=$obj->maxhealth,
     dmg_multiplier=1.0/$dmg_div /* mindmg=$obj->mindmg,maxdmg=$obj->maxdmg, minrangedmg=$obj->minrangedmg,maxrangedmg=$obj->maxrangedmg */,
     mingold=mingold/$health_div, maxgold=maxgold/$health_div
 WHERE entry=$obj->entry
");
$affected += mysql_affected_rows();

if ($affected > 0)  ++$nTweaked;

}
Logs("%d of %d creatures tweaked", $nTweaked, $nTotal);

}


///////////////////////// MAIN CODE BLOCK

$countTotal = 0;

FixGeneral();
FixNPC();
FixGameobjects();
FixGameobjectAllocation();
FixQuests();
FixTooLowMinLevelsOfNextQuestsInChains();
FixItems();
FixQuestLoot();
FixLoot();
FixMissingCreatures();
FixCreaturePlacement();
FixCreatureOnKillReputation();
FixCreatures();
FixCreatureScripts();
TweakGeneral();
TweakNPC();
TweakItems();
TweakQuests();
TweakOnKillReputations();
TweakGameobjectRespawnTimes();
TweakCreatures();
TweakCreatureAllocation();
TweakCreatureRespawnTimes();
TweakCreatureDmgHP();

printf("\nPatches {%d} applied in %.2f seconds\n", $countTotal, microtime(true) - $startTime);

?>
