'use strict';

const AWS = require('aws-sdk');
const _h = require('highland');

const ecs = new AWS.ECS({region: process.env.AWS_REGION || 'us-east-1'});

let familyPrefix = null;

if (process.argv.length >= 3){
  familyPrefix = process.argv[2];
} else {
  return(console.error('Error: No familyPrefix provided. Usage: node sctiptName familyPrefix'));
}

const checkFamily = (familyPrefix, callback) => {
  ecs.listTaskDefinitionFamilies({status: 'ACTIVE', familyPrefix}, (err, data) => {
    if (err) {return callback(err);}
    if (!(data && data.families && data.families.indexOf(familyPrefix) > -1)) {
      return callback(new Error('taskDefinitionFamily not found'));
    }
    return callback();
  });
};

const deregisterAll = (familyPrefix, callback) => {
  let nextToken = null;
  _h((push, next) => {
    const params = {
      familyPrefix,
      nextToken
    };

    ecs.listTaskDefinitions(params, function(err, data) {
      if (err) {
        push(err);
        return next();
      }

      if (data && data.taskDefinitionArns) {
        push(null, data.taskDefinitionArns);
      }
      if (data.nextToken) {
        nextToken = data.nextToken;
        return next();
      };
      return push(null, _h.nil); //end stream
    });
  })
  .flatten()
  .flatMap(_h.wrapCallback((taskDefinition, callback) => {
    ecs.deregisterTaskDefinition({taskDefinition}, (err, result) => {
      if (err) {return callback(err);}
      console.log(`${taskDefinition} ${(result && result.taskDefinition && result.taskDefinition.status === 'INACTIVE') ? 'deregistered' : 'check again <--' }`);
      return callback();
    });
  }))
  .ratelimit(20, 15000) //just a guess - can't find documentation about actual rate limit
  .collect()
  .toCallback(callback);
};

checkFamily(familyPrefix, (err) => {
  if (err) {
    console.error(err);
    process.exit(1);
  }
  deregisterAll(familyPrefix, (err) => {
    if (err) {
      console.error(err);
      process.exit(1);
    }
    console.log('done');
    process.exit();
  });
});